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
Example #2
0
def vend():
    """Simulate a vending machine, taking user input and returning remainder."""
    total = eval(input("Enter the cost (in cents):\n"))
    inserted = 0
    while inserted < total:
        inserted += eval(input("Deposit a coin or note (in cents):\n"))
    if inserted > total:
        sum = inserted - total
        if sum != 0:
            print("Your change is:")
        dollars = sum//100
        if dollars != 0:
            print(dollars,'x $1')
        quarters = (sum - dollars*100)//25
        if quarters != 0:
            print(quarters,'x 25c')
        ten_cents = (sum - dollars*100 - quarters*25)//10
        if ten_cents != 0:
            print(ten_cents,'x 10c')
        five_cents = (sum - dollars*100 - quarters*25 - ten_cents*10)//5
        if five_cents != 0:
            print(five_cents,'x 5c')
        one_cents = (sum - dollars*100 - quarters*25 - ten_cents*10 - five_cents*5)//1
        if one_cents != 0:
            print(one_cents,'x 1c')
Example #3
0
def ejecutar_casos_recursivos(consultas,departamentos,genero,tipoTenant):
    """
    Noviembre 13, 2015
    Autor: Daniel Correa

    Permite ejecutar los diferentes filtros de casos de acuerdo a un arreglo de consultas
    CONSULTAS LLEVA EL SIGUIENTE FORMATO [contulta caso 1, consulta caso 2 , consulta caso 3, ... ,consulta caso n]
    LOS CASOS EMPIEZAN EN 1 EL DE MAS ARRIBA HASTA N EL DE MAS ABAJO
    """
    if departamentos and genero:
        try:
            resultado = eval(consultas[0]%(departamentos,genero))
        except Exception as e:
            print(e)
    elif departamentos:
        try:
            resultado = eval(consultas[1]%(departamentos))
        except Exception as e:
            print(e)
    elif genero:
        try:
            resultado = eval(consultas[2]%(genero))
        except Exception as e:
            print(e)
    else:
        try:
            resultado = eval(consultas[3])
        except Exception as e:
            print(e)
    return resultado
Example #4
0
def setup_template_render(path, config_path):
    """ This function is the gateway for rendering a template for a file.
    """

    # initialization
    cp = get_embedded_config(path)
    output = ''
    filename = os.path.basename(path)

    # use meta-data if not empty for rendering
    if cp.has_option(filename, 'render-function'):
        render_function_name = cp.get(filename, 'render-function')
        render_function = eval(render_function_name)
        output = render_function(path, cp)

    # read configuration file for rendering
    elif os.path.exists(config_path):
        cp.read(config_path)

        # render template
        if cp.has_option(filename, 'render-function'):
            render_function_name = cp.get(filename, 'render-function')
            render_function = eval(render_function_name)
            output = render_function(path, cp)
        else:
            output = render_default(path, cp)

    # if no configuration file is present
    # then render the default template
    else:
        output = render_default(path, cp)

    return output
Example #5
0
def generate_package_wikidocs(package_string, file_prefix='ref',
                              file_suffix='.wiki'):
    d = Documize()
    package = eval(package_string)
    print('''

Generating documentation for package %s''' % package_string)
    for element in dir(package):
        if not isinstance(element, collections.Callable):
            fullname = '%s.%s' % (package_string, element)
            if type(eval(fullname)) == types.ModuleType or type(eval(fullname))\
                 == type:
                d.set_module(fullname)
                wikiname = file_prefix
                for parts in fullname.split('.'):
                    wikiname += parts.capitalize()
                wikiname += file_suffix
                print('Writing %s...' % wikiname, end=' ')
                result = d.output_wiki()
                try:
                    f = open(os.path.join(sys.argv[1], wikiname), 'w')
                    try:
                        f.write(result)
                        print('OK')
                    except:
                        print("ERROR. Couldn't write to file.")
                    f.close()
                except:
                    print("ERROR. Couldn't open file for writing.")
