Example #1
1
def structured_grid_fromfile(f, self):
    l = common._getline(f).split(" ")
    assert l[0].strip().lower() == "dimensions"
    dims = list(map(int, l[1:]))
    assert len(dims) == 3
    l = common._getline(f)
    k, n, datatype = [s.strip().lower() for s in l.split(" ")]
    if k != "points":
        raise ValueError("expected points but got %s" % (repr(k)))
    n = int(n)
    assert datatype in [
        "bit",
        "unsigned_char",
        "char",
        "unsigned_short",
        "short",
        "unsigned_int",
        "int",
        "unsigned_long",
        "long",
        "float",
        "double",
    ], repr(datatype)
    points = []
    log.debug("\tgetting %s points" % n)
    while len(points) < 3 * n:
        l = common._getline(f)
        points += map(eval, l.split(" "))
    assert len(points) == 3 * n
    return StructuredGrid(dims, points), common._getline(f)
Example #2
1
def check(rule, ctxt, target=None, do_raise=True, exc=exceptions.Forbidden):
    creds = ctxt.to_dict()
    target = target or {}

    try:
        result = _ENFORCER.enforce(rule, target, creds, do_raise, exc)
    except Exception:
        result = False
        raise
    else:
        return result
    finally:
        extra = {"policy": {"rule": rule, "target": target}}

        if result:
            LOG.audit(
                _("Policy check succeeded for rule '%(rule)s' " "on target %(target)s")
                % {"rule": rule, "target": repr(target)},
                extra=extra,
            )
        else:
            LOG.audit(
                _("Policy check failed for rule '%(rule)s' " "on target %(target)s")
                % {"rule": rule, "target": repr(target)},
                extra=extra,
            )
Example #3
1
    def _test_flow_matching_check(self, pkt):
        self.logger.debug("egress:[%s]", packet.Packet(pkt.get(KEY_EGRESS)))
        self.logger.debug("packet_in:[%s]", packet.Packet(pkt.get(KEY_PKT_IN)))

        # receive a PacketIn message.
        try:
            self._wait()
        except TestTimeout:
            return TIMEOUT

        assert len(self.rcv_msgs) == 1
        msg = self.rcv_msgs[0]
        assert isinstance(msg, ofproto_v1_3_parser.OFPPacketIn)
        self.logger.debug(
            "dpid=%s : receive_packet[%s]", dpid_lib.dpid_to_str(msg.datapath.id), packet.Packet(msg.data)
        )

        # check the SW which sended PacketIn and output packet.
        pkt_in_src_model = self.tester_sw if KEY_EGRESS in pkt else self.target_sw
        model_pkt = pkt[KEY_EGRESS] if KEY_EGRESS in pkt else pkt[KEY_PKT_IN]

        if msg.datapath.id != pkt_in_src_model.dp.id:
            pkt_type = "packet-in"
            err_msg = "SW[dpid=%s]" % dpid_lib.dpid_to_str(msg.datapath.id)
        elif msg.reason != ofproto_v1_3.OFPR_ACTION:
            pkt_type = "packet-in"
            err_msg = "OFPPacketIn[reason=%d]" % msg.reason
        elif repr(msg.data) != repr(model_pkt):
            pkt_type = "packet"
            err_msg = self._diff_packets(packet.Packet(model_pkt), packet.Packet(msg.data))
        else:
            return TEST_OK

        raise TestFailure(self.state, pkt_type=pkt_type, detail=err_msg)
Example #4
1
    def test_add_filter(self):
        self.assertEqual(len(self.bsq.query_filter), 0)

        self.bsq.add_filter(SQ(foo="bar"))
        self.assertEqual(len(self.bsq.query_filter), 1)

        self.bsq.add_filter(SQ(foo__lt="10"))

        self.bsq.add_filter(~SQ(claris="moof"))

        self.bsq.add_filter(SQ(claris="moof"), use_or=True)

        self.assertEqual(
            repr(self.bsq.query_filter),
            "<SQ: OR ((foo__content=bar AND foo__lt=10 AND NOT (claris__content=moof)) OR claris__content=moof)>",
        )

        self.bsq.add_filter(SQ(claris="moof"))

        self.assertEqual(
            repr(self.bsq.query_filter),
            "<SQ: AND (((foo__content=bar AND foo__lt=10 AND NOT (claris__content=moof)) OR claris__content=moof) AND claris__content=moof)>",
        )

        self.bsq.add_filter(SQ(claris="wtf mate"))

        self.assertEqual(
            repr(self.bsq.query_filter),
            "<SQ: AND (((foo__content=bar AND foo__lt=10 AND NOT (claris__content=moof)) OR claris__content=moof) AND claris__content=moof AND claris__content=wtf mate)>",
        )
