def pair_cross(individ_s, individ_t, cross_point):
        children = []

        first_part_source = bin(individ_s.val)[2:].zfill(gen_count)[0:cross_point]
        first_part_target = bin(individ_t.val)[2:].zfill(gen_count)[0:cross_point]

        second_part_source = bin(individ_s.val)[2:].zfill(gen_count)[cross_point:]
        second_part_target = bin(individ_t.val)[2:].zfill(gen_count)[cross_point:]

        val1 = first_part_source + second_part_target
        val2 = first_part_target + second_part_source

        x = int(val1, 2) * opt["step"]
        fitness1 = eval(fitness_fn)

        x = int(val2, 2) * opt["step"]
        fitness2 = eval(fitness_fn)

        child1 = Individual(0, int(val1, 2), fitness1)
        child2 = Individual(0, int(val2, 2), fitness2)

        children.append(child1)
        children.append(child2)

        return children
Example #2
1
    def get_tests(self, src):
        ret = {"param_in": [], "return_possibilities": [], "shall_round": [], "set": []}

        for r in src.split("\n"):
            m = re.match("# IN (.*)$", r)
            if m:
                param_in = eval(m.group(1))

                param_in = [
                    p
                    if len(p) < 16 or not re.match("[0-9A-F]+$", p)
                    else self.convert_srs(p, self.stat["config"]["db.srs"])
                    for p in param_in
                ]

                ret["param_in"].append(param_in)
                ret["return_possibilities"].append(set())
                ret["shall_round"].append(False)
                ret["set"].append(False)

            m = re.match("# OUT(_ROUND|_SET)? (.*)$", r)
            if m:
                return_out = eval(m.group(2))

                if len(return_out) > 16 and re.match("[0-9A-F]+$", return_out):
                    return_out = self.convert_srs(return_out, self.stat["config"]["db.srs"])

                if m.group(1) == "_ROUND":
                    ret["shall_round"][-1] = True
                if m.group(1) == "_SET":
                    ret["set"][-1] = True

                ret["return_possibilities"][-1].add(return_out)

        return ret
Example #3
1
def select(start, end):
    """Select the span in Select mode."""
    _unmap_select_mode_mapping()

    selection = eval("&selection")

    col = col2byte(start.line + 1, start.col)
    vim.current.window.cursor = start.line + 1, col

    mode = eval("mode()")

    move_cmd = ""
    if mode != "n":
        move_cmd += r"\<Esc>"

    if start == end:
        # Zero Length Tabstops, use 'i' or 'a'.
        if col == 0 or mode not in "i" and col < len(buf[start.line]):
            move_cmd += "i"
        else:
            move_cmd += "a"
    else:
        # Non zero length, use Visual selection.
        move_cmd += "v"
        if "inclusive" in selection:
            if end.col == 0:
                move_cmd += "%iG$" % end.line
            else:
                move_cmd += "%iG%i|" % virtual_position(end.line + 1, end.col)
        elif "old" in selection:
            move_cmd += "%iG%i|" % virtual_position(end.line + 1, end.col)
        else:
            move_cmd += "%iG%i|" % virtual_position(end.line + 1, end.col + 1)
        move_cmd += "o%iG%i|o\\<c-g>" % virtual_position(start.line + 1, start.col + 1)
    feedkeys(move_cmd)