Example #6
0
def _install_handlers(cp, formatters):
    """Install and return handlers"""
    hlist = cp["handlers"]["keys"]
    if not len(hlist):
        return {}
    hlist = hlist.split(",")
    hlist = _strip_spaces(hlist)
    handlers = {}
    fixups = [] #for inter-handler references
    for hand in hlist:
        section = cp["handler_%s" % hand]
        klass = section["class"]
        fmt = section.get("formatter", "")
        try:
            klass = eval(klass, vars(logging))
        except (AttributeError, NameError):
            klass = _resolve(klass)
        args = section["args"]
        args = eval(args, vars(logging))
        h = klass(*args)
        if "level" in section:
            level = section["level"]
            h.setLevel(logging._levelNames[level])
        if len(fmt):
            h.setFormatter(formatters[fmt])
        if issubclass(klass, logging.handlers.MemoryHandler):
            target = section.get("target", "")
            if len(target): #the target handler may not be loaded yet, so keep for later...
                fixups.append((h, target))
        handlers[hand] = h
    #now all handlers are loaded, fixup inter-handler references...
    for h, t in fixups:
        h.setTarget(handlers[t])
    return handlers
Example #7
0
def main():

    usage = """
gdal_calc.py [-A <filename>] [--A_band] [-B...-Z filename]  [--calc <calculation>] [--format] [--outfile output_file] [--type data_type] [--NoDataValue] [--overwrite]
    """

    parser = OptionParser(usage)

    # define options
    parser.add_option("--calc", dest="calc", help="calculation in gdalnumeric syntax using +-/* or any numpy array functions (i.e. logical_and())")
    # hack to limit the number of input file options close to required number
    for myAlpha in AlphaList[0:len(sys.argv)-1]:
        eval('parser.add_option("-%s", dest="%s", help="input gdal raster file, note you can use any letter A-Z")' %(myAlpha, myAlpha))
        eval('parser.add_option("--%s_band", dest="%s_band", default=0, type=int, help="number of raster band for file %s")' %(myAlpha, myAlpha, myAlpha))

    parser.add_option("--outfile", dest="outF", default='gdal_calc.tif', help="output file to generate or fill.")
    parser.add_option("--NoDataValue", dest="NoDataValue", type=float, help="set output nodatavalue (Defaults to datatype specific values)")
    parser.add_option("--type", dest="type", help="set datatype must be one of %s" % list(DefaultNDVLookup.keys()))
    parser.add_option("--format", dest="format", default="GTiff", help="GDAL format for output file (default 'GTiff')")
    parser.add_option("--overwrite", dest="overwrite", action="store_true", help="overwrite output file if it already exists")
    parser.add_option("--debug", dest="debug", action="store_true", help="print debugging information")

    (opts, args) = parser.parse_args()

    if len(sys.argv) == 1:
        print(usage)
    elif not opts.calc:
        print("No calculation provided.  Nothing to do!")
        print(usage)
    else:
        doit(opts, args)
 def _eval_params(self, model, params):
     args = []
     for i, param in enumerate(params):
         if isinstance(param, types.ListType):
             value = self._eval_params(model, param)
         elif is_ref(param):
             value = self.process_ref(param)
         elif is_eval(param):
             value = self.process_eval(param)
         elif isinstance(param, types.DictionaryType): # supports XML syntax
             param_model = self.get_model(param.get('model', model))
             if 'search' in param:
                 q = eval(param['search'], self.eval_context)
                 ids = param_model.search(self.cr, self.uid, q)
                 value = self._get_first_result(ids)
             elif 'eval' in param:
                 local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
                 local_context.update(self.id_map)
                 value = eval(param['eval'], self.eval_context, local_context)
             else:
                 raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
         else:
             value = param # scalar value
         args.append(value)
     return args