Example #5
1
    def test_syntactic(self):
        sentences = list(SyntacticExtractor(
            [{'bio': u'this is part a1, and this is part a2', 'url': 'www.example.org', 'name': 'abc def'}],
            'bio', 'sentences', 'en', {'be': ['is', 'are']}, self.match_base_form
        ).extract(1))

        self.assertEqual(len(sentences), 2)

        missing_parts = {'a1', 'a2'}
        for sentence in sentences:
            self.assertIn('url', sentence)
            self.assertIn('text', sentence)
            self.assertIn('lu', sentence)
            self.assertEqual(sentence['lu'], 'be')

            for p in missing_parts:
                if p in sentence['text']:
                    self.assertEqual(sentence['text'], 'this is part ' + p)
                    missing_parts.remove(p)
                    break
            else:
                self.fail('Extracted unexpected sentence: %s' % repr(sentence))

        if missing_parts:
            self.fail('Did not find parts: %s' % repr(missing_parts))
Example #6
1
    def _parseStatement(self, s):
        statement_re = re.compile("(.*)=(.*)")
        value_list_re = re.compile("([^,]*),?")
        if not statement_re.match(s):
            print "syntax error (statement match): %s" % repr(s)
            return
        statement_split = statement_re.split(s)
        if len(statement_split) != 4:
            print "syntax error (statement split): %s" % repr(s)
            return
        (foo, name, value, bar) = statement_split
        value_split = value_list_re.split(value)
        if len(value_split) < 2 or len(value_split) % 2 != 1:
            print "syntax error (value split): %s" % (repr(value_split))
            return
        try:
            value_array = []
            value_split.reverse()
            value_split.pop()
            while len(value_split) != 0:
                value_array.append(value_split.pop())
                value_split.pop()
        except:
            print traceback.print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
            print "syntax error (value to array): %s" % (repr(value_split))
            return

        return (name, value_array)
Example #7
0
    def test_various_ops(self):
        # This takes about n/3 seconds to run (about n/3 clumps of tasks,
        # times about 1 second per clump).
        NUMTASKS = 10

        # no more than 3 of the 10 can run at once
        sema = threading.BoundedSemaphore(value=3)
        mutex = threading.RLock()
        numrunning = Counter()

        threads = []

        for i in range(NUMTASKS):
            t = TestThread("<thread %d>" % i, self, sema, mutex, numrunning)
            threads.append(t)
            self.assertEqual(t.ident, None)
            self.assertTrue(re.match("<TestThread\(.*, initial\)>", repr(t)))
            t.start()

        if verbose:
            print("waiting for all tasks to complete")
        for t in threads:
            t.join(NUMTASKS)
            self.assertTrue(not t.is_alive())
            self.assertNotEqual(t.ident, 0)
            self.assertFalse(t.ident is None)
            self.assertTrue(re.match("<TestThread\(.*, stopped -?\d+\)>", repr(t)))
        if verbose:
            print("all tasks done")
        self.assertEqual(numrunning.get(), 0)