def diff_structure(st_keys, st_one, st_two):
    st_new = {}
    for i in st_one.keys():
        if i in st_keys:
            if i not in st_two:
                st_new[i] = st_one[i]
            elif st_keys[i] == "string" and str(st_one[i]) != str(st_two[i]):
                st_new[i] = st_one[i]
            elif st_keys[i] == "int" and int(st_one[i]) != int(st_two[i]):
                st_new[i] = st_one[i]
            elif st_keys[i] == "long" and long(st_one[i]) != long(st_two[i]):
                st_new[i] = st_one[i]
            elif st_keys[i] == "array":
                a_st_one = st_one[i] if isinstance(st_one[i], list) else eval(st_one[i])
                b_st_one = st_one[i] if isinstance(st_two[i], list) else eval(st_two[i])
                em_news = list(set(a_st_one).difference(set(b_st_one)))
                em_deleted = list(set(b_st_one).difference(set(a_st_one)))
                if len(em_news) > 0 or len(em_deleted) > 0:
                    st_new[i] = a_st_one
            else:
                pass
    if len(st_new.keys()) > 0:
        return st_new
    else:
        return None
 def _anim(self, cur_img):
     # reset position the current image
     cur_img.setPosition(0, 0)
     # pick a random anim
     number = random.randint(0, 8)
     posx = 0
     posy = 0
     # add 1 sec fadeout time to showtime
     anim_time = self.slideshow_time + 1
     # set zoom level depending on the anim time
     zoom = 110 + anim_time
     if number == 1 or number == 5 or number == 7:
         posx = int(-1280 + (12.8 * anim_time) + 0.5)
     elif number == 2 or number == 6 or number == 8:
         posx = int(1280 - (12.8 * anim_time) + 0.5)
     if number == 3 or number == 5 or number == 6:
         posy = int(-720 + (7.2 * anim_time) + 0.5)
     elif number == 4 or number == 7 or number == 8:
         posy = int(720 - (7.2 * anim_time) + 0.5)
     # position the current image
     cur_img.setPosition(posx, posy)
     # add the animation to the current image
     if number == 0:
         cur_img.setAnimations(eval(EFFECTLIST[number] % (self.adj_time)))
     else:
         cur_img.setAnimations(eval(EFFECTLIST[number] % (self.adj_time, zoom, zoom, self.adj_time)))
Example #6
1
 def handle(self, str):
     """Handle a command string.  First word is command."""
     # Lines beginning with ? are cries for help.
     if str[0] == "?":
         print "Term Commands:"
         print commands
         return
     # Lines beginning with # are comments.
     if str[0] == "#":
         return
     # Lines beginning with ! are Python.
     if str[0] == "!":
         try:
             exec (str.lstrip("!"))
         except:
             print sys.exc_info()[0]
         return
     # Backtick (`) indicates shell commands.
     if str[0] == "`":
         os.system(str.lstrip("`"))
         return
     # By this point, we're looking at a GoodFET command.
     args = str.split()
     if len(args) == 0:
         return
     try:
         eval("self.CMD%s(args)" % args[0])
     except:
         print sys.exc_info()[0]
Example #7
1
def client():
    if len(sys.argv) < 4:
        usage()
    count = int(eval(sys.argv[2]))
    host = sys.argv[3]
    if len(sys.argv) > 4:
        port = eval(sys.argv[4])
    else:
        port = MY_PORT
    testdata = "x" * (BUFSIZE - 1) + "\n"
    t1 = time.time()
    s = socket(AF_INET, SOCK_STREAM)
    t2 = time.time()
    s.connect((host, port))
    t3 = time.time()
    i = 0
    while i < count:
        i = i + 1
        s.send(testdata)
    s.shutdown(1)  # Send EOF
    t4 = time.time()
    data = s.recv(BUFSIZE)
    t5 = time.time()
    print data
    print "Raw timers:", t1, t2, t3, t4, t5
    print "Intervals:", t2 - t1, t3 - t2, t4 - t3, t5 - t4
    print "Total:", t5 - t1
    print "Throughput:", round((BUFSIZE * count * 0.001) / (t5 - t1), 3),
    print "K/sec."
Example #8
1
    def __parseNHML__(self, doc):
        """
        Parse nhml representation of the object
        """
        if isinstance(doc, str):
            # parse the file
            doc = etree.parse(doc).getroot()
        else:
            # assuming doc is an lxml Element object
            assert doc.tag == "soma" or doc.tag == "synapse"
        self.TYPE = doc.get("type")
        self.dims = {}
        self.parameters = {}
        self.id = doc.get("id")
        for elm in doc:
            if elm.tag == "dim":
                if self.dims.has_key(elm.get("id")):
                    self.dims[elm.get("id")] = self.dims[elm.get("id")] + eval(elm.get("range"))
                else:
                    self.dims[elm.get("id")] = eval(elm.get("range"))

            elif elm.tag == "parameter":
                self.parameters[elm.get("id")] = self.neurochip.configurator.parameters[elm.get("SignalName")]
            else:
                pass
        return