Example #9
0
 def isLoginState(self):
     headers = {
         'Host': 'service.bjtu.edu.cn',
         'Connection': 'keep-alive',
         'User-Agent': 'Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
         'Accept': 'application/json, text/javascript, */*; q=0.01',
         'X-Requested-With': 'XMLHttpRequest',
         'Referer': 'http://service.bjtu.edu.cn/LoginAction.action',
         'Accept-Encoding': 'gzip, deflate, sdch',
         'Accept-Language': 'zh-CN,zh;q=0.8',
         'Cookie': self.cookie
     }
     url = 'http://service.bjtu.edu.cn/refreshaccount?t=' + str(random.random())
     r = requests.get(url, headers=headers)
     rc = r.content
     if self.account in rc:#证明当前登陆状态
         try:
             self.accountInfo = eval(rc)
         except:
             pass
         return True
     else:
         try:
             rc = rc.replace('null',"'null'")
             self.accountInfo = eval(rc)
             pass
         except:#可能是登陆了其他账号,销毁当前cookie,方便重新登陆
             self.setCookieLocal('ERROR')
             pass
         return False
Example #10
0
 def processAutoComp(self, aco):
     """ Processes an autocomp request using an AutoCompObject instance. 
     """
     
     # Try using buffer first
     if aco.tryUsingBuffer():
         return
     
     # Include buildins?
     if not aco.name:
         command = "__builtins__.keys()"
         try:
             names = eval(command, {}, self._interpreter.locals)
             aco.addNames(names)
         except Exception:
             pass
     
     # Query list of names
     command = "dir({})".format(aco.name)
     try:
         names = eval(command, {}, self._interpreter.locals)
         aco.addNames(names)
     except Exception:
         pass
     
     # Done
     aco.finish()
Example #11
0
 def test_sms_fillHeader(self):
     "sms_fillHeader copies data from an SMS_AnalParams to an SMS_Header"
     data_fields = ["nFrames", "iFormat", "iFrameRate", "iStochasticType", \
                    "nTracks", "iSamplingRate", "nStochasticCoeff"]
     sms_fillHeader(self.sms_header, self.analysis_params, "")
     for field in data_fields:
         self.assert_(eval("self.sms_header."+field) == eval("self.analysis_params."+field))
Example #12
0
  def onReload(self, moduleName="SegmentCAD"):
    #Generic reload method for any scripted module.
    #ModuleWizard will subsitute correct default moduleName.
    
    import imp, sys, os, slicer
    
    widgetName = moduleName + "Widget"

    # reload the source code
    # - set source file path
    # - load the module to the global space
    filePath = eval('slicer.modules.%s.path' % moduleName.lower())
    p = os.path.dirname(filePath)
    if not sys.path.__contains__(p):
      sys.path.insert(0,p)
    fp = open(filePath, "r")
    globals()[moduleName] = imp.load_module(
        moduleName, fp, filePath, ('.py', 'r', imp.PY_SOURCE))
    fp.close()

    # rebuild the widget
    # - find and hide the existing widget
    # - create a new widget in the existing parent
    # parent = slicer.util.findChildren(name='%s Reload' % moduleName)[0].parent()
    parent = self.parent
    for child in parent.children():
      try:
        child.hide()
      except AttributeError:
        pass
    globals()[widgetName.lower()] = eval(
        'globals()["%s"].%s(parent)' % (moduleName, widgetName))
    globals()[widgetName.lower()].setup()
Example #13
0
    def config_dict(self, local=True):
        """parses the lines from git config --list into a dictionary"""

        kwargs = {
            'list': True,
            'global': not local, # global is a python keyword
        }
        config_lines = self.git.config(**kwargs).splitlines()
        newdict = {}
        for line in config_lines:
            try:
                k, v = line.split('=', 1)
            except:
                # value-less entry in .gitconfig
                continue
            v = core.decode(v)
            k = k.replace('.','_') # git -> model
            if v == 'true' or v == 'false':
                v = bool(eval(v.title()))
            try:
                v = int(eval(v))
            except:
                pass
            newdict[k]=v
        return newdict