Example #8
0
def test_path_info():
    map = Mapper(explicit=False)
    map.minimization = True
    map.connect("myapp/*path_info", controller="myapp")
    map.connect("project/*path_info", controller="myapp")
    map.create_regs(["content", "myapp"])

    app = TestApp(RoutesMiddleware(simple_app, map))
    res = app.get("/")
    assert "matchdict items are []" in res

    res = app.get("/myapp/some/other/url")
    print(res)
    assert (
        b"matchdict items are [('action', "
        + repr(u"index").encode()
        + b"), ('controller', "
        + repr(u"myapp").encode()
        + b"), ('path_info', 'some/other/url')]"
        in res
    )
    assert "'SCRIPT_NAME': '/myapp'" in res
    assert "'PATH_INFO': '/some/other/url'" in res

    res = app.get(
        "/project/pylonshq/browser/pylons/templates/default_project/+package+/pylonshq/browser/pylons/templates/default_project/+package+/controllers"
    )
    print(res)
    assert "'SCRIPT_NAME': '/project'" in res
    assert (
        "'PATH_INFO': '/pylonshq/browser/pylons/templates/default_project/+package+/pylonshq/browser/pylons/templates/default_project/+package+/controllers'"
        in res
    )
Example #9
0
def printExceptionDetailsToStdErr():
    """
        No idea if all of this is needed, infact I know it is not. But for now why not.
        Taken straight from the python manual on Exceptions.
        """
    import sys, traceback

    exc_type, exc_value, exc_traceback = sys.exc_info()
    print2err("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print2err("*** print_exception:")
    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
    print2err("*** print_exc:")
    traceback.print_exc()
    print2err("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print2err(str(formatted_lines[0]))
    print2err((formatted_lines[-1]))
    print2err("*** format_exception:")
    print2err(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    print2err("*** extract_tb:")
    print2err(repr(traceback.extract_tb(exc_traceback)))
    print2err("*** format_tb:")
    print2err(repr(traceback.format_tb(exc_traceback)))
    print2err("*** tb_lineno:" + str(exc_traceback.tb_lineno))
Example #10
0
def test_redirect_middleware():
    map = Mapper(explicit=False)
    map.minimization = True
    map.connect("myapp/*path_info", controller="myapp")
    map.redirect("faq/{section}", "/static/faq/{section}.html")
    map.redirect("home/index", "/", _redirect_code="301 Moved Permanently")
    map.create_regs(["content", "myapp"])

    app = TestApp(RoutesMiddleware(simple_app, map))
    res = app.get("/")
    assert "matchdict items are []" in res

    res = app.get("/faq/home")
    eq_("302 Found", res.status)
    eq_(res.headers["Location"], "/static/faq/home.html")

    res = app.get("/myapp/some/other/url")
    print(res)
    assert (
        b"matchdict items are [('action', "
        + repr(u"index").encode()
        + b"), ('controller', "
        + repr(u"myapp").encode()
        + b"), ('path_info', 'some/other/url')]"
        in res
    )
    assert "'SCRIPT_NAME': '/myapp'" in res
    assert "'PATH_INFO': '/some/other/url'" in res

    res = app.get("/home/index")
    assert "301 Moved Permanently" in res.status
    eq_(res.headers["Location"], "/")
Example #11
0
def test_no_singleton():
    map = Mapper(explicit=False)
    map.minimization = True
    map.connect("myapp/*path_info", controller="myapp")
    map.connect("project/*path_info", controller="myapp")
    map.create_regs(["content", "myapp"])

    app = RoutesMiddleware(simple_app, map, singleton=False)
    env = {"PATH_INFO": "/", "REQUEST_METHOD": "POST", "CONTENT_TYPE": "text/plain;text/html"}

    def start_response_wrapper(status, headers, exc=None):
        pass

    response = b"".join(app(env, start_response_wrapper))
    assert b"matchdict items are []" in response

    # Now a match
    env = {"PATH_INFO": "/project/fred", "REQUEST_METHOD": "POST", "CONTENT_TYPE": "text/plain;text/html"}

    def start_response_wrapper(status, headers, exc=None):
        pass

    response = b"".join(app(env, start_response_wrapper))
    assert (
        b"matchdict items are [('action', "
        + repr(u"index").encode()
        + b"), ('controller', "
        + repr(u"myapp").encode()
        + b"), ('path_info', 'fred')]"
        in response
    )
Example #12
0
    def redis_listen(self):
        print("botworker is listening for messages through Redis")
        while True:
            retval = None

            # blpop returns a tuple
            result = None

            # put it in a loop so that we can still receive KeyboardInterrupts
            # otherwise it will block
            while result is None:
                result = self.redis_conn.blpop(REDIS_KEY_PREFIX, timeout=3)

            key, message_bytes = result
            message = json.loads(message_bytes.decode("utf-8"))
            response_key = message["response_key"]

            try:
                cmd = message["command"]
                args = message.get("args", [])
                kwargs = message.get("kwargs", {})
                method = self.get_method(cmd)
                retval = method(*args, **kwargs)
            except Exception as exc:
                # request_error means the request received through Redis
                # was invalid.
                # response_error means the botworker raised while processing
                # the request.
                retval = {"response_error": repr(exc), "traceback": traceback.format_exc()}
                # don't raise, because then this would crash.
                # logger.exception() will record the full traceback
                logger.exception(repr(exc))
            finally:
                retval_json = json.dumps(retval or {})
                self.redis_conn.rpush(response_key, retval_json)
    def log(self, *msgs):
        log_msg = ""
        nmsgs = len(msgs)
        if nmsgs < 2:
            print >>sys.stderr, "Error message for log", msgs
            return
        for i in range(nmsgs):
            if isinstance(msgs[i], tuple) or isinstance(msgs[i], list):
                log_msg += log_separator
                for msg in msgs[i]:
                    try:
                        log_msg += str(msg)
                    except:
                        log_msg += repr(msg)

                    log_msg += log_separator

            else:
                try:
                    log_msg += str(msgs[i])
                except:
                    log_msg += repr(msgs[i])

                log_msg += log_separator

        if log_msg:
            self._write_log(log_msg)
Example #14
0
def test_array_repr():
    o = 1 + np.finfo(np.longdouble).eps
    a = np.array([o])
    b = np.array([1], dtype=np.longdouble)
    if not np.all(a != b):
        raise ValueError("precision loss creating arrays")
    assert_(repr(a) != repr(b))
Example #15
0
 def on_open(self, info):
     print >> sys.stderr, "Connection Info", repr(self), repr(info.__dict__)
     if "config" not in self.__dict__:
         MyLogger.participants.add(self)
         self.config = copy.deepcopy(models.config["htr"])
     else:
         print >> sys.stderr, "Reusing connection"
Example #16
0
    def test_popitem(self):
        # dict.popitem()
        for copymode in -1, +1:
            # -1: b has same structure as a
            # +1: b is a.copy()
            for log2size in range(12):
                size = 2 ** log2size
                a = {}
                b = {}
                for i in range(size):
                    a[repr(i)] = i
                    if copymode < 0:
                        b[repr(i)] = i
                if copymode > 0:
                    b = a.copy()
                for i in range(size):
                    ka, va = ta = a.popitem()
                    self.assertEqual(va, int(ka))
                    kb, vb = tb = b.popitem()
                    self.assertEqual(vb, int(kb))
                    self.assertFalse(copymode < 0 and ta != tb)
                self.assertFalse(a)
                self.assertFalse(b)

        d = {}
        self.assertRaises(KeyError, d.popitem)
Example #17
0
    def sameValuesAs(self, other):
        # test that sets of attributes exactly match
        # can't rely on __eq__ for this, because __eq__ relies on Attribute.__eq__ which does not look at attributes values

        for key in set(self.iterkeys()).union(set(other.iterkeys())):

            if key == AttributeID.MP_REACH_NLRI:
                continue

            try:
                sval = self[key]
                oval = other[key]

                # In the case where the attribute is, for instance, a list
                # we want to compare values independently of the order
                if isinstance(sval, collections.Iterable):
                    if not isinstance(oval, collections.Iterable):
                        return False
                    else:
                        # we sort based on string representation since the items do not
                        # necessarily implement __cmp__
                        sorter = lambda x, y: cmp(repr(x), repr(y))
                        sval = sorted(sval, sorter)
                        oval = set(oval, sorter)

                if sval != oval:
                    return False
            except KeyError:
                return False

        return True
def run_kd_tree():
    t = kdtree.create(dimensions=2)
    coordinates = []
    currentCoord = (0.5, 0.5)
    totalDistance = 0.0

    t.add(currentCoord)

    fIn = open(sys.argv[1])
    N = int(fIn.readline())

    for line in fIn.readlines():
        coordInput = line.split(" ")
        x = float(coordInput[0])
        y = float(coordInput[1])
        t.add((x, y))

    start = timeit.default_timer()
    # Using k-d tree
    for i in range(N + 1):
        new = t.search_knn(currentCoord, 2)[-1]  # returns closest point to currentCoord
        t = t.remove(currentCoord)  # mark as visited by removing
        totalDistance += float(new[1])
        currentCoord = eval(str(new[0]))  # convert into tuple

    end = timeit.default_timer()
    fIn.close()

    print("\nTotal distance traveled:", end="")
    print(repr(totalDistance).rjust(25))
    print("Total time taken:", end="")
    print(repr(end - start).rjust(32))
Example #19
0
 def test_folder(self, monkeypatch):
     monkeypatch.setenv("BORG_REPO", "path")
     assert (
         repr(Location("::archive"))
         == "Location(proto='file', user=None, host=None, port=None, path='path', archive='archive')"
     )
     assert repr(Location()) == "Location(proto='file', user=None, host=None, port=None, path='path', archive=None)"
def run_brute_force():
    coordinates = []
    currentCoord = (0.5, 0.5)
    totalDistance = 0.0
    sortedDistances = []

    fIn = open(sys.argv[1])
    N = int(fIn.readline())

    for line in fIn.readlines():
        coordInput = line.split(" ")
        x = float(coordInput[0])
        y = float(coordInput[1])
        coordinates.append((x, y))

    start = timeit.default_timer()
    while len(coordinates) != 0:
        # Sort coordinates by their distance from currentCoord
        for i in coordinates:
            sortedDistances.append(distance(currentCoord, i))

        sortedDistances.sort()

        currentCoord = sortedDistances[0][1]  # gets next coordinate
        totalDistance += sortedDistances.pop(0)[0]  # adds minimum distance in list to total
        sortedDistances.clear()  # list must be cleared for new coordinate
        coordinates.remove(currentCoord)  # acts as a loop counter

    end = timeit.default_timer()
    fIn.close()

    print("\nTotal distance traveled:", end="")
    print(repr(totalDistance).rjust(25))
    print("Total time taken:", end="")
    print(repr(end - start).rjust(32))
Example #21
0
def parseHeatmap(heatmap, **kwargs):
    """Return a two dimensional array and a dictionary with information parsed
    from *heatmap*, which may be an input stream or an :file:`.hm` file in VMD
    plugin Heat Mapper format."""

    try:
        readline, close = heatmap.readline, lambda: None
    except AttributeError:
        heatmap = openFile(heatmap)
        readline, close = heatmap.readline, heatmap.close

    meta = {}
    arrs = []

    line = readline()
    while line:
        if line.startswith("-"):
            label, data = line[1:].split(None, 1)
            data = data.strip()
            if data[0] == data[-1] == '"':
                data = data[1:-1]
            label = label.strip()
            try:
                meta[label] = HMTYPES[label](data)
            except KeyError:
                LOGGER.warn("Unrecognized label encountered: {0}".format(repr(label)))
                meta[label] = HMTYPES[label](data)
            except TypeError:
                LOGGER.warn("Could not parse data with label {0}.".format(repr(label)))
        else:
            arrs.append(line.rstrip())
        line = readline()
    close()
    nnums = len(meta.get("numbering", ""))
    heatmap = []
    numbers = []

    for arr in arrs:
        if nnums:
            items = arr.split(":", nnums + 1)
            numbers.append(items[:nnums])
        else:
            items = [arr]
        heatmap.append(fromstring(items[-1], float, sep=";"))

    heatmap = array(heatmap)
    if nnums:
        numbering = meta["numbering"]
        try:
            numbers = array(numbers, int)
        except ValueError:
            try:
                numbers = array(numbers, float)
            except ValueError:
                LOGGER.warn("Numbering for y-axis could not be parsed.")
                numbering = []
        for i, label in enumerate(numbering):
            meta[label] = numbers[:, i].copy()

    return heatmap, meta
Example #22
0
 def test_repr(self):
     ct0 = Callable[[], bool]
     self.assertEqual(repr(ct0), "typing.Callable[[], bool]")
     ct2 = Callable[[str, float], int]
     self.assertEqual(repr(ct2), "typing.Callable[[str, float], int]")
     ctv = Callable[..., str]
     self.assertEqual(repr(ctv), "typing.Callable[..., str]")
Example #23
0
    def __repr__(self):
        """
        N.B. this does not yet represent a string that can be used
        to instantiate an exact copy of an algorithm.

        However, it is getting close, and provides some value as something
        that can be inspected interactively.
        """
        return """
{class_name}(
    capital_base={capital_base}
    sim_params={sim_params},
    initialized={initialized},
    slippage={slippage},
    commission={commission},
    blotter={blotter},
    recorded_vars={recorded_vars})
""".strip().format(
            class_name=self.__class__.__name__,
            capital_base=self.capital_base,
            sim_params=repr(self.sim_params),
            initialized=self.initialized,
            slippage=repr(self.slippage),
            commission=repr(self.commission),
            blotter=repr(self.blotter),
            recorded_vars=repr(self.recorded_vars),
        )
Example #24
0
File: util.py Project: bcorfman/pug
def prettify_data(val, precision=3):
    """prettify_data( val, precision=3)->prettified string
    
Prettify various data including floats, -0.0 etc."""
    from pug.code_storage.constants import _STORE_UNICODE, _PRETTIFY_FLOATS

    if not _STORE_UNICODE and val is unicode(val):
        # we convert unicode values to strings just for pretty's sake
        val = str(val)
    if repr(val) == "-0.0":
        # I don't totally understand why negative zero is possible
        val = 0.0
    if _PRETTIFY_FLOATS and (type(val) == list or type(val) == tuple):
        # prettify floats in lists and tuples
        if type(val) == list:
            output = "["
            end = "]"
        else:
            output = "("
            end = ")"
        items = []
        for item in val:
            items.append(prettify_data(item, precision))
        output += ", ".join(items) + end
    elif _PRETTIFY_FLOATS and type(val) == float:
        # prettify floats
        output = prettify_float(val, precision)
    elif type(val) not in [str, unicode]:
        output = repr(val)
    else:
        output = val
    return output
    def test_in_cache_from_2casttype(self):
        for t in self.type.all_types():
            if t.elsize != self.type.elsize:
                continue
            obj = array(self.num2seq, dtype=t.dtype)
            shape = (len(self.num2seq),)
            a = self.array(shape, intent.in_.c.cache, obj)
            assert_(a.has_shared_memory(), repr(t.dtype))

            a = self.array(shape, intent.in_.cache, obj)
            assert_(a.has_shared_memory(), repr(t.dtype))

            obj = array(self.num2seq, dtype=t.dtype, order="F")
            a = self.array(shape, intent.in_.c.cache, obj)
            assert_(a.has_shared_memory(), repr(t.dtype))

            a = self.array(shape, intent.in_.cache, obj)
            assert_(a.has_shared_memory(), repr(t.dtype))

            try:
                a = self.array(shape, intent.in_.cache, obj[::-1])
            except ValueError as msg:
                if not str(msg).startswith("failed to initialize intent(cache) array"):
                    raise
            else:
                raise SystemError("intent(cache) should have failed on multisegmented array")
Example #26
0
def permutation_bulk(indiv, Optimizer):
    """Move function to perform Permutation of one atom based on atomlist
    Inputs:
        indiv = Individual class object to be altered
        Optimizer = Optimizer class object with needed parameters
    Outputs:
        indiv = Altered Individual class object
    """
    if "MU" in Optimizer.debug:
        debug = True
    else:
        debug = False
    if Optimizer.structure != "Defect":
        Optimizer.output.write(
            "WARNING: Crystal extended permutation attempted on non-Defect system. Skipping Mutation\n"
        )
    else:
        a1 = indiv.bulki[random.randint(0, indiv.bulki.get_number_of_atoms() - 1)]
        opts = [inds for inds in indiv.bulki if inds.symbol != a1.symbol]
        try:
            a2 = opts[random.randint(0, len(opts) - 1)]
        except ValueError:
            a2 = indiv.bulki[random.randint(0, indiv.bulki.get_number_of_atoms() - 1)]
            Optimizer.output.write("WARNING: Permutation Mutation attempted on single atom structure system\n")
        indiv.bulki[a1.index].symbol, indiv.bulki[a2.index].symbol = a2.symbol, a1.symbol
        Optimizer.output.write("Bulk Permutation Mutation performed on individuals bulk\n")
        Optimizer.output.write("Index = " + repr(indiv.index) + "\n")
        Optimizer.output.write(repr(a1.symbol) + " swapped with " + repr(a2.symbol) + "\n")
        Optimizer.output.write(repr(indiv.bulki) + "\n")
        muttype = "PB"
        if indiv.energy == 0:
            indiv.history_index = indiv.history_index + "m" + muttype
        else:
            indiv.history_index = repr(indiv.index) + "m" + muttype
    return indiv
Example #27
0
    def analyze_results(self, tests, results):
        if results is None:
            return

        error = False
        for i, res in enumerate(results):
            print("IN", repr(tests["param_in"][i]))
            print("EXP", "\n    ".join([repr(r) for r in tests["return_possibilities"][i]]))
            print("OUT", repr(res))

            if tests["shall_round"][i]:
                if round(float(res), 5) not in [float(q) for q in tests["return_possibilities"][i]]:
                    error = True
                    print("ERROR return value wrong!")
            elif tests["set"][i]:
                if ";".split(res) not in [";".split(q) for q in tests["return_possibilities"][i]]:
                    error = True
                    print("ERROR return value wrong!")
            else:
                if res not in tests["return_possibilities"][i]:
                    error = True
                    print("ERROR return value wrong!")

        if error:
            raise Exception("eval-test failed!")
Example #28
0
    def test_pawxml_pseudos(self):
        """Test O.GGA_PBE-JTH-paw.xml."""
        oxygen = Pseudo.from_file(ref_file("O.GGA_PBE-JTH-paw.xml"))
        print(repr(oxygen))
        print(oxygen)
        print(oxygen.as_dict())

        self.assertTrue(oxygen.ispaw)
        self.assertTrue(
            oxygen.symbol == "O" and (oxygen.Z, oxygen.core, oxygen.valence) == (8, 2, 6), oxygen.Z_val == 6
        )

        self.assert_almost_equal(oxygen.paw_radius, 1.4146523028)

        # Test pickle
        new_objs = self.serialize_with_pickle(oxygen, test_eq=False)

        for o in new_objs:
            print(repr(o))
            print(o)

            self.assertTrue(o.ispaw)
            self.assertTrue(o.symbol == "O" and (o.Z, o.core, o.valence) == (8, 2, 6), o.Z_val == 6)

            self.assert_almost_equal(o.paw_radius, 1.4146523028)
Example #29
0
 def _writer_coro(self):
     self.logger.debug("Starting writer coro")
     while self._running:
         try:
             self._writer_ready.set()
             packet = yield from asyncio.wait_for(self.outgoing_queue.get(), 5)
             yield from packet.to_stream(self.session.writer)
             self.logger.debug(" -out-> " + repr(packet))
             yield from self.session.writer.drain()
             self.packet_sent.send(packet)
         except asyncio.TimeoutError as ce:
             self.logger.debug("Output queue get timeout")
         except Exception as e:
             self.logger.warn("Unhandled exception in writer coro: %s" % e)
             break
     self.logger.debug("Writer coro stopping")
     # Flush queue before stopping
     if not self.outgoing_queue.empty():
         while True:
             try:
                 packet = self.outgoing_queue.get_nowait()
                 yield from packet.to_stream(self.session.writer)
                 self.logger.debug(" -out-> " + repr(packet))
             except asyncio.QueueEmpty:
                 break
             except Exception as e:
                 self.logger.warn("Unhandled exception in writer coro: %s" % e)
     self.logger.debug("Writer coro stopped")
Example #30
0
 def __repr__(self):
     return "CTransaction(nVersion=%i vin=%s vout=%s nLockTime=%i)" % (
         self.nVersion,
         repr(self.vin),
         repr(self.vout),
         self.nLockTime,
     )