Example #9
0
    def GetChildList(self, FILE=None, parent=None):
        """
        
        Get a list of all children for a given node.
        
        :param FILE: file whose children you are interested in.
        :param parent: add a parent node before FILE node.
        
        :returns: list of children for FILE.
        :rtype: list
        
        .. note:: 
           * currently using eval function.
           * not an especially elegant function.
        
        .. todo::
           * make this function more flexible, closer to HDF5 syntax.
           
        """
        if FILE == None:
            ChildList = self.file.root.__members__

        if FILE != None and parent == None:
            foo = "self.file.root." + FILE
            ChildList = eval(foo + ".__members__")
        elif FILE != None and parent != None:
            foo = "self.file.root." + parent + "." + FILE
            ChildList = eval(foo + ".__members__")

        return ChildList
Example #10
0
    def __init__(self, params):
        """ Constructor. Evaluate ranges and check output variables. """
        super(IntegratePeaks, self).__init__(params)
        self.name("IntegratePeaks")
        self.version("1.0")

        try:
            # Eval slices
            slices = eval(self.params["ranges"], {"__builtins__": None}, {})

            if type(slices) is not list:
                self.logger.error(
                    "[%s] Error while evaluating slice limits. (Error: var evaluated to wrong type '%s')",
                    self.name(),
                    type(slices),
                )
                self.params["ranges"] = []

            else:
                if len(slices) == 2 and type(slices[0]) in (int, long, float) and type(slices[1]) in (int, long, float):
                    # Single slice
                    self.params["ranges"] = [slices]
                else:
                    for s in slices:
                        if (
                            type(s) is not list
                            or len(s) != 2
                            or type(s[0]) not in (int, long, float)
                            or type(s[1]) not in (int, long, float)
                            or s[0] >= s[1]
                        ):
                            # Remove bad slices...
                            slices[slices.index(s)] = []
                    self.params["ranges"] = slices

            # Check that the number of slices are the same as the number of
            # output variables
            if type(self.outvars["output"]) == list:
                n = len(self.outvars["output"]) - len(self.params["ranges"])
                if n > 0:
                    # More outputs than slices. Add some empty ranges.
                    self.logger.warning("[%s] Adding %d empty ranges.", self.name(), n)
                    for i in range(n):
                        self.params["ranges"].append([])

                elif n < 0:
                    # More slices than outputs (or equal)
                    self.logger.warning("[%s] Removing %d ranges without an output variable.", self.name(), -n)
                    for i in range(-n):
                        self.params["ranges"].pop()

            # Eval baseline flag
            if "baseline" in self.params and eval(self.params["baseline"], {"__builtins__": None}, {}) == 1:
                self.params["baseline"] = True
            else:
                self.params["baseline"] = False

        except Exception, e:
            self.logger.error("[%s] Error evaluating ranges (Error: %s)", self.name(), e)
            self.params["ranges"] = []
Example #11
0
 def run(self):
     methods = self.get_test_methods()
     for testname in methods:
         self.output += "" + testname + "() "
         eval("self." + testname + "()")
         self.output += "\n"
     return self.output
def print_nonewline(data):
    if version_info < (3, 0):
        print(data),
    else:
        # eval() is used so the Python 3 print function syntax doesn't
        # throw an exception in Python 2
        eval("print('{0}', end=' ')".format(data))
Example #13
0
 def validate(self, fix=False):
     for validator in self.validators:
         value = None
         if "get" in validator:
             value = self.get_path(validator["get"])
         if "get_eval" in validator:
             value = eval(validator["get_eval"])
         if "get_func" in validator:
             value = eval(validator["get_func"])(self, validator, value)
         if "exec" in validator:
             exec(validator["exec"])
         if "minimum" in validator:
             v = validator["minimum"]
             if value < v:
                 if fix and "get" in validator:
                     self.set_path(validator["get"], v)
                 else:
                     raise ValueError("%s < %s (%s)" % (value, v, validator))
         if "maximum" in validator:
             v = validator["maximum"]
             if value > v:
                 if fix and "get" in validator:
                     self.set_path(validator["get"], v)
                 else:
                     raise ValueError("%s > %s (%s)" % (value, v, validator))
         if "equality" in validator:
             v = validator["equality"]
             if value != v:
                 if fix and "get" in validator:
                     self.set_path(validator["get"], v)
                 else:
                     raise ValueError("%s != %s (%s)" % (value, v, validator))