Example #14
0
def paramiterator(node):
    """ returns a list of all parameters for a widget element """
    outparams = {}
    for k, v in node.attributes.items():
	if v and v[0] in "{[(\"'":
	    v = eval(v)
	else:
	    try:
		v = int(v)
	    except ValueError:
		try:
		    v = float(v)
		except ValueError:
		    pass
	outparams[str(k)] = v

    for e in node.childNodes:
	if e.nodeType == e.ELEMENT_NODE \
		and (e.nodeName not in pyvcp_widgets.elements):
            try:
                v = eval(e.childNodes[0].nodeValue)
            except: 
                exc_type, exc_value, exc_tb = sys.exc_info()
                raise SystemExit, ("Error evaluating xml file:\n"
                    "Widget %s, Property %s\n%s: %s") % (
                        node.nodeName, e.nodeName, exc_type.__name__, exc_value)
	    outparams[str(e.nodeName)] = v
    return outparams
Example #15
0
def getReaderWriter(file_name, out_dir=None):
    r = vtk.vtkDataReader()
    r.SetFileName(file_name)
    f_base = os.path.splitext(file_name)[0]
    r.Update()
    reader = None
    writer = None
    xmlsuffix = '.xml'
    map = {'StructuredPoints': '.vti', 'StructuredGrid': '.vts',
           'RectilinearGrid': '.vtr', 'UnstructuredGrid': '.vtu',
           'PolyData': '.vtp'}
    for i in ['StructuredPoints', 'StructuredGrid', 'RectilinearGrid',
              'UnstructuredGrid', 'PolyData']:
        if eval('r.IsFile%s()'%i):
            reader = eval('vtk.vtk%sReader()'%i)
            if i == 'StructuredPoints':
                writer = eval('vtk.vtkXMLImageDataWriter()')
            else:
                writer = eval('vtk.vtkXML%sWriter()'%i)
            xmlsuffix = map[i]
            break
    if not reader:
        return None, None
    
    reader.SetFileName(file_name)
    reader.Update()

    out_file = f_base + xmlsuffix
    if out_dir:
        out_file = os.path.join(out_dir,
                                os.path.basename(f_base) + xmlsuffix)
    writer.SetFileName(out_file)
    return reader, writer
Example #16
0
def to_python(rule):
    """Convert a list/dict of rules or a `PluralRule` object into a regular
    Python function.  This is useful in situations where you need a real
    function and don't are about the actual rule object:

    >>> func = to_python({'one': 'n is 1', 'few': 'n in 2..4'})
    >>> func(1)
    'one'
    >>> func(3)
    'few'
    >>> func = to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
    >>> func(11)
    'one'
    >>> func(15)
    'few'

    :param rule: the rules as list or dict, or a `PluralRule` object
    :return: a corresponding Python function
    :raise RuleError: if the expression is malformed
    """
    namespace = {
        'IN':       in_range_list,
        'WITHIN':   within_range_list,
        'MOD':      cldr_modulo
    }
    to_python = _PythonCompiler().compile
    result = ['def evaluate(n):']
    for tag, ast in PluralRule.parse(rule).abstract:
        # the str() call is to coerce the tag to the native string.  It's
        # a limited ascii restricted set of tags anyways so that is fine.
        result.append(' if (%s): return %r' % (to_python(ast), str(tag)))
    result.append(' return %r' % _fallback_tag)
    code = compile('\n'.join(result), '<rule>', 'exec')
    eval(code, namespace)
    return namespace['evaluate']
Example #17
0
def main():
    args = parse_args()

    state = getattr(experiments.nmt, args.proto)()
    if args.state:
        if args.state.endswith(".py"):
            state.update(eval(open(args.state).read()))
        else:
            with open(args.state) as src:
                state.update(cPickle.load(src))
    for change in args.changes:
        state.update(eval("dict({})".format(change)))

    logging.basicConfig(level=getattr(logging, state['level']), format="%(asctime)s: %(name)s: %(levelname)s: %(message)s")
    logger.debug("State:\n{}".format(pprint.pformat(state)))

    rng = numpy.random.RandomState(state['seed'])
    enc_dec = RNNEncoderDecoder(state, rng, skip_init=args.skip_init, compute_alignment=True)
    enc_dec.build()
    lm_model = enc_dec.create_lm_model()

    logger.debug("Load data")
    train_data = get_batch_iterator(state)
    logger.debug("Compile trainer")
    algo = eval(state['algo'])(lm_model, state, train_data)
    logger.debug("Run training")
    main = MainLoop(train_data, None, None, lm_model, algo, state, None,
            reset=state['reset'],
            hooks=[RandomSamplePrinter(state, lm_model, train_data)]
                if state['hookFreq'] >= 0
                else None)
    if state['reload']:
        main.load()
    if state['loopIters'] > 0:
        main.main()
