def test_static_required_extraction_success(self): # if static dict is required, dict values must not be empty widget = factory( 'error:dict', name='mydict', value=odict([('k1', 'v1')]), props={ 'required': True, 'static': True, 'key_label': 'Key', 'value_label': 'Value' }) # check valid extraction request = { 'mydict.exists': '1', 'mydict.entry0.value': 'Value1', } data = widget.extract(request=request) self.assertFalse(data.has_errors) self.assertEqual( data.extracted, odict([('k1', 'Value1')]) ) # check rendered rendered = widget(data=data) expected = '<div class="errormessage">' self.assertFalse(rendered.find(expected) > -1) expected = 'name="mydict.entry0.value" type="text" value="Value1"' self.assertTrue(rendered.find(expected) > -1)
def parse_override_function(myclasses_array_dict): while True: should_be_continue = False for class_name, one_myclass in myclasses_array_dict.iteritems(): my_supers = one_myclass[const.m_dict['super']] # setup self's override set override_set = set() if not one_myclass.has_key(const.override_all): one_myclass[const.override_all] = False for over_function in one_myclass[const.m_dict['override']]: if over_function[const.func.name] == const.override_all: one_myclass[const.override_all] = True break override_set.add(over_function[const.func.name]) # also snap super's free|destructor override_set.add(const.member_destructor[const.func.name]) override_set.add(const.member_free[const.func.name]) # traverse all super's vtable, try-match my override-func for super_name in my_supers.keys(): super_class = convert_to_class(myclasses_array_dict, super_name) # create new inherit-vtable if (not my_supers[super_name].has_key(super_name)) \ and super_class[const.m_dict['virtual']]: should_be_continue = True my_supers[super_name][super_name] = odict() my_supers[super_name][super_name]['path'] = super_name my_supers[super_name][super_name][const.control_super] = False v_func_list = [] if not my_supers[super_name][super_name].has_key(const.m_dict['virtual']): my_supers[super_name][super_name][const.m_dict['virtual']] = v_func_list # check override function for v_function in super_class[const.m_dict['virtual']]: if one_myclass[const.override_all] \ or v_function[const.func.name] in override_set: v_func_list.append(v_function) # clone inherit-vtable from supers super2_supers = super_class[const.m_dict['super']] for super2_name, super2_class in super2_supers.iteritems(): for super2_vtable_name, super2_vtable in super2_class.iteritems(): if not my_supers[super_name].has_key(super2_vtable_name): should_be_continue = True vtable_class = convert_to_class(myclasses_array_dict, super2_vtable_name) my_supers[super_name][super2_vtable_name] = odict() my_supers[super_name][super2_vtable_name]['path'] = super_name + '.' + super2_vtable['path'] my_supers[super_name][super2_vtable_name][const.control_super] = False v_func_list = [] if not my_supers[super_name][super2_vtable_name].has_key(const.m_dict['virtual']): my_supers[super_name][super2_vtable_name][const.m_dict['virtual']] = v_func_list # check override function for v_function in vtable_class[const.m_dict['virtual']]: if v_function[const.func.name] in override_set: v_func_list.push(v_function) if not should_be_continue: break
def __call__(self, track, *args ): """count number of entries in a table.""" config = ConfigParser.ConfigParser() config.readfp(open(track),"r") result = odict() def convert( value ): '''convert a value to int, float or str.''' rx_int = re.compile("^\s*[+-]*[0-9]+\s*$") rx_float = re.compile("^\s*[+-]*[0-9.]+[.+\-eE][+-]*[0-9.]*\s*$") if value == None: return value if rx_int.match( value ): return int(value), "int" elif rx_float.match( value ): return float(value), "float" return value, "string" for section in config.sections(): x = odict() for key,value in config.items( section ): x[key] = odict( zip( ("value", "type" ), convert( value )) ) result[section] = x return result
def convert_namespace_to_tree(def_path, input_dict): mysuper = odict() context_dict_tree = odict() # file header or comments mysuper['file_note'] = get_value_else_default(input_dict, 'file_note', False) mysuper['trace'] = get_value_else_default(input_dict, 'trace', False) mysuper['copyright'] = get_value_else_default(input_dict, 'copyright', []) mysuper['author'] = get_value_else_default(input_dict, 'author', []) # author with email mysuper['date'] = get_value_else_default(input_dict, 'date', strftime("%Y-%m-%d", gmtime())) mysuper['summary'] = get_value_else_default(input_dict, 'summary', []) mysuper['note'] = get_value_else_default(input_dict, 'note', []) mysuper['comment'] = get_value_else_default(input_dict, 'comment', []) mysuper['message'] = get_value_else_default(input_dict, 'message', '') mysuper['error'] = get_value_else_default(input_dict, 'error', '') # generate path mysuper['path'] = get_value_else_default(input_dict, 'path', def_path) mysuper['namespace'] = get_value_else_default(input_dict, 'namespace', def_path) mysuper[const.config_super] = 'False' mysuper[const.config_destructor] = 'False' mysuper[const.m_dict['super']] = [] if input_dict.has_key(const.classes): convert_to_myclasses(context_dict_tree, input_dict[const.classes], mysuper) else: raise Exception('json source no "{0}"'.format(const.classes)) return context_dict_tree
def etud_get_poursuite_info(context, sem, etud): """{ 'nom' : ..., 'semlist' : [ { 'semestre_id': , 'moy' : ... }, {}, ...] } """ I = {} I.update(etud) # copie nom, prenom, sexe, ... # Now add each semester, starting from the first one semlist = [] current_id = sem['semestre_id'] for sem_id in range(1, current_id+1): sem_descr = None for s in etud['sems']: if s['semestre_id'] == sem_id: etudid = etud['etudid'] nt = context._getNotesCache().get_NotesTable(context, s['formsemestre_id']) dec = nt.get_etud_decision_sem(etudid) if (dec and (code_semestre_validant(dec['code']) or code_semestre_attente(dec['code'])) and nt.get_etud_etat(etudid) == 'I'): sem_descr = odict( data=( ('moy', nt.get_etud_moy_gen(etudid)), ('rang', nt.get_etud_rang(etudid)), ('effectif', len(nt.T)), ('date_debut', s['date_debut']), ('date_fin', s['date_fin']), ('periode', '%s - %s' % (s['mois_debut'], s['mois_fin'])) )) if not sem_descr: sem_descr = odict( data=(('moy',''), ('rang',''), ('effectif', ''), ('date_debut', ''), ('date_fin', ''), ('periode', ''))) sem_descr['semestre_id'] = sem_id semlist.append(sem_descr) I['semlist'] = semlist return I
def form(self): # make configuration data available on form context self.props = ILDAPProps(self.plugin) self.users = ILDAPUsersConfig(self.plugin) self.groups = ILDAPGroupsConfig(self.plugin) # prepare users data on form context self.users_attrmap = odict() for key in self.static_attrs_users: self.users_attrmap[key] = self.users.attrmap.get(key) self.users_propsheet_attrmap = odict() for key, value in self.users.attrmap.items(): if key in self.static_attrs_users: continue self.users_propsheet_attrmap[key] = value # prepare groups data on form context self.groups_attrmap = odict() for key in self.static_attrs_groups: self.groups_attrmap[key] = self.groups.attrmap.get(key) self.groups_propsheet_attrmap = odict() for key, value in self.groups.attrmap.items(): if key in self.static_attrs_groups: continue self.groups_propsheet_attrmap[key] = value # handle form form = parse_from_YAML('pas.plugins.ldap:properties.yaml', self, _) controller = Controller(form, self.request) if not controller.next: return controller.rendered self.request.RESPONSE.redirect(controller.next) return u''
def GET(self, what="any", field="any", key="*", limit=10, offset=0, which='3'): if what not in ("any", "gene", "enrichment", "species", "tissue"): return web.notfound() sexp=self.get_search_expression(what, field, key, limit, offset) limit=int(limit) offset=int(offset) html=odict.odict() html['species']=html['tissue']=html['gene']=html['enrichment']='' hitcounts=odict.odict() hitcounts['species']=hitcounts['tissue']=hitcounts['gene']= \ hitcounts['enrichment']=0 chitcounts=odict.odict() ## Get the hit counts hitcounts['species']= \ model.search_for_species(field, key, which, count=True)[0].count chitcounts['species']=0 hitcounts['tissue']=\ model.search_for_tissue(field, key, which, count=True)[0].count chitcounts['tissue']=hitcounts['species'] hitcounts['gene']= \ model.search_for_gene(field, key, which, count=True)[0].count chitcounts['gene']=chitcounts['tissue']+hitcounts['tissue']; hitcounts['enrichment']= \ model.search_for_enrichment(field, key, which,count=True)[0].count chitcounts['enrichment']=chitcounts['gene']+hitcounts['gene'] ## What to show offsets, limits = self.get_pos(hitcounts, offset, limit) ## Show it if what in ('species', 'any') and limits['species'] != 0: html['species']=self.search_for_species(field, key, which, limits['species'], offsets['species']) if what in ('tissue', 'any') and limits['tissue'] != 0: html['tissue']=self.search_for_tissue(field, key, which, limits['tissue'], offsets['species']) if what in ('gene', 'any') and limits['gene'] != 0: html['gene']=self.search_for_gene(field, key, which, limits['gene'], offsets['gene']) if what in ('enrichment', 'any') and limits['enrichment'] != 0: html['enrichment']= \ self.search_for_enrichment(field, key, which, limits['enrichment'], offsets['enrichment']) return render.searchresults(hitcounts, chitcounts, html, offset, web.ctx.home, field, key, limit, what, sum(hitcounts.values()), sexp, which)
def generate_thesaurus(self, neg_kwds): """The main function which gets thesaurus keywords. Loops through existing keywords and get thesaurus keywords based on config. Args: neg_kwds: a list of keywords whose context related keywords should not be included. Returns: A dictionary containing """ ekwds = self.ekwds # existing keywords. synsxx = odict() # Ordered dictionary. for kwd in ekwds: # do this for each word in a kwd s_kwd = kwd.split() synsxx[kwd] = odict() # ([],[]) #close syns and hyponyms for x in s_kwd: synsxx[kwd][x] = [[x], []] # close syns and hyponyms #only take verbs and nouns kwd_syns = wn.synsets(x) if not kwd_syns: continue counter = 0 words_temp_syns = [] words_temp_hyps = [] if x in self.final_word_dict.keys(): continue # TODO: add a separate loop for homonyms cached_kwd_syns = set(kwd_syns[:]) for i in kwd_syns: #TODO(mrafi): remove negative kwds. negative_keywords = self.get_negative_keywords( neg_kwds, i) cached_kwd_syns = cached_kwd_syns - set(negative_keywords) if not cached_kwd_syns.__contains__(i): continue if not self.config.get('include_all_pos_types') and i.pos not in ('n', 'v', 'a'): continue if self.config['close_syns']: types_of_kwd = i.lemmas # XXX:for synonyms this is it temp = sorted(i.lemma_names()) #if i in for j in temp: words_temp_syns.append('%s ' % (j.replace('_', ' '))) if self.config['hypo_syns']: types_of_kwd = i.hyponyms() # data for hyponyms temp = sorted([lemma.name for synset in types_of_kwd for lemma in synset.lemmas]) for j in temp: words_temp_hyps.append('%s ' % (j.replace('_', ' '))) if not types_of_kwd: continue counter += 1 if words_temp_syns: synsxx[kwd][x][0] = sorted(list(set(words_temp_syns))) if words_temp_hyps: synsxx[kwd][x][1] = sorted(list(set(words_temp_hyps))) return synsxx
def asdict(self): ndx = np.arange(0, self.len) by_row = odict.odict() for n in ndx: by_row[n] = odict.odict() for n in by_row.keys(): for cn in self.names: by_row[n][cn] = self.col[cn][n] return by_row
def __init__(self): self.Ty = TypeContainer() PublishWellKnownTypes(self.Ty) self.recs = odict([(rName, self.Ty.get(rName)) for rName in sd.recordSchema.iterkeys()]) self.hnds = odict([(hName + 'Handle', self.Ty.get(hName + 'Handle')) for hName in sd.handleSchema]) for rec in self.recs.itervalues(): rec.handle = self.hnds[str(rec) + 'Handle'] self.Ty.NativeReader = ClassDef('NativeReader') self.Ty.NativeWriter = ClassDef('NativeWriter')
def reset(self): """ Empty the table """ self.keywords = odict() self.comments = [] self.columns = odict() self.data = None self._primary_key = None return
def test_first_and_last_key(self): # Test first and last key. o = odict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) self.assertEqual(o.firstkey(), 'a') self.assertEqual(o.lastkey(), 'd') o = odict() msg = "\"'firstkey(): ordered dictionary is empty'\"" self.assertRaisesWithMessage(msg, o.firstkey, KeyError) msg = "\"'lastkey(): ordered dictionary is empty'\"" self.assertRaisesWithMessage(msg, o.lastkey, KeyError)
def test_odict_storage(self): obj = OdictStorageObject() self.assertEqual(obj.storage, odict()) obj['foo'] = 'foo' self.assertEqual(obj.storage, odict([('foo', 'foo')])) self.assertEqual(obj['foo'], 'foo') self.assertEqual([key for key in obj], ['foo']) del obj['foo'] self.assertEqual(obj.storage, odict())
def test_casting(self): # casting to dict will fail # Reason -> http://bugs.python.org/issue1615701 # The __init__ function of dict checks wether arg is subclass of dict, # and ignores overwritten __getitem__ & co if so. # This was fixed and later reverted due to behavioural problems with # pickle. self.assertEqual(dict(odict([(1, 1)])), {1: [_nil, 1, _nil]}) # The following ways for type conversion work self.assertEqual(dict(odict([(1, 1)]).items()), {1: 1}) self.assertEqual(odict([(1, 1)]).as_dict(), {1: 1})
def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): if not hasattr(self, "__globals__") or self.__globals__ == None : self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals if ipython_globals == None: myf=self.__globals__ else: myf=ipython_globals a = odict() a['vis'] = '' a['field'] = '' a['spw'] = '' a['model'] = '' a['nterms'] = 1 a['wprojplanes'] = 1 a['complist'] = '' a['incremental'] = False a['usescratch'] = False a['async']=False a['nterms'] = { 0:odict([{'notvalue':1}, {'reffreq':''}])} ### This function sets the default values but also will return the list of ### parameters or the default value of a given parameter if(param == None): myf['__set_default_parameters'](a) elif(param == 'paramkeys'): return a.keys() else: if(paramvalue==None and subparam==None): if(a.has_key(param)): return a[param] else: return self.itsdefault(param) else: retval=a[param] if(type(a[param])==dict): for k in range(len(a[param])): valornotval='value' if(a[param][k].has_key('notvalue')): valornotval='notvalue' if((a[param][k][valornotval])==paramvalue): retval=a[param][k].copy() retval.pop(valornotval) if(subparam != None): if(retval.has_key(subparam)): retval=retval[subparam] else: retval=self.itsdefault(subparam) else: retval=self.itsdefault(subparam) return retval
def update( self ): self.detailedBalance = dict.fromkeys( self.goods, 0 ) self.globalBalance = 0 self.neededDiversity = 0 self.imports = dict() self.exports = dict() for good in self.goods: self.imports[ good ] = self.board.getImports( self.category + "." + good ) self.exports[ good ] = self.board.getExports( self.category + "." + good ) self.detailedBalance[ good ] += self.imports[ good ] - self.exports[ good ] self.globalBalance += self.imports[ good ] - self.exports[ good ] self.producers = odict() for producer in self.__producers: number = len( self.board.getObjectsByType( producer ) ) available = self.board.isAvailable( producer ) goods = dict() for good in self.goods: if self.category + "." + good in GameItemTypes.attributes[ producer ]: goods[ good ] = number * GameItemTypes.attributes[ producer ][ self.category + "." + good ] self.detailedBalance[ good ] += goods[ good ] self.globalBalance += goods[ good ] self.producers[ producer ] = ( number, available, goods ) self.detailedConsumers = odict() for detailedConsumer in self.__detailedConsumers: number = len( self.board.getObjectsByType( detailedConsumer ) ) available = self.board.isAvailable( detailedConsumer ) goods = dict() for good in self.goods: if self.category + "." + good in GameItemTypes.attributes[ detailedConsumer ]: goods[ good ] = number * GameItemTypes.attributes[ detailedConsumer ][ self.category + "." + good ] self.detailedBalance[ good ] += goods[ good ] self.globalBalance += goods[ good ] self.detailedConsumers[ detailedConsumer ] = ( number, available, goods ) self.globalConsumers = odict() for globalConsumer in self.__globalConsumers: number = len( self.board.getObjectsByType( globalConsumer ) ) available = self.board.isAvailable( globalConsumer ) goods = number * GameItemTypes.attributes[ globalConsumer ][ self.category ] self.globalBalance += goods self.globalConsumers[ globalConsumer ] = ( number, available, goods ) if number > 0: self.neededDiversity = max( self.neededDiversity, GameItemTypes.attributes[ globalConsumer ][ "NeededDiversity." + self.category ] ) self.hasGlobalConsumers = len( self.__globalConsumers ) > 0 self.globalBalanceIsOk = self.globalBalance >= 0 self.availableDiversity = len( [ good for good in self.goods if self.detailedBalance[ good ] > 0 ] ) self.availableDiversityIsOk = self.availableDiversity >= self.neededDiversity self.detailedBalanceIsOk = dict( [ ( good, balance >= 0 ) for ( good, balance ) in self.detailedBalance.iteritems() ] )
def __init__(self): self.cfg = dict() self.cfg_file = self._find_cfg() self.load_config() self.cmds = odict() self.aliases = odict() for ep in iter_entry_points(self.entry_point_keys['commands']): self.cmds[ep.name] = ep.load()(ep.name, self) for ep in iter_entry_points(self.entry_point_keys['aliases']): self.aliases[ep.name] = ep.load()() self.cmds.sort() self.aliases.sort()
def __init__(self, class_, context=None): """ :param class_: class object for creating children in test. :param context: an optional root context to test against, If None, an instance of class_ is created as root. """ self._results = odict() self.class_ = class_ self.context = context if self.context is None: self.context = class_() self._results = odict()
def __init__(self, *args, **kwargs): BaseWindow.__init__(self, *args, **kwargs) [setattr(self,k,v) for k,v in kwargs.iteritems() if k in ('settings','translator','platform','fanArt','cachesByName', 'upcoming', )] [setattr(self,k,v) for k,v in self.cachesByName.iteritems() if k in ('mythChannelIconCache','domainCache', )] self.programs = [] # [RecordedProgram] self.channelsById = None # {int:Channel} self.tunersById = None # {int:Tuner} self.listItemsByProgram = odict.odict() # {Program:ListItem} self.programsByListItemKey = odict.odict() # {ListItem:Program} self.sortBy = self.settings.get('upcoming_sort_by') self.sortAscending = self.settings.getBoolean('upcoming_sort_ascending') self.activeRenderToken = None
def __init__(self, exist_kwds, config): """Constructor. Args: exist_kwds: A list of source/sample words. # TODO(mrafi): Change config from a dictionary to depth level. config: a dictionary containing flags for hypernymns and hyponymns.""" self.ekwds = self.make_list(exist_kwds) self.config = config # config is a dictionary self.nkwds = [] self.word_dict = odict() self.filex = 'test.txt' self.kwd_list = [] self.final_word_dict = odict()
def save(self, widget, data): props = ILDAPProps(self.plugin) users = ILDAPUsersConfig(self.plugin) groups = ILDAPGroupsConfig(self.plugin) def fetch(name): name = 'ldapsettings.%s' % name __traceback_info__ = name return data.fetch(name).extracted props.uri = fetch('server.uri') props.user = fetch('server.user') password = fetch('server.password') if password is not UNSET: props.password = password # XXX: later #props.start_tls = fetch('server.start_tls') #props.tls_cacertfile = fetch('server.tls_cacertfile') #props.tls_cacertdir = fetch('server.tls_cacertdir') #props.tls_clcertfile = fetch('server.tls_clcertfile') #props.tls_clkeyfile = fetch('server.tls_clkeyfile') #props.retry_max = fetch(at('server.retry_max') #props.retry_delay = fetch('server.retry_delay') props.cache = fetch('cache.cache') props.memcached = fetch('cache.memcached') props.timeout = fetch('cache.timeout') users.baseDN = fetch('users.dn') map = odict() map.update(fetch('users.aliases_attrmap')) users_propsheet_attrmap = fetch('users.propsheet_attrmap') if users_propsheet_attrmap is not UNSET: map.update(users_propsheet_attrmap) users.attrmap = map users.scope = fetch('users.scope') users.queryFilter = fetch('users.query') objectClasses = fetch('users.object_classes') objectClasses = \ [v.strip() for v in objectClasses.split(',') if v.strip()] users.objectClasses = objectClasses groups = self.groups groups.baseDN = fetch('groups.dn') map = odict() map.update(fetch('groups.aliases_attrmap')) groups_propsheet_attrmap = fetch('groups.propsheet_attrmap') if groups_propsheet_attrmap is not UNSET: map.update(groups_propsheet_attrmap) groups.attrmap = map groups.scope = fetch('groups.scope') groups.queryFilter = fetch('groups.query') objectClasses = fetch('groups.object_classes') objectClasses = \ [v.strip() for v in objectClasses.split(',') if v.strip()] groups.objectClasses = objectClasses
def test_posix_account(self, props): ucfg = UsersConfig( baseDN='ou=defaults,dc=my-domain,dc=com', attrmap=odict(( ('rdn', 'cn'), ('id', 'cn') )), scope=SUBTREE, queryFilter='(objectClass=posixAccount)', objectClasses=['account', 'posixAccount'], defaults={} ) users = Users(props, ucfg) user = users.create('posixuser') user() self.assertEqual(sorted(user.context.attrs.items()), [ (u'cn', u'posixuser'), (u'gidNumber', u'100'), (u'homeDirectory', u'/home/posixuser'), (u'objectClass', [u'account', u'posixAccount']), (u'uid', u'posixuser'), (u'uidNumber', u'100') ]) defaults.creation_defaults['posixAccount']['loginShell'] = posix.loginShell ucfg = UsersConfig( baseDN='ou=defaults,dc=my-domain,dc=com', attrmap=odict(( ('rdn', 'uid'), ('id', 'uid') )), scope=SUBTREE, queryFilter='(objectClass=posixAccount)', objectClasses=['account', 'posixAccount'], defaults={} ) users = Users(props, ucfg) user = users.create('posixuser1') user() self.assertEqual(sorted(user.context.attrs.items()), [ (u'cn', u'posixuser1'), (u'gidNumber', u'101'), (u'homeDirectory', u'/home/posixuser1'), (u'loginShell', u'/bin/false'), (u'objectClass', [u'account', u'posixAccount']), (u'uid', u'posixuser1'), (u'uidNumber', u'101') ]) del defaults.creation_defaults['posixAccount']['loginShell']
def collect(self): """collect all data. Data is stored in a multi-level dictionary (DataTree) """ self.data = odict() is_function, datapaths = self.getDataPaths(self.tracker) # if function, no datapaths if is_function: d = self.getData(()) # save in data tree as leaf DataTree.setLeaf(self.data, ("all",), d) self.debug("%s: collecting data finished for function." % (self.tracker)) return # if no tracks, error if len(datapaths) == 0 or len(datapaths[0]) == 0: self.warn("%s: no tracks found - no output" % self.tracker) raise ValueError("no tracks found from %s" % self.tracker) # filter data paths datapaths = self.filterDataPaths(datapaths) # if no tracks, error if len(datapaths) == 0 or len(datapaths[0]) == 0: self.warn("%s: no tracks remain after filtering - no output" % self.tracker) raise ValueError("no tracks found from %s" % self.tracker) all_paths = list(itertools.product(*datapaths)) self.debug("%s: collecting data started for %i data paths" % (self.tracker, len(all_paths))) self.data = odict() for path in all_paths: d = self.getData(path) # ignore empty data sets if d == None: continue # save in data tree as leaf DataTree.setLeaf(self.data, path, d) self.debug("%s: collecting data finished for %i data paths" % (self.tracker, len(all_paths)))
def __init__(self, class_, context=None, sorted_output=False): """ ``class_`` class object for creating children in test. ``context`` an optional root context to test against, If None, an instance of class_ is created as root. """ self._results = odict() self.class_ = class_ self.context = context if self.context is None: self.context = class_() self.sorted_output = sorted_output self._results = odict()
def getDict( self, stmt ): """return results from SQL statement *stmt* as a dictionary. Example: SELECT column1, column2 FROM table Result: { 1: 2, 2: 4, 3: 2} The first column is taken as the dictionary key """ # convert to tuples e = self.execute(self.buildStatement(stmt)) columns = e.keys() result = odict() for row in e: result[row[0]] = odict( zip( columns[1:], row[1:] ) ) return result
def test_create_tree(self): self.assertEqual(create_tree(odict), odict([ ('child_0', odict([ ('subchild_0', odict()), ('subchild_1', odict()) ])), ('child_1', odict([ ('subchild_0', odict()), ('subchild_1', odict()) ])), ('child_2', odict([ ('subchild_0', odict()), ('subchild_1', odict()) ])) ]))
def _load_keys(self): self._keys = odict() self._child_dns = {} attrlist = ['dn'] if self._seckey_attrs: self._seckeys = dict() attrlist.extend(self._seckey_attrs) for key, attrs in self.search(attrlist=attrlist): try: self._keys[key] except KeyError: self._keys[key] = None self._child_dns[key] = attrs['dn'] for seckey_attr, seckey in \ self._calculate_seckeys(attrs).items(): try: self._seckeys[seckey_attr] except KeyError: self._seckeys[seckey_attr] = {} try: self._seckeys[seckey_attr][seckey] except KeyError: self._seckeys[seckey_attr][seckey] = key else: raise KeyError( u"Secondary key not unique: %s='%s'." % \ (seckey_attr, seckey)) else: raise RuntimeError(u"Key not unique: %s='%s'." % \ (self._key_attr, key))
def _resolvearg(self, arg): if isinstance(arg, _ast.Str): return repr(arg.s) elif isinstance(arg, _ast.Num): return arg.n elif isinstance(arg, _ast.Name): return arg.id elif isinstance(arg, _ast.Call): args = list() for a in arg.args: args.append(self._resolvearg(a)) kwargs = odict() for keyword in arg.keywords: kwargs[keyword.arg] = self._resolvearg(keyword.value) try: return Call(name=arg.func.id, args=args, kwargs=kwargs) except AttributeError: return Call(name=arg.func.attr, args=args, kwargs=kwargs) elif isinstance(arg, _ast.Tuple) or isinstance(arg, _ast.List): ret = list() for a in arg.elts: ret.append(self._resolvearg(a)) if isinstance(arg, _ast.Tuple): ret = tuple(ret) return ret elif isinstance(arg, _ast.Dict): ret = dict() pointer = 0 for key in arg.keys: key = self._resolvearg(key) ret[key] = self._resolvearg(arg.values[pointer]) pointer += 1 return ret
def run(): head('dict') root = dict() global root print CREATE_DELETE_ROW dict_results = { 1000: result(dict, 1000), 10000: result(dict, 10000), 100000: result(dict, 100000), 1000000: result(dict, 1000000), } head('odict') root = odict.odict() global root print CREATE_DELETE_ROW odict_results = { 1000: result(odict.odict, 1000), 10000: result(odict.odict, 10000), 100000: result(odict.odict, 100000), 1000000: result(odict.odict, 1000000), } head('relation ``dict:odict``') print RELATION_ROW for key, value in dict_results.items(): dstart, dmid, dend = value ostart, omid, oend = odict_results[key] relation_create = (omid - ostart) / (dmid - dstart) relation_delete = (oend - omid) / (dend - dmid) relation_row('creating', key, relation_create) relation_row('deleting', key, relation_delete)
def returnQuantities(runNumber): infoCollector = getInfoCollector(runNumber) quantities =[] # f = returnFile(runNumber) # for key in f.GetListOfKeys(): # if key.ReadObj().ClassName() == "PotCollection": # potCollection = key.ReadObj() for pot in getPotCollection(runNumber): for trigStat in pot.fConditionalTriggerStat: quantities.append(odict()) #quantities[-1]["runName"] = "testRunName" quantities[-1]["runName"] = infoCollector.runName.replace('run_','') quantities[-1]["potName"] = pot.GetName() quantities[-1]["condition"] = trigStat.GetName() quantities[-1]["nevents"] = trigStat.fConditions quantities[-1][""] = trigStat.fConditionANDRawSimuCCoutputTheSame quantities[-1]["fConditionANDRawSimuCCoutputNotTheSame"] = trigStat.fConditionANDRawSimuCCoutputNotTheSame quantities[-1]["fConditionANDRawSimuCCoutputNotTheSameEven"] = trigStat.fConditionANDRawSimuCCoutputNotTheSameEven quantities[-1]["fConditionANDRawSimuCCoutputNotTheSameOdd"] = trigStat.fConditionANDRawSimuCCoutputNotTheSameOdd quantities[-1]["fConditionANDRawSimuCCoutputNotTheSameEvenOdd"] = trigStat.fConditionANDRawSimuCCoutputNotTheSameEvenOdd quantities[-1]["fConditionANDTriggerRaw0Simu0"] = trigStat.fConditionANDTriggerRaw0Simu0 quantities[-1]["fConditionANDTriggerRaw1Simu0"] = trigStat.fConditionANDTriggerRaw1Simu0 quantities[-1]["fConditionANDTriggerRaw0Simu1"] = trigStat.fConditionANDTriggerRaw0Simu1 quantities[-1]["fConditionANDTriggerRaw1Simu1"] = trigStat.fConditionANDTriggerRaw1Simu1 for potType in (ROOT.ERawOrSimu.kRaw,ROOT.ERawOrSimu.kSimu): for trigStat in pot.GetPot(potType).fConditionalTriggerStat: if quantities[-1]["condition"] == trigStat.GetName(): #print "fConditionANDTrigger"+str(ROOT.PreTriggerStat.RawOrSimuString(potType)) quantities[-1]["fConditionANDTrigger"+str(ROOT.PreTriggerStat.RawOrSimuString(potType))] = trigStat.fConditionANDTrigger assert(len(quantities)!=0) return quantities
def nodespaces(self): """A storage and general way to access our nodespaces. An ``AttributedNode`` uses this to store the ``attrs`` nodespace i.e. """ if self._nodespaces is None: self._nodespaces = odict() self._nodespaces['__children__'] = self return self._nodespaces
def test_pop(self): # Test pop and popitem o = odict([(1, 'a'), (2, 'b')]) self.assertRaisesWithMessage('3', o.pop, KeyError, 3) self.assertEqual(o.pop(3, 'foo'), 'foo') self.assertEqual(o.pop(2), 'b') self.assertEqual(o.popitem(), (1, 'a')) msg = "\"'popitem(): ordered dictionary is empty'\"" self.assertRaisesWithMessage(msg, o.popitem, KeyError)
def __init__(self, decoratorname=None, astnode=None, buffer=[]): PythonNode.__init__(self, None, astnode, buffer) CallableArguments.__init__(self) self.decoratorname = decoratorname self._args_orgin = list() self._kwargs_orgin = odict() self.parser = self.parserfactory(self) if astnode is not None: self.parser()
def test_swap(self): # Test ``swap`` o = odict([('0', 'a'), ('1', 'b'), ('2', 'c'), ('3', 'd'), ('4', 'e')]) # Cannot swap same key with self.assertRaises(ValueError): o.swap('0', '0') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e']) # Case first 2, a < b o.swap('0', '1') self.assertEqual(o.keys(), ['1', '0', '2', '3', '4']) self.assertEqual(o.values(), ['b', 'a', 'c', 'd', 'e']) # Case first 2, a > b o.swap('0', '1') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e']) # Case last 2, a < b o.swap('3', '4') self.assertEqual(o.keys(), ['0', '1', '2', '4', '3']) self.assertEqual(o.values(), ['a', 'b', 'c', 'e', 'd']) # Case last 2, a > b o.swap('3', '4') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e']) # Case neighbors, a < b o.swap('1', '2') self.assertEqual(o.keys(), ['0', '2', '1', '3', '4']) self.assertEqual(o.values(), ['a', 'c', 'b', 'd', 'e']) # Case neighbors, a > b o.swap('1', '2') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e']) # Case non neighbors, one key first, a < b o.swap('0', '2') self.assertEqual(o.keys(), ['2', '1', '0', '3', '4']) self.assertEqual(o.values(), ['c', 'b', 'a', 'd', 'e']) # Case non neighbors, one key first, a > b o.swap('0', '2') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e']) # Case non neighbors, one key last, a < b o.swap('2', '4') self.assertEqual(o.keys(), ['0', '1', '4', '3', '2']) self.assertEqual(o.values(), ['a', 'b', 'e', 'd', 'c']) # Case non neighbors, one key last, a > b o.swap('2', '4') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e']) # Case non neighbors, a < b o.swap('1', '3') self.assertEqual(o.keys(), ['0', '3', '2', '1', '4']) self.assertEqual(o.values(), ['a', 'd', 'c', 'b', 'e']) # Case non neighbors, a > b o.swap('1', '3') self.assertEqual(o.keys(), ['0', '1', '2', '3', '4']) self.assertEqual(o.values(), ['a', 'b', 'c', 'd', 'e'])
def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): if not hasattr(self, "__globals__") or self.__globals__ == None: self.__globals__ = sys._getframe(len(inspect.stack()) - 1).f_globals if ipython_globals == None: myf = self.__globals__ else: myf = ipython_globals a = odict() a['muser'] = globalpy.muser_global_muser a['inputfile'] = '' a['start'] = '' a['integral'] = 1 a['niter'] = 1 a['hourangle'] = 999 a['declination'] = 999 a['correct'] = 0 a['calibration'] = True a['bigfile'] = False a['debug'] = globalpy.muser_global_debug ### This function sets the default values but also will return the list of ### parameters or the default value of a given parameter if (param == None): myf['__set_default_parameters'](a) elif (param == 'paramkeys'): return a.keys() else: if (paramvalue == None and subparam == None): if (a.has_key(param)): return a[param] else: return self.itsdefault(param) else: retval = a[param] if (type(a[param]) == dict): for k in range(len(a[param])): valornotval = 'value' if (a[param][k].has_key('notvalue')): valornotval = 'notvalue' if ((a[param][k][valornotval]) == paramvalue): retval = a[param][k].copy() retval.pop(valornotval) if (subparam != None): if (retval.has_key(subparam)): retval = retval[subparam] else: retval = self.itsdefault(subparam) else: retval = self.itsdefault(subparam) return retval
def test_reverse_iteration(self): # Reverse iteration o = odict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) self.assertEqual([x for x in o.riterkeys()], ['d', 'c', 'b', 'a']) self.assertEqual(o.rkeys(), ['d', 'c', 'b', 'a']) self.assertEqual([x for x in o.ritervalues()], [4, 3, 2, 1]) self.assertEqual(o.rvalues(), [4, 3, 2, 1]) self.assertEqual([x for x in o.riteritems()], [('d', 4), ('c', 3), ('b', 2), ('a', 1)]) self.assertEqual(o.ritems(), [('d', 4), ('c', 3), ('b', 2), ('a', 1)])
def create_odict_from_items(name, key, dictlst): """ Construct an ordered dictionary from a list of dictionaries, using the key from the dictionary. """ def _generator(): for delement in dictlst: dvalues = dict((k, v) for (k, v) in delement.iteritems()) yield (delement[key], Struct(name, **dvalues)) return odict(_generator())
def test_compound_blueprint_structural_children(self): # Compound with structural compound as child value = { 'inner': 'Value 1 from parent', 'inner2': 'Value 2 from parent', } compound = factory('compound', name='COMPOUND', value=value) structural = compound['STRUCTURAL'] = factory( 'compound', props={'structural': True}) structural['inner'] = factory('text') structural['inner2'] = factory('text', props={'required': True}) self.check_output( """ <div> <input class="text" id="input-COMPOUND-inner" name="COMPOUND.inner" type="text" value="Value 1 from parent"/> <input class="required text" id="input-COMPOUND-inner2" name="COMPOUND.inner2" required="required" type="text" value="Value 2 from parent"/> </div> """, fxml(tag('div', compound()))) self.assertEqual(compound.treerepr().split('\n'), [ "<class 'yafowil.base.Widget'>: COMPOUND", " <class 'yafowil.base.Widget'>: STRUCTURAL", " <class 'yafowil.base.Widget'>: inner", " <class 'yafowil.base.Widget'>: inner2", "" ]) data = compound.extract({ 'COMPOUND.inner': 'newvalue', 'COMPOUND.inner2': '', }) self.assertEqual(data.name, 'COMPOUND') self.assertEqual(data.value, { 'inner2': 'Value 2 from parent', 'inner': 'Value 1 from parent' }) expected = odict() expected['inner'] = 'newvalue' expected['inner2'] = '' self.assertEqual(data.extracted, expected) data_inner = data['inner'] self.assertEqual(data_inner.name, 'inner') self.assertEqual(data_inner.value, 'Value 1 from parent') self.assertEqual(data_inner.extracted, 'newvalue') self.assertEqual(data_inner.errors, []) data_inner2 = data['inner2'] self.assertEqual(data_inner2.name, 'inner2') self.assertEqual(data_inner2.value, 'Value 2 from parent') self.assertEqual(data_inner2.extracted, '') self.assertEqual(data_inner2.errors, [ExtractionError('Mandatory field was empty')])
def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): if not hasattr(self, "__globals__") or self.__globals__ == None: self.__globals__ = sys._getframe(len(inspect.stack()) - 1).f_globals if ipython_globals == None: myf = self.__globals__ else: myf = ipython_globals a = odict() a['vis'] = '' a['outputvis'] = '' a['timerange'] = '' a['spw'] = '' a['subtime1'] = '' a['subtime2'] = '' a['splitsel'] = True a['reverse'] = False a['overwrite'] = False ### This function sets the default values but also will return the list of ### parameters or the default value of a given parameter if (param == None): myf['__set_default_parameters'](a) elif (param == 'paramkeys'): return a.keys() else: if (paramvalue == None and subparam == None): if (a.has_key(param)): return a[param] else: return self.itsdefault(param) else: retval = a[param] if (type(a[param]) == dict): for k in range(len(a[param])): valornotval = 'value' if (a[param][k].has_key('notvalue')): valornotval = 'notvalue' if ((a[param][k][valornotval]) == paramvalue): retval = a[param][k].copy() retval.pop(valornotval) if (subparam != None): if (retval.has_key(subparam)): retval = retval[subparam] else: retval = self.itsdefault(subparam) else: retval = self.itsdefault(subparam) return retval
def ldap_rcfg(self): settings = self.attrs attr_map = odict(settings.roles_aliases_attrmap.items()) return RolesConfig( baseDN=settings.roles_dn, attrmap=attr_map, scope=int(settings.roles_scope), queryFilter=settings.roles_query, objectClasses=settings.roles_object_classes, # member_relation=settings.roles_relation, defaults=factory_defaults.role)
def __init__(self, *args, **kwargs): BaseWindow.__init__(self, *args, **kwargs) # inject dependencies from constructor [setattr(self,k,v) for k,v in kwargs.iteritems() if k in ('settings', 'translator', 'platform', 'fanArt', 'cachesByName', 'bus',)] [setattr(self,k,v) for k,v in self.cachesByName.iteritems()] self.t = self.translator.get self.programs = [] # [RecordedProgram] self.allGroupTitle = self.t(m.ALL_RECORDINGS) self.activeRenderToken = None self.groupsByTitle = odict.odict() # {unicode:Group} self.groupsListItems = [] self.activeGroup = None self.lastFocusId = None self.sameBackgroundCache = {} # {title:filepath} self.bus.register(self) self.GROUP_SORT_BY = odict.odict([ ('Title', {'translation_id': m.TITLE, 'reverse': False, 'sorter' : lambda g: [g.title, u'0000'][g.title == self.allGroupTitle]}), ('Date', {'translation_id': m.DATE, 'reverse': True, 'sorter' : lambda g: [g.programs[0].starttimeAsTime(), datetime.datetime(datetime.MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)][g.title == self.allGroupTitle]})]) self.dirty = False
def tget_defaults(param=None): myf = stack_frame_find() a = odict() a['task'] = '' a['savefile'] = '' if (param == None): myf['__set_default_parameters'](a) elif (param == 'paramkeys'): return a.keys() else: if (a.has_key(param)): return a[param]
def test3_hc(topo, ncgic, nhc) : # Copy over fgice and fgrnd # The values of these might have to change a bit, but # not the structure. ovars = odict() ovars['fgice'] = gread(topo, 'fgice') ovars['fgrnd'] = gread(topo, 'fgrnd') fgice = ovars['fgice'][0] fgrnd = ovars['fgrnd'][0] # Allocate but only read things we need now zatmo_t = gread(topo, 'zatmo') tlandi_t = gread(ncgic, 'tlandi') snowli_t = gread(ncgic, 'snowli') ovars['elevhc'] = prepend_dim(zatmo_t, 'nhc', nhc) ovars['tlandi'] = prepend_dim(tlandi_t, 'nhc', nhc) ovars['snowli'] = prepend_dim(snowli_t, 'nhc', nhc) ovars['fhc'] = (np.zeros(ovars['snowli'][0].shape), ovars['snowli'][1], 'f8') elevhc = ovars['elevhc'][0] tlandi = ovars['tlandi'][0] snowli = ovars['snowli'][0] fhc = ovars['fhc'][0] # Make height-classified versions of vars by copying for ihc in range(0,nhc) : elevhc[ihc,:] = zatmo_t[0][:] tlandi[ihc,:] = tlandi_t[0][:] snowli[ihc,:] = snowli_t[0][:] fhc[:] = 1.0 / float(nhc) # --------------------------------------------- jm = snowli.shape[1] im = snowli.shape[2] print fgrnd.shape, jm, im for j in range(0,jm) : for i in range(0, im) : if fgice[j,i] == 0 : continue elevhc[0,j,i] = max(0, zatmo_t[0][j,i] - 300) elevhc[1,j,i] = zatmo_t[0][j,i] elevhc[2,j,i] = zatmo_t[0][j,i] + 300 # elevhc[0,j,i] = 0 # elevhc[1,j,i] = 1000 # elevhc[2,j,i] = 2000 fhc[0,:] = .25 fhc[1,:] = .5 fhc[2,:] = .25 return ovars
def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): if not hasattr(self, "__globals__") or self.__globals__ == None : self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals if ipython_globals == None: myf=self.__globals__ else: myf=ipython_globals a = odict() a['infile'] = '' a['is_loop_mode'] = True a['mode'] = True a['band'] = None a['channel'] = 4 a['weight'] = 0 a['polarization'] = 0 a['movera'] = 0 a['movedec'] = 0 a['P_ANGLE'] = False a['fits'] = 0 a['debug'] = globalpy.muser_global_debug a['outdir'] = '' ### This function sets the default values but also will return the list of ### parameters or the default value of a given parameter if(param == None): myf['__set_default_parameters'](a) elif(param == 'paramkeys'): return a.keys() else: if(paramvalue==None and subparam==None): if(a.has_key(param)): return a[param] else: return self.itsdefault(param) else: retval=a[param] if(type(a[param])==dict): for k in range(len(a[param])): valornotval='value' if(a[param][k].has_key('notvalue')): valornotval='notvalue' if((a[param][k][valornotval])==paramvalue): retval=a[param][k].copy() retval.pop(valornotval) if(subparam != None): if(retval.has_key(subparam)): retval=retval[subparam] else: retval=self.itsdefault(subparam) else: retval=self.itsdefault(subparam) return retval
def test_insertafter(self): o = odict([('0', 'a')]) with self.assertRaises(ValueError): o.insertafter('0', '0', 'a') with self.assertRaises(KeyError): o.insertafter('x', '1', 'b') o.insertafter('0', '1', 'b') self.assertEqual(o.keys(), ['0', '1']) self.assertEqual(o.values(), ['a', 'b']) o.insertafter('0', '2', 'c') self.assertEqual(o.keys(), ['0', '2', '1']) self.assertEqual(o.values(), ['a', 'c', 'b'])
class CheckForDupesUsing(object): # TODO: Rename to RecordingDupMethodType NONE = 1 SUBTITLE = 2 DESCRIPTION = 4 SUBTITLE_AND_DESCRIPTION = 6 SUBTITLE_THEN_DESCRIPTION = 8 # TODO: Verify if exists in protocol 40 translations = odict([(NONE, 145), (SUBTITLE, 146), (DESCRIPTION, 147), (SUBTITLE_AND_DESCRIPTION, 148), (SUBTITLE_THEN_DESCRIPTION, 200)])
class AppRoot(FactoryNode): """Application root. """ factories = odict() @instance_property def properties(self): return Properties() @instance_property def metadata(self): return Metadata()
def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): if not hasattr(self, "__globals__") or self.__globals__ == None: self.__globals__ = sys._getframe(len(inspect.stack()) - 1).f_globals if ipython_globals == None: myf = self.__globals__ else: myf = ipython_globals a = odict() a['subarray'] = 1 a['is_loop_mode'] = True a['start_time'] = '' a['end_time'] = '' a['task_type'] = '' a['time_average'] = '' a['time_interval'] = None a['debug'] = globalpy.muser_global_debug ### This function sets the default values but also will return the list of ### parameters or the default value of a given parameter if (param == None): myf['__set_default_parameters'](a) elif (param == 'paramkeys'): return a.keys() else: if (paramvalue == None and subparam == None): if (a.has_key(param)): return a[param] else: return self.itsdefault(param) else: retval = a[param] if (type(a[param]) == dict): for k in range(len(a[param])): valornotval = 'value' if (a[param][k].has_key('notvalue')): valornotval = 'notvalue' if ((a[param][k][valornotval]) == paramvalue): retval = a[param][k].copy() retval.pop(valornotval) if (subparam != None): if (retval.has_key(subparam)): retval = retval[subparam] else: retval = self.itsdefault(subparam) else: retval = self.itsdefault(subparam) return retval
def __init__(self): self.nsReader = 'Internal.Metadata.NativeFormat' self.Ty = TypeContainer() PublishWellKnownTypes(self.Ty) self.Ty.MetadataRecord = StructDef('MetadataRecord', flags = AccessFlags.Public | TypeFlags.Partial) self.Ty.Handle = self.Ty.MetadataRecord self.Ty.NativeWriter = ClassDef('NativeWriter') self.records = odict([(rName, self.CreateRecord(rName, rMembers)) for (rName,rMembers) in sd.recordSchema.iteritems()])
def pointcal_defaults(param=None): a = inspect.stack() stacklevel = 0 for k in range(len(a)): if (string.find(a[k][1], 'ipython console') > 0): stacklevel = k myf = sys._getframe(stacklevel).f_globals a = odict() a['vis'] = '' a['model'] = '' a['caltable'] = '' a['field'] = '' a['spw'] = '' a['selectdata'] = { 1: { 'value': False }, 0: odict([{ 'value': True }, { 'timerange': '' }, { 'uvrange': '' }, { 'antenna': '' }, { 'scan': '' }, { 'msselect': '' }]) } a['solint'] = 0.0 if (param == None): myf['__set_default_parameters'](a) elif (param == 'paramkeys'): return a.keys() else: if (a.has_key(param)): return a[param]
def test_compound_blueprint_value_callbacks(self): # Check compound with value callbacks def val(widget, data): return 'val F1' value = { 'f1': val, } compound = factory('compound', 'comp', value=value) compound['f1'] = factory('text') self.assertEqual( compound(), ('<input class="text" id="input-comp-f1" name="comp.f1" ' 'type="text" value="val F1" />')) data = compound.extract({'comp.f1': 'New val 1'}) self.assertEqual(data.name, 'comp') self.assertEqual(data.value, {'f1': val}) expected = odict() expected['f1'] = 'New val 1' self.assertEqual(data.extracted, expected) self.assertEqual(data.errors, []) def value(widget, data): return {'f1': 'F1 Val'} compound = factory('compound', 'comp', value=value) compound['f1'] = factory('text') self.assertEqual( compound(), ('<input class="text" id="input-comp-f1" name="comp.f1" ' 'type="text" value="F1 Val" />')) data = compound.extract({'comp.f1': 'New val 1'}) self.assertEqual(data.name, 'comp') self.assertEqual(data.value, {'f1': 'F1 Val'}) expected = odict() expected['f1'] = 'New val 1' self.assertEqual(data.extracted, expected) self.assertEqual(data.errors, [])
def parse_init_constructor(myclasses_array_dict): # parse 1-times, process self for class_name, one_myclass in myclasses_array_dict.iteritems(): ''' - if no init, append one - if mult-init, rename as: init, init2, init3, ... - re-construct init as dict: "init":{ "scope":"public", "paremeter":"", "argument":{"para1":"arg1","para2":"arg2"} - Also append this info into vtable of supers for init ''' if len(one_myclass[const.m_dict['init']]) == 0: member_init = copy.deepcopy(const.member_init) member_init[const.func.name] = class_name one_myclass[const.m_dict['init']].append(member_init) for method in one_myclass[const.m_dict['init']]: method_setter = odict([('scope', method[const.func.scope]), \ ('name', method[const.func.name]), \ ('params', method[const.func.params]), \ ('args', method[const.func.args]), \ ('setters', odict())]) one_myclass[const.m_dict['init_setter']].append(method_setter) # if have params, try match with vars (no-static) if method[const.func.params]: params,args = parse_parameters(method[const.func.params]) for arg in args: for variable in one_myclass[const.m_dict['var']]: if variable[const.func.static] != 'True' \ and (variable[const.func.name].lower() == arg \ or variable[const.func.name].lower() == '_' + arg \ or variable[const.func.name].lower() == arg + '_'): method_setter['setters'][variable[const.func.name]] = arg break # exit find first var # parse 2-times, process supers for class_name, one_myclass in myclasses_array_dict.iteritems(): super_setter = one_myclass[const.m_dict['super_setter']] for super_name,superclass in one_myclass[const.m_dict['super']].iteritems(): super_class = convert_to_class(myclasses_array_dict, super_name) super_setter[super_name] = super_class[const.m_dict['init_setter']]
def __init__(self, fic_log=None, fic_sql=None, tipo_log=0, tipo_sql=0): self.__contador = 0 self.__error = None self.__cam_valor = odict() self.__log = None self.__sql = None self.__ficlog = fic_log self.__ficsql = fic_sql self.__tipo_log = tipo_log self.__tipo_sql = tipo_sql self.db = DbPostgres() self.db.auto_commit = False self.__cam_filtros = dict()
def renderEpisodeColumn(self, myRenderToken, myGroup): results = odict.odict() for (listItem, program) in myGroup.programsByListItem.items()[:]: if self.closed or xbmc.abortRequested or myRenderToken != self.activeRenderToken: return try: season, episode = self.fanArt.getSeasonAndEpisode(program) if season and episode: results[listItem] = '%sx%s' % (season, episode) self.updateListItemProperty(listItem, 'episode', results[listItem]) except: log.exception('Rendering season and episode for program %s' % safe_str(program.fullTitle())) myGroup.episodesDone = True
def _read_all_giss_struct(fname): topo = odict.odict() for rec in giss.gissfile.reader(fname): val = np.zeros(rec.data.shape) # Promote to double name = rec.var.lower() val[:] = rec.data[:] topo[name] = giutil.Struct({ 'name': name, 'val': val, 'sdims': (u'jm', u'im'), 'dtype': 'f8' }) return topo
def create(self): body = MessageBody( self, { 'area': None, 'klines': odict.odict(), 'seenby': [], 'text': '', 'body': '', }) body.__struct__ = self return body
def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): if not hasattr(self, "__globals__") or self.__globals__ == None: self.__globals__ = sys._getframe(len(inspect.stack()) - 1).f_globals if ipython_globals == None: myf = self.__globals__ else: myf = ipython_globals a = odict() a['cdate'] = '2013-12-23' a['ctime'] = '0:0:0' a['cplate'] = 'sun' a['ra'] = 0. a['dec'] = 0. a['debug'] = globalpy.muser_global_debug ### This function sets the default values but also will return the list of ### parameters or the default value of a given parameter if (param == None): myf['__set_default_parameters'](a) elif (param == 'paramkeys'): return a.keys() else: if (paramvalue == None and subparam == None): if (a.has_key(param)): return a[param] else: return self.itsdefault(param) else: retval = a[param] if (type(a[param]) == dict): for k in range(len(a[param])): valornotval = 'value' if (a[param][k].has_key('notvalue')): valornotval = 'notvalue' if ((a[param][k][valornotval]) == paramvalue): retval = a[param][k].copy() retval.pop(valornotval) if (subparam != None): if (retval.has_key(subparam)): retval = retval[subparam] else: retval = self.itsdefault(subparam) else: retval = self.itsdefault(subparam) return retval
class CheckForDupesIn(object): """ RecordingDupInType: kDupsInRecorded = 0x01, 1 kDupsInOldRecorded = 0x02, 2 kDupsInAll = 0x0F, 15 """ CURRENT_RECORDINGS = 1 PREVIOUS_RECORDINGS = 2 ALL_RECORDINGS = 15 translations = odict([(ALL_RECORDINGS, 153), (CURRENT_RECORDINGS, 149), (PREVIOUS_RECORDINGS, 150)])
def __init__(self, *args, **kwargs): BaseWindow.__init__(self, *args, **kwargs) [setattr(self,k,v) for k,v in kwargs.iteritems() if k in ('settings', 'translator', 'platform', 'fanArt', 'cachesByName',)] [setattr(self,k,v) for k,v in self.cachesByName.iteritems() if k in ('mythChannelIconCache', 'domainCache')] self.channels = None # Channels sorted and merged (if multiple tuners) self.channelsById = None # {int channelId:Channel} self.programs = None # [TVProgram] self.listItemsByChannel = odict() # {Channel:ListItem} self.lastSelected = int(self.settings.get('livetv_last_selected')) self.activeRenderToken = None self.tvQueue = collections.deque() # Channels showing a tv program that needs poster lookup self.movieQueue = collections.deque() # Channels showing a movie that needs poster lookup
def get_converted_json_schema_for_angular(self): def convert_type(type_name): type_map = { 'textfield': 'string', 'checkbox': 'string', 'button': 'string', 'radio': 'string' } return type_map.get(type_name, type_name) def convert_widget(input_type_name): input_type_map = { 'text': 'string', 'checkbox': 'checkbox', 'radio': 'radio', 'button': 'button' } return input_type_map.get(input_type_name, input_type_name) schema_json_new = {"properties": odict()} if self.schema_json: schema_json = json.loads(self.schema_json) for field in schema_json.get('components'): field_dict = { "type": convert_type(field.get('type')), "title": field.get('label', ''), "widget": convert_widget(field.get('inputType', field.get('type'))), "description": field.get('description', ''), "placeholder": field.get('placeholder', '') } if field.get('type') == 'radio': field_dict["oneOf"] = [] for option in field.get('values'): field_dict["oneOf"].append({ "description": option.get('label'), "enum": [option.get('value')] }) if field.get('type') == 'button': if schema_json_new.has_key('buttons'): field_dict['label'] = field_dict['title'] schema_json_new['buttons'].append(field_dict) else: schema_json_new['buttons'] = [field_dict] else: schema_json_new["properties"][field['key'].replace('undefined', '')] = field_dict # import pdb;pdb.set_trace() # schema_json_new["required"] = ["email", "password", "rememberMe"] return schema_json_new