Example #14
0
def test0(outdir="svgout"):
    # print all drawings and their doc strings from the test
    # file
    if not os.path.isdir(outdir):
        os.mkdir(outdir)
    # grab all drawings from the test module
    from reportlab.graphics import testshapes

    drawings = []

    for funcname in dir(testshapes):
        # if funcname[0:11] == 'getDrawing2':
        #    print 'hacked to only show drawing 2'
        if funcname[0:10] == "getDrawing":
            drawing = eval("testshapes." + funcname + "()")
            docstring = eval("testshapes." + funcname + ".__doc__")
            drawings.append((drawing, docstring))

    # return

    i = 0
    for (d, docstring) in drawings:
        filename = outdir + os.sep + "renderSVG_%d.svg" % i
        drawToFile(d, filename)
        # print 'saved', filename
        i = i + 1
    def getProbeData(self):
        """Returns probe-data from all readers. The returned datastructure has
            the following syntax.
            [
                {
                    "name"      : "<name>",
                    "headers"   : [ "foo", "time", "bar" ],
                    "data"      : [ [3, "2009-11-04", 1], [...], ...]
                },
                { ... }, ...
            ]
        """
        retVal = []
        for item in _DataProber.PipelineObjects:
            name = item["name"]
            probe = item["Probe"]
            probe.Source.Point1 = _DataProber.Widget.Point1WorldPosition
            probe.Source.Point2 = _DataProber.Widget.Point2WorldPosition
            print "Probing ", probe.Source.Point1, probe.Source.Point2
            simple.UpdatePipeline(time=_DataProber.View.ViewTime, proxy=probe)

            # fetch probe result from root node.
            do = simple.servermanager.Fetch(probe, 0)
            data = vtkWebUtilities.WriteAttributesToJavaScript(vtk.vtkDataObject.POINT, do)
            headers = vtkWebUtilities.WriteAttributeHeadersToJavaScript(vtk.vtkDataObject.POINT, do)
            # process the strings returned by vtkPVWebUtilities to generate
            # Python objects
            nan = "_nan_"
            data = eval(data)
            headers = eval(headers)
            retVal.append({"name": name, "headers": headers, "data": data})
        return retVal
Example #16
0
def create_store(name):
    """
    Creates the store with `name`.
    """

    name = str(name)

    if name in store_dicts:
        return

    # Create the dict.
    d = StoreDict()
    store_dicts[name] = d

    # Set the name.
    d["__name__"] = name
    d["__package__"] = name

    # Set up the default contents of the store.
    eval("1", d)

    for k, v in renpy.minstore.__dict__.iteritems():
        if k not in d:
            d[k] = v

    # Create the corresponding module.
    sys.modules[name] = StoreModule(d)

    # If we're a module in the store, add us to the store.
    if name.startswith("store."):
        store_dicts["store"][name[6:]] = sys.modules[name]
Example #17
0
def safer_eval(_input):
    try:
        from Ganga.GPIDev.Base.Proxy import getRuntimeGPIObject

        temp_output = getRuntimeGPIObject(_input, True)
        if temp_output is None:
            if len(_input) > 0:
                try:
                    _output = eval(str(_input))
                except:
                    _output = str(_input)
            else:
                _output = None
        elif isclass(temp_output):
            _output = stripProxy(temp_output)
        else:
            _output = temp_output
    except ImportError:
        if len(_input) > 0:
            try:
                _output = eval(str(_input))
            except:
                _output = str(_input)
        else:
            _output = None

    return _output