Example #18
0
def vending_machine():
    deposit = 0 
    #get the cost of the item(s) purchased
    cost = eval(input('Enter the cost (in cents):\n'))
    #ask for money to pay when cost is greater than 0 and ask for more deposit when not enough
    while deposit < cost:
        deposit += eval(input('Deposit a coin or note (in cents):\n'))
    change = deposit - cost
    #Give change when due
    if change > 0:
        print('Your change is:')
        
        for i in (100, 25, 10, 5, 1):
            #check decreasingly if one of the possible coin is part of the change
            if change >= i:
                #specify for change more than or equal to $1 as in dollar               
                if i == 100:
                    print(change//i, ' x ', '$1',sep = '')
                else:
                    print(change//i, ' x ', i,'c',sep = '')
                change -= (change//i)*i
                #check until chanege is 0 then break loop
                if change == 0:
                    break
            else:
                continue
Example #19
0
    def process_report(self, node):
        values = {}
        for dest, f in (('name','string'), ('model','model'), ('report_name','name')):
            values[dest] = getattr(node, f)
            assert values[dest], "Attribute %s of report is empty !" % (f,)
        for field,dest in (('rml','report_rml'),('file','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
            if getattr(node, field):
                values[dest] = getattr(node, field)
        if node.auto:
            values['auto'] = eval(node.auto)
        if node.sxw:
            sxw_file = misc.file_open(node.sxw)
            try:
                sxw_content = sxw_file.read()
                values['report_sxw_content'] = sxw_content
            finally:
                sxw_file.close()
        if node.header:
            values['header'] = eval(node.header)
        values['multi'] = node.multi and eval(node.multi)
        xml_id = node.id
        self.validate_xml_id(xml_id)

        self._set_group_values(node, values)

        id = self.pool.get('ir.model.data')._update(self.cr, SUPERUSER_ID, "ir.actions.report.xml", \
                self.module, values, xml_id, noupdate=self.isnoupdate(node), mode=self.mode)
        self.id_map[xml_id] = int(id)

        if not node.menu or eval(node.menu):
            keyword = node.keyword or 'client_print_multi'
            value = 'ir.actions.report.xml,%s' % id
            replace = node.replace or True
            self.pool.get('ir.model.data').ir_set(self.cr, SUPERUSER_ID, 'action', \
                    keyword, values['name'], [values['model']], value, replace=replace, isobject=True, xml_id=xml_id)
def getScoreOfExample(rule, dataSetExample):
    # print "dataSetExample:", dataSetExample
    # create variables that are the features of the example
    for feature in featuresInDataSet:
        if dataSetExample[feature] == SAME or dataSetExample[feature] == DIFFERENT:
            vars()[feature] = dataSetExample[feature]
        else:
            vars()[feature] = int(dataSetExample[feature])
        # FIVE ####vars()[feature] = dataSetExample[feature]
    # eval preCondition and condition to know what score to choose
    score = 0
    for sNodeAndItsAssociatedPNodes in rule:
        # print "Current Rule:", sNodeAndItsAssociatedPNodes
        # print "before score:", score
        if eval(sNodeAndItsAssociatedPNodes.preCondition):
            if eval(sNodeAndItsAssociatedPNodes.condition):
                # print("going to alpha1")
                score += sNodeAndItsAssociatedPNodes.alpha1
            else:
                # print("going to alpha2")
                score += sNodeAndItsAssociatedPNodes.alpha2
        else:
            score += 0
        # print "after score:", score
    return score
 def make_seq(items, part):
     if items is nil:
         return nil
     elif eval("items.first.{0}".format(part)) is nil:
         return nil
     else:
         return Pair(eval("items.first.{0}".format(part)), make_seq(items.second, part))
Example #22
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 #23
0
def filterRecords(expression,records):
	## Format the string
	tags = ["not","and","or",">","<",">=","<=","==","+","-","(",")"]
	expression = expression.lower()
	for t in tags:
		expression = expression.replace(t," "+t+" ")

	## Get all keys from records
	all_keys = set([])
	for r in records:
		all_keys = all_keys | set (r.keys())

	## Identify metrics in expression
	words = expression.split()
	for w in all_keys:
		if w in words:
			expression = expression.replace(w,"r[\""+w+"\"]")

	## Delete SEQRES records
	preselection = []
	for r in records:
		if  not "seqres" in r.keys():
			preselection.append(r)

	selection = []
	for r in preselection:
		if eval(expression):
			selection.append(r)
		print(eval(expression))

	return selection
Example #24
0
 def co_header(self,line):
     header=line.split()
     self.data.name=header[1]
     self.data.nbases=eval(header[2])
     self.data.nreads=eval(header[3])
     self.data.nsegments=eval(header[4])
     self.data.uorc=header[5]
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 bs(self,line):
     header=line.split()
     bsdata=bs()
     bsdata.padded_start=eval(header[1])
     bsdata.padded_end=eval(header[2])
     bsdata.name=header[3]
     self.data.bs.append(bsdata)
Example #27
0
def plot_results_vs_other(results, x_field, y_field, other_field, extra_title=""):
    """ Function to plot Y vs X of anything. It accesses the members of "results" to plot them.
    other_field is used to separate by another field, and make separate line plots for each"""
    others = set()
    for par in results:
        others.add( eval('par.%s' % other_field) )
    others = list(others)
    others.sort()
        
    figure()
    
    for other in others:
        data = []
        for par in results:   
            this_other = eval('par.%s' % other_field)
            if this_other == other: 
                x = eval('par.%s' % x_field)      
                y = eval('par.%s' % y_field)
                data.append( (x,y) )      
        data.sort()
        xs = [x for (x,y) in data]
        ys = [y for (x,y) in data]
        p = plot(xs,ys, marker='.', label="%s = %f" % (other_field, other))
        
    if extra_title != "": extra_title = "\n" + extra_title
    title("%s vs %s%s" % (y_field, x_field, extra_title) );
    xlabel(x_field)
    ylabel(y_field)
    legend(loc='best')
    savefig("%s_vs_%s.png" % (y_field, x_field));
Example #28
0
def plot_results_with_slope(results, x_field, y_field, x_scale=1):
    """ Function to plot Y vs X of anything. It accesses the members of "results" to plot them.
    other_field is used to separate by another field, and make separate line plots for each
    
    @param x_scale :: multiply x by this amount
    """
    figure()
    
    data = []
    for par in results:   
        x = eval('par.%s' % x_field)      
        y = eval('par.%s' % y_field)
        data.append( (x,y) )      
    data.sort()
    xs = [x*x_scale for (x,y) in data]
    ys = [y for (x,y) in data]
    
    # Now get the slope 
    gradient, intercept, r_value, p_value, std_err = stats.linregress(xs,ys)
    
    p = plot(xs,ys, marker='.', label="y = %.3gx + %.3g" % (gradient, intercept))
            
    title("%s vs %s" % (y_field, x_field));
    xlabel("%s x %s" % (x_field, x_scale) )
    ylabel(y_field)
    legend(loc='best')
    savefig("%s_vs_%s.png" % (y_field, x_field));
Example #29
0
 def repeatLWidgetsSignals(self, signals = None):
     super(LExecutableComposite, self).repeatLWidgetsSignals()
     if signals is None:
         signals = [ 'processStarted', 'processFinished', 'processResumed', 'processPaused' ]
     for widget in self.getLWidgets():
         for signal in signals:
             eval("widget.%s.connect(self.%s.emit)" % (signal, signal))
Example #30
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)