def simulate_per_quantile(quantile, arguments_partial):
    """
   simulation interface
   :param quantile: quantile of distribution
   :return: excess and out of stock rate
   """

    df = arguments_partial["simulation_df"]

    prediction = arguments_partial["simulation"]["prediction"]["model"]
    prediction_func = eval(prediction)
    prediction_window = arguments_partial["simulation"]["prediction"]["window"]
    prediction_func(df, "PRODUCT_ID", prediction_window, 0)

    replenishment_rule = arguments_partial["simulation"]["replenishment"]["model"]
    replenishment_rule_func = eval(replenishment_rule)

    df["ORDER"] = df["PREDICTION"].apply(lambda x: replenishment_rule_func(0, 0, quantile, x))
    df["INCOMING"] = df.groupby("PRODUCT_ID")["ORDER"].transform(lambda x: x.shift(1))
    df["STOCK_YESTERDAY"] = 0.0

    df_temp = pd.DataFrame(
        map(stock_simulation_rule, df["STOCK_YESTERDAY"], df["SALES"], df["INCOMING"]),
        columns=["STOCK", "missing", "surplus"],
    )

    df["surplus"] = df_temp["surplus"]
    df["missing"] = df_temp["missing"]

    df = df.dropna()

    surplus = float(df.surplus.sum()) / df["SALES"].sum()
    oos_quota = len(df[df.missing > 0]) / float(len(df))

    return surplus, oos_quota, quantile
Example #19
0
    def get_valuation_rate(self, item_code, qty):
        # get default warehouse
        warehouse = sql("select default_warehouse from tabItem where name = %s", item_code)
        warehouse = warehouse and warehouse[0][0] or ""
        in_rate = 0

        # get default valuation method
        val_method = sql("select valuation_method from tabItem where name = %s", item_code)
        val_method = val_method and val_method[0][0] or ""
        if not val_method:
            val_method = get_defaults().has_key("valuation_method") and get_defaults()["valuation_method"] or "FIFO"

        if val_method == "FIFO":
            if warehouse:
                bin_obj = get_obj("Warehouse", warehouse).get_bin(item_code)
                prev_sle = bin_obj.get_prev_sle("", nowdate(), (now().split(" ")[1])[:-3])
                fcfs_stack = prev_sle and (prev_sle[0][3] and eval(prev_sle[0][3]) or []) or []
            else:
                prev_sle = sql(
                    "select fcfs_stack from `tabStock Ledger Entry` where item_code = '%s' and posting_date <= '%s' order by posting_date DESC, posting_time DESC, name DESC limit 1"
                    % (item_code, nowdate())
                )
                fcfs_stack = prev_sle and (prev_sle[0][0] and eval(prev_sle[0][0]) or []) or []
            in_rate = fcfs_stack and self.get_fifo_rate(fcfs_stack, qty) or 0
        elif val_method == "Moving Average":
            in_rate = sql(
                "select ifnull(sum(valuation_rate), 0)/ ifnull(count(*),1) from `tabBin` where item_code = '%s' and ifnull(ma_rate, 0) > 0"
                % cstr(item_code)
            )
            in_rate = in_rate and flt(in_rate[0][0]) or 0
        return in_rate
Example #20
0
def hy_eval(hytree, namespace, module_name):
    foo = HyObject()
    foo.start_line = 0
    foo.end_line = 0
    foo.start_column = 0
    foo.end_column = 0
    replace_hy_obj(hytree, foo)

    if not isinstance(module_name, string_types):
        raise HyTypeError(foo, "Module name must be a string")

    _ast, expr = hy_compile(hytree, module_name, get_expr=True)

    # Spoof the positions in the generated ast...
    for node in ast.walk(_ast):
        node.lineno = 1
        node.col_offset = 1

    for node in ast.walk(expr):
        node.lineno = 1
        node.col_offset = 1

    if not isinstance(namespace, dict):
        raise HyTypeError(foo, "Globals must be a dictionary")

    # Two-step eval: eval() the body of the exec call
    eval(ast_compile(_ast, "<eval_body>", "exec"), namespace)

    # Then eval the expression context and return that
    return eval(ast_compile(expr, "<eval>", "eval"), namespace)
Example #21
0
 def __generateFromXml__(self, chip, xml):
     """
     Generates the parameter translation xml file.
     NOTE: Backward compatibility function
     """
     self.domdoc = xml
     self.id = self.domdoc.getAttribute("id")
     self.parameters = {}
     for i in self.domdoc.getElementsByTagName("parameter"):
         param_id = i.getAttribute("id")
         paramname = i.getAttribute("biasname")
         param = self.neurochip.configurator.parameters[paramname]
         self.parameters[param_id] = param
     # Determine if its soma or synapse
     if self.domdoc.tagName == "soma":
         self.TYPE = "SOMA"
     elif self.domdoc.tagName == "synapse":
         self.TYPE = self.domdoc.getAttribute("type").upper() + " SYNAPSE"
     # TODO: store addresses list instead of ranges, i.e. [[0, 0], [0, 1],
     # ..., [5, 3], [5, 4], ... ]
     # Determining the dimensions of the Group
     # TODO: incapsulate dimensions in neuron group
     self.dims = {}
     for i in self.domdoc.getElementsByTagName("dim"):
         d = i.getAttribute("id")  # ID here is the coordinate (like X , S etc)
         if not i.getAttribute("populate"):
             if d in self.dims:
                 self.dims[d] = self.dims[d] + eval(i.getAttribute("range"))
             else:
                 self.dims[d] = eval(i.getAttribute("range"))
     return self
Example #22
0
    def Run(self):
        for x in self.Query(Banlist).select():
            self.data = ""
            print("Retrieving data from [%s]" % (x.name))
            if x.url == "SPECIAL":
                function = "self.Get%s()" % (x.name.capitalize())
                data = eval(function)
            else:
                data = self.GetBasic(x.url)
            print("Done".ljust(50))

            classobj = eval(x.name.capitalize())

            # Now that we have the data, delete the previous contents
            # of the table so we don't have to deal with updates
            sa.class_mapper(classobj).local_table.drop()
            sa.class_mapper(classobj).local_table.create()

            sys.stdout.write("Creating database objects...")
            sys.stdout.flush()
            self.InjectIntoDb(classobj, data)
            print("DONE")
            sys.stdout.write("Flushing to disk...")
            sys.stdout.flush()
            self.session.flush()
            print("DONE")
Example #23
0
def platform_module(name=platform_default()):
    """Return the imported module for the platform.

    This looks for a module name that matches the specified argument.
    If the name is unspecified, we fetch the appropriate default for
    our execution environment.
    """
    full_name = "SCons.Platform." + name
    if full_name not in sys.modules:
        if os.name == "java":
            eval(full_name)
        else:
            try:
                file, path, desc = imp.find_module(name, sys.modules["SCons.Platform"].__path__)
                try:
                    mod = imp.load_module(full_name, file, path, desc)
                finally:
                    if file:
                        file.close()
            except ImportError:
                try:
                    import zipimport

                    importer = zipimport.zipimporter(sys.modules["SCons.Platform"].__path__[0])
                    mod = importer.load_module(full_name)
                except ImportError:
                    raise SCons.Errors.UserError("No platform named '%s'" % name)
            setattr(SCons.Platform, name, mod)
    return sys.modules[full_name]
Example #24
0
 def setAttachedProperty(self, prop, **argd):
     global layout_dic
     name = prop['name'].split('.')[-1].lower()
     data = prop['data']
     child = prop['child']
     if name == 'dock_side':
         data = data.strip()
         result = eval(data, layout_dic)            
         self.dock_side(child, result)
     elif name == 'dock':
         docks = data.split(',')
         dock_cmd = {}
         for d in docks:
             dock, region = d.split(':')
             dock = dock.strip().lower()
             try:
                 dock = RegionLayoutItem.keymap[dock]
             except:
                 print '[layout.py] unknown dock name(%s) !!!' %dock
             try:
                 region = eval(region.strip())
             except:
                 if argd.get('parser', None):
                     region = argd['parser'].queryMacroValue(region.strip())
                 else:
                     region = eval(strValue, argd['macro'])
             dock_cmd[dock] = region
         self.dock(child, dock_cmd)
Example #25
0
 def help_rainlaunch(self):
     msg = (
         "Rain launch command: Run a command in the requested OS or enter in Interactive mode. The requested OS can be already registered in the requested "
         + " infrastructure or stored in the Image Repository. The latter implies to register the image in the requested infrastructure"
     )
     self.print_man("launch ", msg)
     eval('self.do_rainlaunch("-h")')
Example #26
0
    def write_inline_def(self, node, identifiers, nested):
        """write a locally-available def callable inside an enclosing def."""

        namedecls = node.get_argument_expressions()

        decorator = node.decorator
        if decorator:
            self.printer.writeline("@runtime._decorate_inline(context, %s)" % decorator)
        self.printer.writeline("def %s(%s):" % (node.funcname, ",".join(namedecls)))
        filtered = len(node.filter_args.args) > 0
        buffered = eval(node.attributes.get("buffered", "False"))
        cached = eval(node.attributes.get("cached", "False"))
        self.printer.writelines(
            # push new frame, assign current frame to __M_caller
            "__M_caller = context.caller_stack._push_frame()",
            "try:",
        )
        if buffered or filtered or cached:
            self.printer.writelines("context._push_buffer()")

        identifiers = identifiers.branch(node, nested=nested)

        self.write_variable_declares(identifiers)

        self.identifier_stack.append(identifiers)
        for n in node.nodes:
            n.accept_visitor(self)
        self.identifier_stack.pop()

        self.write_def_finish(node, buffered, filtered, cached)
        self.printer.writeline(None)
        if cached:
            self.write_cache_decorator(node, node.funcname, namedecls, False, identifiers, inline=True, toplevel=False)
Example #27
0
def change_attr_expression(thread_id, frame_id, attr, expression, dbg):
    """Changes some attribute in a given frame.
    """
    frame = find_frame(thread_id, frame_id)
    if frame is None:
        return

    try:
        expression = expression.replace("@LINE@", "\n")

        if dbg.plugin:
            result = dbg.plugin.change_variable(frame, attr, expression)
            if result:
                return result

        if attr[:7] == "Globals":
            attr = attr[8:]
            if attr in frame.f_globals:
                frame.f_globals[attr] = eval(expression, frame.f_globals, frame.f_locals)
                return frame.f_globals[attr]
        else:
            if pydevd_save_locals.is_save_locals_available():
                frame.f_locals[attr] = eval(expression, frame.f_globals, frame.f_locals)
                pydevd_save_locals.save_locals(frame)
                return frame.f_locals[attr]

            # default way (only works for changing it in the topmost frame)
            result = eval(expression, frame.f_globals, frame.f_locals)
            Exec("%s=%s" % (attr, expression), frame.f_globals, frame.f_locals)
            return result

    except Exception:
        traceback.print_exc()
Example #28
0
def eval_loop():
    while True:
        ui = raw_input("Enter command or 'done' to quit: ")  # User input prompt
        if ui == "done":  # Breaks if user enters 'done'
            return ui
        else:
            print eval(ui)  # Evaluates the code entered by user
    def __init__(self, filename=None, verbose=False, read=False):
        self.lst_of_data = []
        self.verbose = verbose
        self.lineCounter = 0

        if read and filename:
            with open(filename, "r") as f:
                for line in f:
                    ll = line.split("\t")
                    try:
                        lst = eval(ll[1])
                    except:
                        lst = None

                    try:
                        dct = eval(ll[2])
                    except:
                        dct = None

                    self._smallaccept(lst, dct)
            return

        if filename:
            self.filename = filename
            with open(self.filename, "w") as f:
                pass
    def init_map_connections(self):
        if not self.display_connections:
            return
        for direction in self.map.connections.keys():
            if direction in self.connections.keys():
                if hasattr(self.connections[direction], "canvas"):
                    self.connections[direction].kill_canvas()
            if self.map.connections[direction] == {}:
                self.connections[direction] = {}
                continue
            self.connections[direction] = Map(self, self.map.connections[direction]["map_name"], config=self.config)

            if direction in ["north", "south"]:
                x1 = 0
                y1 = 0
                x2 = x1 + eval(self.map.connections[direction]["strip_length"], self.config.constants)
                y2 = y1 + 3
            else:  # east, west
                x1 = 0
                y1 = 0
                x2 = x1 + 3
                y2 = y1 + eval(self.map.connections[direction]["strip_length"], self.config.constants)

            self.connections[direction].crop(x1, y1, x2, y2)
            self.connections[direction].init_canvas(self.map_frame)
            self.connections[direction].canvas.pack(side={"west": LEFT, "east": RIGHT}[direction])
            self.connections[direction].draw()