code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def formatElement(self, kw, format='elegant'): """ convert json/dict of element configuration into elegant/mad format :param kw: keyword """ etype = self.getElementType(kw) econf_dict = self.getElementConf(kw) econf_str = '' for k, v in econf_dict.items(): econf_str += (k + ' = ' + '"' + str(v) + '"' + ', ') if format == 'elegant': fmtstring = '{eid:<10s}:{etype:>10s}, {econf}'.format(eid=kw.upper(), etype=etype.upper(), econf=econf_str[ :-2]) # [:-2] slicing to remove trailing space and ',' elif format == 'mad': raise NotImplementedError("Not implemented, yet") return fmtstring
def function[formatElement, parameter[self, kw, format]]: constant[ convert json/dict of element configuration into elegant/mad format :param kw: keyword ] variable[etype] assign[=] call[name[self].getElementType, parameter[name[kw]]] variable[econf_dict] assign[=] call[name[self].getElementConf, parameter[name[kw]]] variable[econf_str] assign[=] constant[] for taget[tuple[[<ast.Name object at 0x7da1b0804580>, <ast.Name object at 0x7da1b08050c0>]]] in starred[call[name[econf_dict].items, parameter[]]] begin[:] <ast.AugAssign object at 0x7da1b0804910> if compare[name[format] equal[==] constant[elegant]] begin[:] variable[fmtstring] assign[=] call[constant[{eid:<10s}:{etype:>10s}, {econf}].format, parameter[]] return[name[fmtstring]]
keyword[def] identifier[formatElement] ( identifier[self] , identifier[kw] , identifier[format] = literal[string] ): literal[string] identifier[etype] = identifier[self] . identifier[getElementType] ( identifier[kw] ) identifier[econf_dict] = identifier[self] . identifier[getElementConf] ( identifier[kw] ) identifier[econf_str] = literal[string] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[econf_dict] . identifier[items] (): identifier[econf_str] +=( identifier[k] + literal[string] + literal[string] + identifier[str] ( identifier[v] )+ literal[string] + literal[string] ) keyword[if] identifier[format] == literal[string] : identifier[fmtstring] = literal[string] . identifier[format] ( identifier[eid] = identifier[kw] . identifier[upper] (), identifier[etype] = identifier[etype] . identifier[upper] (), identifier[econf] = identifier[econf_str] [ :- literal[int] ]) keyword[elif] identifier[format] == literal[string] : keyword[raise] identifier[NotImplementedError] ( literal[string] ) keyword[return] identifier[fmtstring]
def formatElement(self, kw, format='elegant'): """ convert json/dict of element configuration into elegant/mad format :param kw: keyword """ etype = self.getElementType(kw) econf_dict = self.getElementConf(kw) econf_str = '' for (k, v) in econf_dict.items(): econf_str += k + ' = ' + '"' + str(v) + '"' + ', ' # depends on [control=['for'], data=[]] if format == 'elegant': fmtstring = '{eid:<10s}:{etype:>10s}, {econf}'.format(eid=kw.upper(), etype=etype.upper(), econf=econf_str[:-2]) # depends on [control=['if'], data=[]] # [:-2] slicing to remove trailing space and ',' elif format == 'mad': raise NotImplementedError('Not implemented, yet') # depends on [control=['if'], data=[]] return fmtstring
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): """Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. Otherwise, it is also valid for none of the flags to be set. flag_values: An optional FlagValues instance to validate against. """ def validate_mutual_exclusion(flags_dict): flag_count = sum(1 for val in flags_dict.values() if val is not None) if flag_count == 1 or (not required and flag_count == 0): return True message = ('%s one of (%s) must be specified.' % ('Exactly' if required else 'At most', ', '.join(flag_names))) raise ValidationError(message) register_multi_flags_validator( flag_names, validate_mutual_exclusion, flag_values=flag_values)
def function[mark_flags_as_mutual_exclusive, parameter[flag_names, required, flag_values]]: constant[Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. Otherwise, it is also valid for none of the flags to be set. flag_values: An optional FlagValues instance to validate against. ] def function[validate_mutual_exclusion, parameter[flags_dict]]: variable[flag_count] assign[=] call[name[sum], parameter[<ast.GeneratorExp object at 0x7da207f01300>]] if <ast.BoolOp object at 0x7da20c6c6980> begin[:] return[constant[True]] variable[message] assign[=] binary_operation[constant[%s one of (%s) must be specified.] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.IfExp object at 0x7da2054a6e30>, <ast.Call object at 0x7da2054a7640>]]] <ast.Raise object at 0x7da2054a4370> call[name[register_multi_flags_validator], parameter[name[flag_names], name[validate_mutual_exclusion]]]
keyword[def] identifier[mark_flags_as_mutual_exclusive] ( identifier[flag_names] , identifier[required] = keyword[False] , identifier[flag_values] = identifier[FLAGS] ): literal[string] keyword[def] identifier[validate_mutual_exclusion] ( identifier[flags_dict] ): identifier[flag_count] = identifier[sum] ( literal[int] keyword[for] identifier[val] keyword[in] identifier[flags_dict] . identifier[values] () keyword[if] identifier[val] keyword[is] keyword[not] keyword[None] ) keyword[if] identifier[flag_count] == literal[int] keyword[or] ( keyword[not] identifier[required] keyword[and] identifier[flag_count] == literal[int] ): keyword[return] keyword[True] identifier[message] =( literal[string] % ( literal[string] keyword[if] identifier[required] keyword[else] literal[string] , literal[string] . identifier[join] ( identifier[flag_names] ))) keyword[raise] identifier[ValidationError] ( identifier[message] ) identifier[register_multi_flags_validator] ( identifier[flag_names] , identifier[validate_mutual_exclusion] , identifier[flag_values] = identifier[flag_values] )
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): """Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. Otherwise, it is also valid for none of the flags to be set. flag_values: An optional FlagValues instance to validate against. """ def validate_mutual_exclusion(flags_dict): flag_count = sum((1 for val in flags_dict.values() if val is not None)) if flag_count == 1 or (not required and flag_count == 0): return True # depends on [control=['if'], data=[]] message = '%s one of (%s) must be specified.' % ('Exactly' if required else 'At most', ', '.join(flag_names)) raise ValidationError(message) register_multi_flags_validator(flag_names, validate_mutual_exclusion, flag_values=flag_values)
async def _queue(self, ctx, page: int = 1): """ Shows the player's queue. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send('There\'s nothing in the queue! Why not queue something?') items_per_page = 10 pages = math.ceil(len(player.queue) / items_per_page) start = (page - 1) * items_per_page end = start + items_per_page queue_list = '' for index, track in enumerate(player.queue[start:end], start=start): queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\n' embed = discord.Embed(colour=discord.Color.blurple(), description=f'**{len(player.queue)} tracks**\n\n{queue_list}') embed.set_footer(text=f'Viewing page {page}/{pages}') await ctx.send(embed=embed)
<ast.AsyncFunctionDef object at 0x7da1b0108a30>
keyword[async] keyword[def] identifier[_queue] ( identifier[self] , identifier[ctx] , identifier[page] : identifier[int] = literal[int] ): literal[string] identifier[player] = identifier[self] . identifier[bot] . identifier[lavalink] . identifier[players] . identifier[get] ( identifier[ctx] . identifier[guild] . identifier[id] ) keyword[if] keyword[not] identifier[player] . identifier[queue] : keyword[return] keyword[await] identifier[ctx] . identifier[send] ( literal[string] ) identifier[items_per_page] = literal[int] identifier[pages] = identifier[math] . identifier[ceil] ( identifier[len] ( identifier[player] . identifier[queue] )/ identifier[items_per_page] ) identifier[start] =( identifier[page] - literal[int] )* identifier[items_per_page] identifier[end] = identifier[start] + identifier[items_per_page] identifier[queue_list] = literal[string] keyword[for] identifier[index] , identifier[track] keyword[in] identifier[enumerate] ( identifier[player] . identifier[queue] [ identifier[start] : identifier[end] ], identifier[start] = identifier[start] ): identifier[queue_list] += literal[string] identifier[embed] = identifier[discord] . identifier[Embed] ( identifier[colour] = identifier[discord] . identifier[Color] . identifier[blurple] (), identifier[description] = literal[string] ) identifier[embed] . identifier[set_footer] ( identifier[text] = literal[string] ) keyword[await] identifier[ctx] . identifier[send] ( identifier[embed] = identifier[embed] )
async def _queue(self, ctx, page: int=1): """ Shows the player's queue. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue: return await ctx.send("There's nothing in the queue! Why not queue something?") # depends on [control=['if'], data=[]] items_per_page = 10 pages = math.ceil(len(player.queue) / items_per_page) start = (page - 1) * items_per_page end = start + items_per_page queue_list = '' for (index, track) in enumerate(player.queue[start:end], start=start): queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\n' # depends on [control=['for'], data=[]] embed = discord.Embed(colour=discord.Color.blurple(), description=f'**{len(player.queue)} tracks**\n\n{queue_list}') embed.set_footer(text=f'Viewing page {page}/{pages}') await ctx.send(embed=embed)
def transform(self,x,inds=None,labels = None): """return a transformation of x using population outputs""" if inds: # return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) # for I in inds)).transpose() return np.asarray( [self.out(I,x,labels,self.otype) for I in inds]).transpose() elif self._best_inds: # return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) # for I in self._best_inds)).transpose() return np.asarray( [self.out(I,x,labels,self.otype) for I in self._best_inds]).transpose() else: return x
def function[transform, parameter[self, x, inds, labels]]: constant[return a transformation of x using population outputs] if name[inds] begin[:] return[call[call[name[np].asarray, parameter[<ast.ListComp object at 0x7da1b197d8a0>]].transpose, parameter[]]]
keyword[def] identifier[transform] ( identifier[self] , identifier[x] , identifier[inds] = keyword[None] , identifier[labels] = keyword[None] ): literal[string] keyword[if] identifier[inds] : keyword[return] identifier[np] . identifier[asarray] ( [ identifier[self] . identifier[out] ( identifier[I] , identifier[x] , identifier[labels] , identifier[self] . identifier[otype] ) keyword[for] identifier[I] keyword[in] identifier[inds] ]). identifier[transpose] () keyword[elif] identifier[self] . identifier[_best_inds] : keyword[return] identifier[np] . identifier[asarray] ( [ identifier[self] . identifier[out] ( identifier[I] , identifier[x] , identifier[labels] , identifier[self] . identifier[otype] ) keyword[for] identifier[I] keyword[in] identifier[self] . identifier[_best_inds] ]). identifier[transpose] () keyword[else] : keyword[return] identifier[x]
def transform(self, x, inds=None, labels=None): """return a transformation of x using population outputs""" if inds: # return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) # for I in inds)).transpose() return np.asarray([self.out(I, x, labels, self.otype) for I in inds]).transpose() # depends on [control=['if'], data=[]] elif self._best_inds: # return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) # for I in self._best_inds)).transpose() return np.asarray([self.out(I, x, labels, self.otype) for I in self._best_inds]).transpose() # depends on [control=['if'], data=[]] else: return x
def create_user(self, user): """ Creates a new user. :param user: The user object to be created. :type user: ``dict`` """ data = self._create_user_dict(user=user) response = self._perform_request( url='/um/users', method='POST', data=json.dumps(data)) return response
def function[create_user, parameter[self, user]]: constant[ Creates a new user. :param user: The user object to be created. :type user: ``dict`` ] variable[data] assign[=] call[name[self]._create_user_dict, parameter[]] variable[response] assign[=] call[name[self]._perform_request, parameter[]] return[name[response]]
keyword[def] identifier[create_user] ( identifier[self] , identifier[user] ): literal[string] identifier[data] = identifier[self] . identifier[_create_user_dict] ( identifier[user] = identifier[user] ) identifier[response] = identifier[self] . identifier[_perform_request] ( identifier[url] = literal[string] , identifier[method] = literal[string] , identifier[data] = identifier[json] . identifier[dumps] ( identifier[data] )) keyword[return] identifier[response]
def create_user(self, user): """ Creates a new user. :param user: The user object to be created. :type user: ``dict`` """ data = self._create_user_dict(user=user) response = self._perform_request(url='/um/users', method='POST', data=json.dumps(data)) return response
def get_clone(rec): """ >>> get_clone("Medicago truncatula chromosome 2 clone mth2-48e18") ('2', 'mth2-48e18') """ s = rec.description chr = re.search(chr_pat, s) clone = re.search(clone_pat, s) chr = chr.group(1) if chr else "" clone = clone.group(1) if clone else "" return chr, clone
def function[get_clone, parameter[rec]]: constant[ >>> get_clone("Medicago truncatula chromosome 2 clone mth2-48e18") ('2', 'mth2-48e18') ] variable[s] assign[=] name[rec].description variable[chr] assign[=] call[name[re].search, parameter[name[chr_pat], name[s]]] variable[clone] assign[=] call[name[re].search, parameter[name[clone_pat], name[s]]] variable[chr] assign[=] <ast.IfExp object at 0x7da1b09bc1c0> variable[clone] assign[=] <ast.IfExp object at 0x7da1b09bd210> return[tuple[[<ast.Name object at 0x7da1b09bc3d0>, <ast.Name object at 0x7da1b09beda0>]]]
keyword[def] identifier[get_clone] ( identifier[rec] ): literal[string] identifier[s] = identifier[rec] . identifier[description] identifier[chr] = identifier[re] . identifier[search] ( identifier[chr_pat] , identifier[s] ) identifier[clone] = identifier[re] . identifier[search] ( identifier[clone_pat] , identifier[s] ) identifier[chr] = identifier[chr] . identifier[group] ( literal[int] ) keyword[if] identifier[chr] keyword[else] literal[string] identifier[clone] = identifier[clone] . identifier[group] ( literal[int] ) keyword[if] identifier[clone] keyword[else] literal[string] keyword[return] identifier[chr] , identifier[clone]
def get_clone(rec): """ >>> get_clone("Medicago truncatula chromosome 2 clone mth2-48e18") ('2', 'mth2-48e18') """ s = rec.description chr = re.search(chr_pat, s) clone = re.search(clone_pat, s) chr = chr.group(1) if chr else '' clone = clone.group(1) if clone else '' return (chr, clone)
def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning("{} {}: {}".format( error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format( cls, record[ID])) elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') else: raise ValueError('Bad record ({})'.format( psycopg2.errorcodes.lookup(error.pgcode)))
def function[create, parameter[self, cls, record, user]]: constant[Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) ] call[name[self].validate_record, parameter[name[cls], name[record]]] call[name[record]][name[CREATION_DATE]] assign[=] call[name[self].nowstr, parameter[]] call[name[record]][name[CREATOR]] assign[=] name[user] <ast.Try object at 0x7da20cabf580>
keyword[def] identifier[create] ( identifier[self] , identifier[cls] , identifier[record] , identifier[user] = literal[string] ): literal[string] identifier[self] . identifier[validate_record] ( identifier[cls] , identifier[record] ) identifier[record] [ identifier[CREATION_DATE] ]= identifier[record] [ identifier[UPDATE_DATE] ]= identifier[self] . identifier[nowstr] () identifier[record] [ identifier[CREATOR] ]= identifier[record] [ identifier[UPDATER] ]= identifier[user] keyword[try] : keyword[return] identifier[self] . identifier[db] . identifier[insert] ( identifier[cls] , identifier[record] ) keyword[except] ( identifier[psycopg2] . identifier[IntegrityError] , identifier[psycopg2] . identifier[ProgrammingError] , identifier[psycopg2] . identifier[DataError] ) keyword[as] identifier[error] : identifier[logging] . identifier[warning] ( literal[string] . identifier[format] ( identifier[error] . identifier[__class__] . identifier[__name__] , identifier[psycopg2] . identifier[errorcodes] . identifier[lookup] ( identifier[error] . identifier[pgcode] ), identifier[error] . identifier[pgerror] )) keyword[if] identifier[error] . identifier[pgcode] == identifier[psycopg2] . identifier[errorcodes] . identifier[UNIQUE_VIOLATION] : keyword[raise] identifier[KeyError] ( literal[string] . identifier[format] ( identifier[cls] , identifier[record] [ identifier[ID] ])) keyword[elif] identifier[error] . identifier[pgcode] == identifier[psycopg2] . identifier[errorcodes] . identifier[UNDEFINED_COLUMN] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[psycopg2] . identifier[errorcodes] . identifier[lookup] ( identifier[error] . identifier[pgcode] )))
def create(self, cls, record, user='undefined'): """Persist new record >>> s = teststore() >>> s.create('tstoretest', {'id': '1', 'name': 'Toto'}) >>> s.create('tstoretest', {'id': '2', 'name': 'Tata'}, user='jane') >>> r = s.get('tstoretest', '2') >>> r[CREATOR] 'jane' >>> s.create('badcls', {'id': '1', 'name': 'Toto'}) Traceback (most recent call last): ... ValueError: Unsupported record type "badcls" >>> s.create('tstoretest', {'id': '1', 'name': 'Joe'}) Traceback (most recent call last): ... KeyError: 'There is already a record for tstoretest/1' >>> s.create('tstoretest', {'id': '2', 'badfield': 'Joe'}) Traceback (most recent call last): ... ValueError: Undefined field >>> s.create('tstoretest', {'id': '2', 'age': 'bad'}) Traceback (most recent call last): ... ValueError: Bad record (INVALID_TEXT_REPRESENTATION) """ self.validate_record(cls, record) record[CREATION_DATE] = record[UPDATE_DATE] = self.nowstr() record[CREATOR] = record[UPDATER] = user try: return self.db.insert(cls, record) # depends on [control=['try'], data=[]] except (psycopg2.IntegrityError, psycopg2.ProgrammingError, psycopg2.DataError) as error: logging.warning('{} {}: {}'.format(error.__class__.__name__, psycopg2.errorcodes.lookup(error.pgcode), error.pgerror)) if error.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise KeyError('There is already a record for {}/{}'.format(cls, record[ID])) # depends on [control=['if'], data=[]] elif error.pgcode == psycopg2.errorcodes.UNDEFINED_COLUMN: raise ValueError('Undefined field') # depends on [control=['if'], data=[]] else: raise ValueError('Bad record ({})'.format(psycopg2.errorcodes.lookup(error.pgcode))) # depends on [control=['except'], data=['error']]
def process_hit_event(self, frame): """Return (stop_state, delete_temporary) at a breakpoint hit event.""" if not self.enabled: return False, False # Count every hit when breakpoint is enabled. self.hits += 1 # A conditional breakpoint. if self.cond: try: if not eval_(self.cond, frame.f_globals, frame.f_locals): return False, False except Exception: # If the breakpoint condition evaluation fails, the most # conservative thing is to stop on the breakpoint. Don't # delete temporary, as another hint to the user. return True, False if self.ignore > 0: self.ignore -= 1 return False, False return True, True
def function[process_hit_event, parameter[self, frame]]: constant[Return (stop_state, delete_temporary) at a breakpoint hit event.] if <ast.UnaryOp object at 0x7da1b0e728f0> begin[:] return[tuple[[<ast.Constant object at 0x7da1b0e70b50>, <ast.Constant object at 0x7da1b0e73460>]]] <ast.AugAssign object at 0x7da1b0e73670> if name[self].cond begin[:] <ast.Try object at 0x7da1b0e73eb0> if compare[name[self].ignore greater[>] constant[0]] begin[:] <ast.AugAssign object at 0x7da1b0ea0d60> return[tuple[[<ast.Constant object at 0x7da1b0ea1c90>, <ast.Constant object at 0x7da1b0ea1570>]]] return[tuple[[<ast.Constant object at 0x7da1b0ea00a0>, <ast.Constant object at 0x7da1b0ea0910>]]]
keyword[def] identifier[process_hit_event] ( identifier[self] , identifier[frame] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[enabled] : keyword[return] keyword[False] , keyword[False] identifier[self] . identifier[hits] += literal[int] keyword[if] identifier[self] . identifier[cond] : keyword[try] : keyword[if] keyword[not] identifier[eval_] ( identifier[self] . identifier[cond] , identifier[frame] . identifier[f_globals] , identifier[frame] . identifier[f_locals] ): keyword[return] keyword[False] , keyword[False] keyword[except] identifier[Exception] : keyword[return] keyword[True] , keyword[False] keyword[if] identifier[self] . identifier[ignore] > literal[int] : identifier[self] . identifier[ignore] -= literal[int] keyword[return] keyword[False] , keyword[False] keyword[return] keyword[True] , keyword[True]
def process_hit_event(self, frame): """Return (stop_state, delete_temporary) at a breakpoint hit event.""" if not self.enabled: return (False, False) # depends on [control=['if'], data=[]] # Count every hit when breakpoint is enabled. self.hits += 1 # A conditional breakpoint. if self.cond: try: if not eval_(self.cond, frame.f_globals, frame.f_locals): return (False, False) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except Exception: # If the breakpoint condition evaluation fails, the most # conservative thing is to stop on the breakpoint. Don't # delete temporary, as another hint to the user. return (True, False) # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] if self.ignore > 0: self.ignore -= 1 return (False, False) # depends on [control=['if'], data=[]] return (True, True)
def delete_repository_config(namespace, name, snapshot_id): """Redacts a configuration and all of its associated configurations. The configuration should exist in the methods repository. Args: namespace (str): configuration namespace configuration (str): configuration name snapshot_id (int): snapshot_id of the configuration Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_configurations_namespace_name_snapshotId """ uri = "configurations/{0}/{1}/{2}".format(namespace, name, snapshot_id) return __delete(uri)
def function[delete_repository_config, parameter[namespace, name, snapshot_id]]: constant[Redacts a configuration and all of its associated configurations. The configuration should exist in the methods repository. Args: namespace (str): configuration namespace configuration (str): configuration name snapshot_id (int): snapshot_id of the configuration Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_configurations_namespace_name_snapshotId ] variable[uri] assign[=] call[constant[configurations/{0}/{1}/{2}].format, parameter[name[namespace], name[name], name[snapshot_id]]] return[call[name[__delete], parameter[name[uri]]]]
keyword[def] identifier[delete_repository_config] ( identifier[namespace] , identifier[name] , identifier[snapshot_id] ): literal[string] identifier[uri] = literal[string] . identifier[format] ( identifier[namespace] , identifier[name] , identifier[snapshot_id] ) keyword[return] identifier[__delete] ( identifier[uri] )
def delete_repository_config(namespace, name, snapshot_id): """Redacts a configuration and all of its associated configurations. The configuration should exist in the methods repository. Args: namespace (str): configuration namespace configuration (str): configuration name snapshot_id (int): snapshot_id of the configuration Swagger: https://api.firecloud.org/#!/Method_Repository/delete_api_configurations_namespace_name_snapshotId """ uri = 'configurations/{0}/{1}/{2}'.format(namespace, name, snapshot_id) return __delete(uri)
def add_subreddit(self, subreddit, _delete=False, *args, **kwargs): """Add a subreddit to the multireddit. :param subreddit: The subreddit name or Subreddit object to add The additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request_json`. """ subreddit = six.text_type(subreddit) url = self.reddit_session.config['multireddit_add'].format( user=self._author, multi=self.name, subreddit=subreddit) method = 'DELETE' if _delete else 'PUT' # The modhash isn't necessary for OAuth requests if not self.reddit_session._use_oauth: self.reddit_session.http.headers['x-modhash'] = \ self.reddit_session.modhash data = {'model': dumps({'name': subreddit})} try: self.reddit_session.request(url, data=data, method=method, *args, **kwargs) finally: # The modhash isn't necessary for OAuth requests if not self.reddit_session._use_oauth: del self.reddit_session.http.headers['x-modhash']
def function[add_subreddit, parameter[self, subreddit, _delete]]: constant[Add a subreddit to the multireddit. :param subreddit: The subreddit name or Subreddit object to add The additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request_json`. ] variable[subreddit] assign[=] call[name[six].text_type, parameter[name[subreddit]]] variable[url] assign[=] call[call[name[self].reddit_session.config][constant[multireddit_add]].format, parameter[]] variable[method] assign[=] <ast.IfExp object at 0x7da204962ef0> if <ast.UnaryOp object at 0x7da2049609a0> begin[:] call[name[self].reddit_session.http.headers][constant[x-modhash]] assign[=] name[self].reddit_session.modhash variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da204963190>], [<ast.Call object at 0x7da204962b30>]] <ast.Try object at 0x7da204962e00>
keyword[def] identifier[add_subreddit] ( identifier[self] , identifier[subreddit] , identifier[_delete] = keyword[False] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[subreddit] = identifier[six] . identifier[text_type] ( identifier[subreddit] ) identifier[url] = identifier[self] . identifier[reddit_session] . identifier[config] [ literal[string] ]. identifier[format] ( identifier[user] = identifier[self] . identifier[_author] , identifier[multi] = identifier[self] . identifier[name] , identifier[subreddit] = identifier[subreddit] ) identifier[method] = literal[string] keyword[if] identifier[_delete] keyword[else] literal[string] keyword[if] keyword[not] identifier[self] . identifier[reddit_session] . identifier[_use_oauth] : identifier[self] . identifier[reddit_session] . identifier[http] . identifier[headers] [ literal[string] ]= identifier[self] . identifier[reddit_session] . identifier[modhash] identifier[data] ={ literal[string] : identifier[dumps] ({ literal[string] : identifier[subreddit] })} keyword[try] : identifier[self] . identifier[reddit_session] . identifier[request] ( identifier[url] , identifier[data] = identifier[data] , identifier[method] = identifier[method] , * identifier[args] ,** identifier[kwargs] ) keyword[finally] : keyword[if] keyword[not] identifier[self] . identifier[reddit_session] . identifier[_use_oauth] : keyword[del] identifier[self] . identifier[reddit_session] . identifier[http] . identifier[headers] [ literal[string] ]
def add_subreddit(self, subreddit, _delete=False, *args, **kwargs): """Add a subreddit to the multireddit. :param subreddit: The subreddit name or Subreddit object to add The additional parameters are passed directly into :meth:`~praw.__init__.BaseReddit.request_json`. """ subreddit = six.text_type(subreddit) url = self.reddit_session.config['multireddit_add'].format(user=self._author, multi=self.name, subreddit=subreddit) method = 'DELETE' if _delete else 'PUT' # The modhash isn't necessary for OAuth requests if not self.reddit_session._use_oauth: self.reddit_session.http.headers['x-modhash'] = self.reddit_session.modhash # depends on [control=['if'], data=[]] data = {'model': dumps({'name': subreddit})} try: self.reddit_session.request(url, *args, data=data, method=method, **kwargs) # depends on [control=['try'], data=[]] finally: # The modhash isn't necessary for OAuth requests if not self.reddit_session._use_oauth: del self.reddit_session.http.headers['x-modhash'] # depends on [control=['if'], data=[]]
def _rcconf_status(name, service_status): ''' Modifies /etc/rc.conf so a service is started or not at boot time and can be started via /etc/rc.d/<service> ''' rcconf = '/etc/rc.conf' rxname = '^{0}=.*'.format(name) newstatus = '{0}={1}'.format(name, service_status) ret = __salt__['cmd.retcode']('grep \'{0}\' {1}'.format(rxname, rcconf)) if ret == 0: # service found in rc.conf, modify its status __salt__['file.replace'](rcconf, rxname, newstatus) else: ret = __salt__['file.append'](rcconf, newstatus) return ret
def function[_rcconf_status, parameter[name, service_status]]: constant[ Modifies /etc/rc.conf so a service is started or not at boot time and can be started via /etc/rc.d/<service> ] variable[rcconf] assign[=] constant[/etc/rc.conf] variable[rxname] assign[=] call[constant[^{0}=.*].format, parameter[name[name]]] variable[newstatus] assign[=] call[constant[{0}={1}].format, parameter[name[name], name[service_status]]] variable[ret] assign[=] call[call[name[__salt__]][constant[cmd.retcode]], parameter[call[constant[grep '{0}' {1}].format, parameter[name[rxname], name[rcconf]]]]] if compare[name[ret] equal[==] constant[0]] begin[:] call[call[name[__salt__]][constant[file.replace]], parameter[name[rcconf], name[rxname], name[newstatus]]] return[name[ret]]
keyword[def] identifier[_rcconf_status] ( identifier[name] , identifier[service_status] ): literal[string] identifier[rcconf] = literal[string] identifier[rxname] = literal[string] . identifier[format] ( identifier[name] ) identifier[newstatus] = literal[string] . identifier[format] ( identifier[name] , identifier[service_status] ) identifier[ret] = identifier[__salt__] [ literal[string] ]( literal[string] . identifier[format] ( identifier[rxname] , identifier[rcconf] )) keyword[if] identifier[ret] == literal[int] : identifier[__salt__] [ literal[string] ]( identifier[rcconf] , identifier[rxname] , identifier[newstatus] ) keyword[else] : identifier[ret] = identifier[__salt__] [ literal[string] ]( identifier[rcconf] , identifier[newstatus] ) keyword[return] identifier[ret]
def _rcconf_status(name, service_status): """ Modifies /etc/rc.conf so a service is started or not at boot time and can be started via /etc/rc.d/<service> """ rcconf = '/etc/rc.conf' rxname = '^{0}=.*'.format(name) newstatus = '{0}={1}'.format(name, service_status) ret = __salt__['cmd.retcode']("grep '{0}' {1}".format(rxname, rcconf)) if ret == 0: # service found in rc.conf, modify its status __salt__['file.replace'](rcconf, rxname, newstatus) # depends on [control=['if'], data=[]] else: ret = __salt__['file.append'](rcconf, newstatus) return ret
def read_parfile(parfile): """load a pest-compatible .par file into a pandas.DataFrame Parameters ---------- parfile : str pest parameter file name Returns ------- pandas.DataFrame : pandas.DataFrame """ assert os.path.exists(parfile), "Pst.parrep(): parfile not found: " +\ str(parfile) f = open(parfile, 'r') header = f.readline() par_df = pd.read_csv(f, header=None, names=["parnme", "parval1", "scale", "offset"], sep="\s+") par_df.index = par_df.parnme return par_df
def function[read_parfile, parameter[parfile]]: constant[load a pest-compatible .par file into a pandas.DataFrame Parameters ---------- parfile : str pest parameter file name Returns ------- pandas.DataFrame : pandas.DataFrame ] assert[call[name[os].path.exists, parameter[name[parfile]]]] variable[f] assign[=] call[name[open], parameter[name[parfile], constant[r]]] variable[header] assign[=] call[name[f].readline, parameter[]] variable[par_df] assign[=] call[name[pd].read_csv, parameter[name[f]]] name[par_df].index assign[=] name[par_df].parnme return[name[par_df]]
keyword[def] identifier[read_parfile] ( identifier[parfile] ): literal[string] keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[parfile] ), literal[string] + identifier[str] ( identifier[parfile] ) identifier[f] = identifier[open] ( identifier[parfile] , literal[string] ) identifier[header] = identifier[f] . identifier[readline] () identifier[par_df] = identifier[pd] . identifier[read_csv] ( identifier[f] , identifier[header] = keyword[None] , identifier[names] =[ literal[string] , literal[string] , literal[string] , literal[string] ], identifier[sep] = literal[string] ) identifier[par_df] . identifier[index] = identifier[par_df] . identifier[parnme] keyword[return] identifier[par_df]
def read_parfile(parfile): """load a pest-compatible .par file into a pandas.DataFrame Parameters ---------- parfile : str pest parameter file name Returns ------- pandas.DataFrame : pandas.DataFrame """ assert os.path.exists(parfile), 'Pst.parrep(): parfile not found: ' + str(parfile) f = open(parfile, 'r') header = f.readline() par_df = pd.read_csv(f, header=None, names=['parnme', 'parval1', 'scale', 'offset'], sep='\\s+') par_df.index = par_df.parnme return par_df
def update_data(): """ Update data sent by background process to global allData """ global allData while not q.empty(): allData = q.get() for key, value in tags.items(): if key in allData: allData[key]['name'] = value
def function[update_data, parameter[]]: constant[ Update data sent by background process to global allData ] <ast.Global object at 0x7da20c6aa830> while <ast.UnaryOp object at 0x7da20c6aad70> begin[:] variable[allData] assign[=] call[name[q].get, parameter[]] for taget[tuple[[<ast.Name object at 0x7da20c6aa7a0>, <ast.Name object at 0x7da20c6ab6a0>]]] in starred[call[name[tags].items, parameter[]]] begin[:] if compare[name[key] in name[allData]] begin[:] call[call[name[allData]][name[key]]][constant[name]] assign[=] name[value]
keyword[def] identifier[update_data] (): literal[string] keyword[global] identifier[allData] keyword[while] keyword[not] identifier[q] . identifier[empty] (): identifier[allData] = identifier[q] . identifier[get] () keyword[for] identifier[key] , identifier[value] keyword[in] identifier[tags] . identifier[items] (): keyword[if] identifier[key] keyword[in] identifier[allData] : identifier[allData] [ identifier[key] ][ literal[string] ]= identifier[value]
def update_data(): """ Update data sent by background process to global allData """ global allData while not q.empty(): allData = q.get() # depends on [control=['while'], data=[]] for (key, value) in tags.items(): if key in allData: allData[key]['name'] = value # depends on [control=['if'], data=['key', 'allData']] # depends on [control=['for'], data=[]]
def to_mixed_case(s): """ convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase """ out = '' last_c = '' for c in s: if c == '_': pass elif last_c in ('', '_'): out += c.upper() else: out += c.lower() last_c = c return out
def function[to_mixed_case, parameter[s]]: constant[ convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase ] variable[out] assign[=] constant[] variable[last_c] assign[=] constant[] for taget[name[c]] in starred[name[s]] begin[:] if compare[name[c] equal[==] constant[_]] begin[:] pass variable[last_c] assign[=] name[c] return[name[out]]
keyword[def] identifier[to_mixed_case] ( identifier[s] ): literal[string] identifier[out] = literal[string] identifier[last_c] = literal[string] keyword[for] identifier[c] keyword[in] identifier[s] : keyword[if] identifier[c] == literal[string] : keyword[pass] keyword[elif] identifier[last_c] keyword[in] ( literal[string] , literal[string] ): identifier[out] += identifier[c] . identifier[upper] () keyword[else] : identifier[out] += identifier[c] . identifier[lower] () identifier[last_c] = identifier[c] keyword[return] identifier[out]
def to_mixed_case(s): """ convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase """ out = '' last_c = '' for c in s: if c == '_': pass # depends on [control=['if'], data=[]] elif last_c in ('', '_'): out += c.upper() # depends on [control=['if'], data=[]] else: out += c.lower() last_c = c # depends on [control=['for'], data=['c']] return out
def is_pdf(document): """Check if a document is a PDF file and return True if is is.""" if not executable_exists('pdftotext'): current_app.logger.warning( "GNU file was not found on the system. " "Switching to a weak file extension test." ) if document.lower().endswith(".pdf"): return True return False # Tested with file version >= 4.10. First test is secure and works # with file version 4.25. Second condition is tested for file # version 4.10. file_output = os.popen('file ' + re.escape(document)).read() try: filetype = file_output.split(":")[-1] except IndexError: current_app.logger.error( "Your version of the 'file' utility seems to be unsupported." ) raise IncompatiblePDF2Text('Incompatible pdftotext') pdf = filetype.find("PDF") > -1 # This is how it should be done however this is incompatible with # file version 4.10. # os.popen('file -bi ' + document).read().find("application/pdf") return pdf
def function[is_pdf, parameter[document]]: constant[Check if a document is a PDF file and return True if is is.] if <ast.UnaryOp object at 0x7da20c7ca350> begin[:] call[name[current_app].logger.warning, parameter[constant[GNU file was not found on the system. Switching to a weak file extension test.]]] if call[call[name[document].lower, parameter[]].endswith, parameter[constant[.pdf]]] begin[:] return[constant[True]] return[constant[False]] variable[file_output] assign[=] call[call[name[os].popen, parameter[binary_operation[constant[file ] + call[name[re].escape, parameter[name[document]]]]]].read, parameter[]] <ast.Try object at 0x7da20c7c9e40> variable[pdf] assign[=] compare[call[name[filetype].find, parameter[constant[PDF]]] greater[>] <ast.UnaryOp object at 0x7da204564100>] return[name[pdf]]
keyword[def] identifier[is_pdf] ( identifier[document] ): literal[string] keyword[if] keyword[not] identifier[executable_exists] ( literal[string] ): identifier[current_app] . identifier[logger] . identifier[warning] ( literal[string] literal[string] ) keyword[if] identifier[document] . identifier[lower] (). identifier[endswith] ( literal[string] ): keyword[return] keyword[True] keyword[return] keyword[False] identifier[file_output] = identifier[os] . identifier[popen] ( literal[string] + identifier[re] . identifier[escape] ( identifier[document] )). identifier[read] () keyword[try] : identifier[filetype] = identifier[file_output] . identifier[split] ( literal[string] )[- literal[int] ] keyword[except] identifier[IndexError] : identifier[current_app] . identifier[logger] . identifier[error] ( literal[string] ) keyword[raise] identifier[IncompatiblePDF2Text] ( literal[string] ) identifier[pdf] = identifier[filetype] . identifier[find] ( literal[string] )>- literal[int] keyword[return] identifier[pdf]
def is_pdf(document): """Check if a document is a PDF file and return True if is is.""" if not executable_exists('pdftotext'): current_app.logger.warning('GNU file was not found on the system. Switching to a weak file extension test.') if document.lower().endswith('.pdf'): return True # depends on [control=['if'], data=[]] return False # depends on [control=['if'], data=[]] # Tested with file version >= 4.10. First test is secure and works # with file version 4.25. Second condition is tested for file # version 4.10. file_output = os.popen('file ' + re.escape(document)).read() try: filetype = file_output.split(':')[-1] # depends on [control=['try'], data=[]] except IndexError: current_app.logger.error("Your version of the 'file' utility seems to be unsupported.") raise IncompatiblePDF2Text('Incompatible pdftotext') # depends on [control=['except'], data=[]] pdf = filetype.find('PDF') > -1 # This is how it should be done however this is incompatible with # file version 4.10. # os.popen('file -bi ' + document).read().find("application/pdf") return pdf
def does_match_exist(self, inst): """ Returns True if inst does match one of specified criteria. :param inst: declaration instance :type inst: :class:`declaration_t` :rtype: bool """ answer = True if self._decl_type is not None: answer &= isinstance(inst, self._decl_type) if self.name is not None: answer &= inst.name == self.name if self.parent is not None: answer &= self.parent is inst.parent if self.fullname is not None: if inst.name: answer &= self.fullname == declaration_utils.full_name(inst) else: answer = False return answer
def function[does_match_exist, parameter[self, inst]]: constant[ Returns True if inst does match one of specified criteria. :param inst: declaration instance :type inst: :class:`declaration_t` :rtype: bool ] variable[answer] assign[=] constant[True] if compare[name[self]._decl_type is_not constant[None]] begin[:] <ast.AugAssign object at 0x7da18dc989d0> if compare[name[self].name is_not constant[None]] begin[:] <ast.AugAssign object at 0x7da18dc9a800> if compare[name[self].parent is_not constant[None]] begin[:] <ast.AugAssign object at 0x7da18dc9a230> if compare[name[self].fullname is_not constant[None]] begin[:] if name[inst].name begin[:] <ast.AugAssign object at 0x7da18dc99570> return[name[answer]]
keyword[def] identifier[does_match_exist] ( identifier[self] , identifier[inst] ): literal[string] identifier[answer] = keyword[True] keyword[if] identifier[self] . identifier[_decl_type] keyword[is] keyword[not] keyword[None] : identifier[answer] &= identifier[isinstance] ( identifier[inst] , identifier[self] . identifier[_decl_type] ) keyword[if] identifier[self] . identifier[name] keyword[is] keyword[not] keyword[None] : identifier[answer] &= identifier[inst] . identifier[name] == identifier[self] . identifier[name] keyword[if] identifier[self] . identifier[parent] keyword[is] keyword[not] keyword[None] : identifier[answer] &= identifier[self] . identifier[parent] keyword[is] identifier[inst] . identifier[parent] keyword[if] identifier[self] . identifier[fullname] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[inst] . identifier[name] : identifier[answer] &= identifier[self] . identifier[fullname] == identifier[declaration_utils] . identifier[full_name] ( identifier[inst] ) keyword[else] : identifier[answer] = keyword[False] keyword[return] identifier[answer]
def does_match_exist(self, inst): """ Returns True if inst does match one of specified criteria. :param inst: declaration instance :type inst: :class:`declaration_t` :rtype: bool """ answer = True if self._decl_type is not None: answer &= isinstance(inst, self._decl_type) # depends on [control=['if'], data=[]] if self.name is not None: answer &= inst.name == self.name # depends on [control=['if'], data=[]] if self.parent is not None: answer &= self.parent is inst.parent # depends on [control=['if'], data=[]] if self.fullname is not None: if inst.name: answer &= self.fullname == declaration_utils.full_name(inst) # depends on [control=['if'], data=[]] else: answer = False # depends on [control=['if'], data=[]] return answer
def getAllAnnotationSets(self): """ Returns all variant annotation sets on the server. """ for variantSet in self.getAllVariantSets(): iterator = self._client.search_variant_annotation_sets( variant_set_id=variantSet.id) for variantAnnotationSet in iterator: yield variantAnnotationSet
def function[getAllAnnotationSets, parameter[self]]: constant[ Returns all variant annotation sets on the server. ] for taget[name[variantSet]] in starred[call[name[self].getAllVariantSets, parameter[]]] begin[:] variable[iterator] assign[=] call[name[self]._client.search_variant_annotation_sets, parameter[]] for taget[name[variantAnnotationSet]] in starred[name[iterator]] begin[:] <ast.Yield object at 0x7da20c6e5840>
keyword[def] identifier[getAllAnnotationSets] ( identifier[self] ): literal[string] keyword[for] identifier[variantSet] keyword[in] identifier[self] . identifier[getAllVariantSets] (): identifier[iterator] = identifier[self] . identifier[_client] . identifier[search_variant_annotation_sets] ( identifier[variant_set_id] = identifier[variantSet] . identifier[id] ) keyword[for] identifier[variantAnnotationSet] keyword[in] identifier[iterator] : keyword[yield] identifier[variantAnnotationSet]
def getAllAnnotationSets(self): """ Returns all variant annotation sets on the server. """ for variantSet in self.getAllVariantSets(): iterator = self._client.search_variant_annotation_sets(variant_set_id=variantSet.id) for variantAnnotationSet in iterator: yield variantAnnotationSet # depends on [control=['for'], data=['variantAnnotationSet']] # depends on [control=['for'], data=['variantSet']]
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None): """ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername) :param user_id: Int : Unique identifier of the target user :param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages :return: types.Message """ return apihelper.restrict_chat_member(self.token, chat_id, user_id, until_date, can_send_messages, can_send_media_messages, can_send_other_messages, can_add_web_page_previews)
def function[restrict_chat_member, parameter[self, chat_id, user_id, until_date, can_send_messages, can_send_media_messages, can_send_other_messages, can_add_web_page_previews]]: constant[ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername) :param user_id: Int : Unique identifier of the target user :param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages :return: types.Message ] return[call[name[apihelper].restrict_chat_member, parameter[name[self].token, name[chat_id], name[user_id], name[until_date], name[can_send_messages], name[can_send_media_messages], name[can_send_other_messages], name[can_add_web_page_previews]]]]
keyword[def] identifier[restrict_chat_member] ( identifier[self] , identifier[chat_id] , identifier[user_id] , identifier[until_date] = keyword[None] , identifier[can_send_messages] = keyword[None] , identifier[can_send_media_messages] = keyword[None] , identifier[can_send_other_messages] = keyword[None] , identifier[can_add_web_page_previews] = keyword[None] ): literal[string] keyword[return] identifier[apihelper] . identifier[restrict_chat_member] ( identifier[self] . identifier[token] , identifier[chat_id] , identifier[user_id] , identifier[until_date] , identifier[can_send_messages] , identifier[can_send_media_messages] , identifier[can_send_other_messages] , identifier[can_add_web_page_previews] )
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None): """ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. :param chat_id: Int or String : Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername) :param user_id: Int : Unique identifier of the target user :param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues :param can_send_media_messages Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages :param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages :param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages :return: types.Message """ return apihelper.restrict_chat_member(self.token, chat_id, user_id, until_date, can_send_messages, can_send_media_messages, can_send_other_messages, can_add_web_page_previews)
def create_instances(configuration): """Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict """ instances = {} for methods in configuration.itervalues(): for element in methods.itervalues(): if not isinstance(element, tuple): continue cls, _ = element if cls not in instances: instances[cls] = cls() return instances
def function[create_instances, parameter[configuration]]: constant[Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict ] variable[instances] assign[=] dictionary[[], []] for taget[name[methods]] in starred[call[name[configuration].itervalues, parameter[]]] begin[:] for taget[name[element]] in starred[call[name[methods].itervalues, parameter[]]] begin[:] if <ast.UnaryOp object at 0x7da18f813550> begin[:] continue <ast.Tuple object at 0x7da18f811030> assign[=] name[element] if compare[name[cls] <ast.NotIn object at 0x7da2590d7190> name[instances]] begin[:] call[name[instances]][name[cls]] assign[=] call[name[cls], parameter[]] return[name[instances]]
keyword[def] identifier[create_instances] ( identifier[configuration] ): literal[string] identifier[instances] ={} keyword[for] identifier[methods] keyword[in] identifier[configuration] . identifier[itervalues] (): keyword[for] identifier[element] keyword[in] identifier[methods] . identifier[itervalues] (): keyword[if] keyword[not] identifier[isinstance] ( identifier[element] , identifier[tuple] ): keyword[continue] identifier[cls] , identifier[_] = identifier[element] keyword[if] identifier[cls] keyword[not] keyword[in] identifier[instances] : identifier[instances] [ identifier[cls] ]= identifier[cls] () keyword[return] identifier[instances]
def create_instances(configuration): """Create necessary class instances from a configuration with no argument to the constructor :param dict configuration: configuration dict like in :attr:`~pyextdirect.configuration.Base.configuration` :return: a class-instance mapping :rtype: dict """ instances = {} for methods in configuration.itervalues(): for element in methods.itervalues(): if not isinstance(element, tuple): continue # depends on [control=['if'], data=[]] (cls, _) = element if cls not in instances: instances[cls] = cls() # depends on [control=['if'], data=['cls', 'instances']] # depends on [control=['for'], data=['element']] # depends on [control=['for'], data=['methods']] return instances
def p_typed_var_list(self, p): '''typed_var_list : typed_var_list COMMA typed_var | typed_var''' if len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
def function[p_typed_var_list, parameter[self, p]]: constant[typed_var_list : typed_var_list COMMA typed_var | typed_var] if compare[call[name[len], parameter[name[p]]] equal[==] constant[4]] begin[:] call[call[name[p]][constant[1]].append, parameter[call[name[p]][constant[3]]]] call[name[p]][constant[0]] assign[=] call[name[p]][constant[1]]
keyword[def] identifier[p_typed_var_list] ( identifier[self] , identifier[p] ): literal[string] keyword[if] identifier[len] ( identifier[p] )== literal[int] : identifier[p] [ literal[int] ]. identifier[append] ( identifier[p] [ literal[int] ]) identifier[p] [ literal[int] ]= identifier[p] [ literal[int] ] keyword[elif] identifier[len] ( identifier[p] )== literal[int] : identifier[p] [ literal[int] ]=[ identifier[p] [ literal[int] ]]
def p_typed_var_list(self, p): """typed_var_list : typed_var_list COMMA typed_var | typed_var""" if len(p) == 4: p[1].append(p[3]) p[0] = p[1] # depends on [control=['if'], data=[]] elif len(p) == 2: p[0] = [p[1]] # depends on [control=['if'], data=[]]
def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath): ''' Plots the original data in a graph above the plot of the dtw'ed data ''' _matplotlibCheck() plt.hold(True) fig, (ax0) = plt.subplots(nrows=1) # Old data plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red', linewidth=2, label="From") plot2 = ax0.plot(toTuple[0], toTuple[1], color='blue', linewidth=2, label="To") ax0.set_title("Plot of F0 Morph") plt.ylabel('Pitch (hz)') plt.xlabel('Time (s)') # Merge data colorValue = 0 colorStep = 255.0 / len(mergeTupleList) for timeList, valueList in mergeTupleList: colorValue += colorStep hexValue = "#%02x0000" % int(255 - colorValue) if int(colorValue) == 255: ax0.plot(timeList, valueList, color=hexValue, linewidth=1, label="Merged line, final iteration") else: ax0.plot(timeList, valueList, color=hexValue, linewidth=1) plt.legend(loc=1, borderaxespad=0.) # plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"]) plt.savefig(fnFullPath, dpi=300, bbox_inches='tight') plt.close(fig)
def function[plotF0, parameter[fromTuple, toTuple, mergeTupleList, fnFullPath]]: constant[ Plots the original data in a graph above the plot of the dtw'ed data ] call[name[_matplotlibCheck], parameter[]] call[name[plt].hold, parameter[constant[True]]] <ast.Tuple object at 0x7da1b101fa30> assign[=] call[name[plt].subplots, parameter[]] variable[plot1] assign[=] call[name[ax0].plot, parameter[call[name[fromTuple]][constant[0]], call[name[fromTuple]][constant[1]]]] variable[plot2] assign[=] call[name[ax0].plot, parameter[call[name[toTuple]][constant[0]], call[name[toTuple]][constant[1]]]] call[name[ax0].set_title, parameter[constant[Plot of F0 Morph]]] call[name[plt].ylabel, parameter[constant[Pitch (hz)]]] call[name[plt].xlabel, parameter[constant[Time (s)]]] variable[colorValue] assign[=] constant[0] variable[colorStep] assign[=] binary_operation[constant[255.0] / call[name[len], parameter[name[mergeTupleList]]]] for taget[tuple[[<ast.Name object at 0x7da1b1116950>, <ast.Name object at 0x7da1b1114520>]]] in starred[name[mergeTupleList]] begin[:] <ast.AugAssign object at 0x7da1b1115a20> variable[hexValue] assign[=] binary_operation[constant[#%02x0000] <ast.Mod object at 0x7da2590d6920> call[name[int], parameter[binary_operation[constant[255] - name[colorValue]]]]] if compare[call[name[int], parameter[name[colorValue]]] equal[==] constant[255]] begin[:] call[name[ax0].plot, parameter[name[timeList], name[valueList]]] call[name[plt].legend, parameter[]] call[name[plt].savefig, parameter[name[fnFullPath]]] call[name[plt].close, parameter[name[fig]]]
keyword[def] identifier[plotF0] ( identifier[fromTuple] , identifier[toTuple] , identifier[mergeTupleList] , identifier[fnFullPath] ): literal[string] identifier[_matplotlibCheck] () identifier[plt] . identifier[hold] ( keyword[True] ) identifier[fig] ,( identifier[ax0] )= identifier[plt] . identifier[subplots] ( identifier[nrows] = literal[int] ) identifier[plot1] = identifier[ax0] . identifier[plot] ( identifier[fromTuple] [ literal[int] ], identifier[fromTuple] [ literal[int] ], identifier[color] = literal[string] , identifier[linewidth] = literal[int] , identifier[label] = literal[string] ) identifier[plot2] = identifier[ax0] . identifier[plot] ( identifier[toTuple] [ literal[int] ], identifier[toTuple] [ literal[int] ], identifier[color] = literal[string] , identifier[linewidth] = literal[int] , identifier[label] = literal[string] ) identifier[ax0] . identifier[set_title] ( literal[string] ) identifier[plt] . identifier[ylabel] ( literal[string] ) identifier[plt] . identifier[xlabel] ( literal[string] ) identifier[colorValue] = literal[int] identifier[colorStep] = literal[int] / identifier[len] ( identifier[mergeTupleList] ) keyword[for] identifier[timeList] , identifier[valueList] keyword[in] identifier[mergeTupleList] : identifier[colorValue] += identifier[colorStep] identifier[hexValue] = literal[string] % identifier[int] ( literal[int] - identifier[colorValue] ) keyword[if] identifier[int] ( identifier[colorValue] )== literal[int] : identifier[ax0] . identifier[plot] ( identifier[timeList] , identifier[valueList] , identifier[color] = identifier[hexValue] , identifier[linewidth] = literal[int] , identifier[label] = literal[string] ) keyword[else] : identifier[ax0] . identifier[plot] ( identifier[timeList] , identifier[valueList] , identifier[color] = identifier[hexValue] , identifier[linewidth] = literal[int] ) identifier[plt] . identifier[legend] ( identifier[loc] = literal[int] , identifier[borderaxespad] = literal[int] ) identifier[plt] . identifier[savefig] ( identifier[fnFullPath] , identifier[dpi] = literal[int] , identifier[bbox_inches] = literal[string] ) identifier[plt] . identifier[close] ( identifier[fig] )
def plotF0(fromTuple, toTuple, mergeTupleList, fnFullPath): """ Plots the original data in a graph above the plot of the dtw'ed data """ _matplotlibCheck() plt.hold(True) (fig, ax0) = plt.subplots(nrows=1) # Old data plot1 = ax0.plot(fromTuple[0], fromTuple[1], color='red', linewidth=2, label='From') plot2 = ax0.plot(toTuple[0], toTuple[1], color='blue', linewidth=2, label='To') ax0.set_title('Plot of F0 Morph') plt.ylabel('Pitch (hz)') plt.xlabel('Time (s)') # Merge data colorValue = 0 colorStep = 255.0 / len(mergeTupleList) for (timeList, valueList) in mergeTupleList: colorValue += colorStep hexValue = '#%02x0000' % int(255 - colorValue) if int(colorValue) == 255: ax0.plot(timeList, valueList, color=hexValue, linewidth=1, label='Merged line, final iteration') # depends on [control=['if'], data=[]] else: ax0.plot(timeList, valueList, color=hexValue, linewidth=1) # depends on [control=['for'], data=[]] plt.legend(loc=1, borderaxespad=0.0) # plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"]) plt.savefig(fnFullPath, dpi=300, bbox_inches='tight') plt.close(fig)
def great_circle_vec(lat1, lng1, lat2, lng2, earth_radius=6371009): """ Vectorized function to calculate the great-circle distance between two points or between vectors of points, using haversine. Parameters ---------- lat1 : float or array of float lng1 : float or array of float lat2 : float or array of float lng2 : float or array of float earth_radius : numeric radius of earth in units in which distance will be returned (default is meters) Returns ------- distance : float or vector of floats distance or vector of distances from (lat1, lng1) to (lat2, lng2) in units of earth_radius """ phi1 = np.deg2rad(lat1) phi2 = np.deg2rad(lat2) d_phi = phi2 - phi1 theta1 = np.deg2rad(lng1) theta2 = np.deg2rad(lng2) d_theta = theta2 - theta1 h = np.sin(d_phi / 2) ** 2 + np.cos(phi1) * np.cos(phi2) * np.sin(d_theta / 2) ** 2 h = np.minimum(1.0, h) # protect against floating point errors arc = 2 * np.arcsin(np.sqrt(h)) # return distance in units of earth_radius distance = arc * earth_radius return distance
def function[great_circle_vec, parameter[lat1, lng1, lat2, lng2, earth_radius]]: constant[ Vectorized function to calculate the great-circle distance between two points or between vectors of points, using haversine. Parameters ---------- lat1 : float or array of float lng1 : float or array of float lat2 : float or array of float lng2 : float or array of float earth_radius : numeric radius of earth in units in which distance will be returned (default is meters) Returns ------- distance : float or vector of floats distance or vector of distances from (lat1, lng1) to (lat2, lng2) in units of earth_radius ] variable[phi1] assign[=] call[name[np].deg2rad, parameter[name[lat1]]] variable[phi2] assign[=] call[name[np].deg2rad, parameter[name[lat2]]] variable[d_phi] assign[=] binary_operation[name[phi2] - name[phi1]] variable[theta1] assign[=] call[name[np].deg2rad, parameter[name[lng1]]] variable[theta2] assign[=] call[name[np].deg2rad, parameter[name[lng2]]] variable[d_theta] assign[=] binary_operation[name[theta2] - name[theta1]] variable[h] assign[=] binary_operation[binary_operation[call[name[np].sin, parameter[binary_operation[name[d_phi] / constant[2]]]] ** constant[2]] + binary_operation[binary_operation[call[name[np].cos, parameter[name[phi1]]] * call[name[np].cos, parameter[name[phi2]]]] * binary_operation[call[name[np].sin, parameter[binary_operation[name[d_theta] / constant[2]]]] ** constant[2]]]] variable[h] assign[=] call[name[np].minimum, parameter[constant[1.0], name[h]]] variable[arc] assign[=] binary_operation[constant[2] * call[name[np].arcsin, parameter[call[name[np].sqrt, parameter[name[h]]]]]] variable[distance] assign[=] binary_operation[name[arc] * name[earth_radius]] return[name[distance]]
keyword[def] identifier[great_circle_vec] ( identifier[lat1] , identifier[lng1] , identifier[lat2] , identifier[lng2] , identifier[earth_radius] = literal[int] ): literal[string] identifier[phi1] = identifier[np] . identifier[deg2rad] ( identifier[lat1] ) identifier[phi2] = identifier[np] . identifier[deg2rad] ( identifier[lat2] ) identifier[d_phi] = identifier[phi2] - identifier[phi1] identifier[theta1] = identifier[np] . identifier[deg2rad] ( identifier[lng1] ) identifier[theta2] = identifier[np] . identifier[deg2rad] ( identifier[lng2] ) identifier[d_theta] = identifier[theta2] - identifier[theta1] identifier[h] = identifier[np] . identifier[sin] ( identifier[d_phi] / literal[int] )** literal[int] + identifier[np] . identifier[cos] ( identifier[phi1] )* identifier[np] . identifier[cos] ( identifier[phi2] )* identifier[np] . identifier[sin] ( identifier[d_theta] / literal[int] )** literal[int] identifier[h] = identifier[np] . identifier[minimum] ( literal[int] , identifier[h] ) identifier[arc] = literal[int] * identifier[np] . identifier[arcsin] ( identifier[np] . identifier[sqrt] ( identifier[h] )) identifier[distance] = identifier[arc] * identifier[earth_radius] keyword[return] identifier[distance]
def great_circle_vec(lat1, lng1, lat2, lng2, earth_radius=6371009): """ Vectorized function to calculate the great-circle distance between two points or between vectors of points, using haversine. Parameters ---------- lat1 : float or array of float lng1 : float or array of float lat2 : float or array of float lng2 : float or array of float earth_radius : numeric radius of earth in units in which distance will be returned (default is meters) Returns ------- distance : float or vector of floats distance or vector of distances from (lat1, lng1) to (lat2, lng2) in units of earth_radius """ phi1 = np.deg2rad(lat1) phi2 = np.deg2rad(lat2) d_phi = phi2 - phi1 theta1 = np.deg2rad(lng1) theta2 = np.deg2rad(lng2) d_theta = theta2 - theta1 h = np.sin(d_phi / 2) ** 2 + np.cos(phi1) * np.cos(phi2) * np.sin(d_theta / 2) ** 2 h = np.minimum(1.0, h) # protect against floating point errors arc = 2 * np.arcsin(np.sqrt(h)) # return distance in units of earth_radius distance = arc * earth_radius return distance
def threaded_per_region(q, params): """ Helper for multithreading on a per-region basis :param q: :param params: :return: """ while True: try: params['region'] = q.get() method = params['method'] method(params) except Exception as e: printException(e) finally: q.task_done()
def function[threaded_per_region, parameter[q, params]]: constant[ Helper for multithreading on a per-region basis :param q: :param params: :return: ] while constant[True] begin[:] <ast.Try object at 0x7da1b2631120>
keyword[def] identifier[threaded_per_region] ( identifier[q] , identifier[params] ): literal[string] keyword[while] keyword[True] : keyword[try] : identifier[params] [ literal[string] ]= identifier[q] . identifier[get] () identifier[method] = identifier[params] [ literal[string] ] identifier[method] ( identifier[params] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[printException] ( identifier[e] ) keyword[finally] : identifier[q] . identifier[task_done] ()
def threaded_per_region(q, params): """ Helper for multithreading on a per-region basis :param q: :param params: :return: """ while True: try: params['region'] = q.get() method = params['method'] method(params) # depends on [control=['try'], data=[]] except Exception as e: printException(e) # depends on [control=['except'], data=['e']] finally: q.task_done() # depends on [control=['while'], data=[]]
def secgroup_delete(call=None, kwargs=None): ''' Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ''' if call != 'function': raise SaltCloudSystemExit( 'The secgroup_delete function must be called with -f or --function.' ) if kwargs is None: kwargs = {} name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning( 'Both the \'secgroup_id\' and \'name\' arguments were provided. ' '\'secgroup_id\' will take precedence.' ) elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) else: raise SaltCloudSystemExit( 'The secgroup_delete function requires either a \'name\' or a ' '\'secgroup_id\' to be provided.' ) server, user, password = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = { 'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2], } return data
def function[secgroup_delete, parameter[call, kwargs]]: constant[ Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 ] if compare[name[call] not_equal[!=] constant[function]] begin[:] <ast.Raise object at 0x7da20c6c73a0> if compare[name[kwargs] is constant[None]] begin[:] variable[kwargs] assign[=] dictionary[[], []] variable[name] assign[=] call[name[kwargs].get, parameter[constant[name], constant[None]]] variable[secgroup_id] assign[=] call[name[kwargs].get, parameter[constant[secgroup_id], constant[None]]] if name[secgroup_id] begin[:] if name[name] begin[:] call[name[log].warning, parameter[constant[Both the 'secgroup_id' and 'name' arguments were provided. 'secgroup_id' will take precedence.]]] <ast.Tuple object at 0x7da20c6c7c40> assign[=] call[name[_get_xml_rpc], parameter[]] variable[auth] assign[=] call[constant[:].join, parameter[list[[<ast.Name object at 0x7da20c76c820>, <ast.Name object at 0x7da20c76cb20>]]]] variable[response] assign[=] call[name[server].one.secgroup.delete, parameter[name[auth], call[name[int], parameter[name[secgroup_id]]]]] variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da18dc9aef0>, <ast.Constant object at 0x7da18dc98250>, <ast.Constant object at 0x7da18dc981c0>, <ast.Constant object at 0x7da18dc988b0>], [<ast.Constant object at 0x7da18dc9b9a0>, <ast.Subscript object at 0x7da18dc9a9e0>, <ast.Subscript object at 0x7da18dc9b130>, <ast.Subscript object at 0x7da18dc98640>]] return[name[data]]
keyword[def] identifier[secgroup_delete] ( identifier[call] = keyword[None] , identifier[kwargs] = keyword[None] ): literal[string] keyword[if] identifier[call] != literal[string] : keyword[raise] identifier[SaltCloudSystemExit] ( literal[string] ) keyword[if] identifier[kwargs] keyword[is] keyword[None] : identifier[kwargs] ={} identifier[name] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] ) identifier[secgroup_id] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] ) keyword[if] identifier[secgroup_id] : keyword[if] identifier[name] : identifier[log] . identifier[warning] ( literal[string] literal[string] ) keyword[elif] identifier[name] : identifier[secgroup_id] = identifier[get_secgroup_id] ( identifier[kwargs] ={ literal[string] : identifier[name] }) keyword[else] : keyword[raise] identifier[SaltCloudSystemExit] ( literal[string] literal[string] ) identifier[server] , identifier[user] , identifier[password] = identifier[_get_xml_rpc] () identifier[auth] = literal[string] . identifier[join] ([ identifier[user] , identifier[password] ]) identifier[response] = identifier[server] . identifier[one] . identifier[secgroup] . identifier[delete] ( identifier[auth] , identifier[int] ( identifier[secgroup_id] )) identifier[data] ={ literal[string] : literal[string] , literal[string] : identifier[response] [ literal[int] ], literal[string] : identifier[response] [ literal[int] ], literal[string] : identifier[response] [ literal[int] ], } keyword[return] identifier[data]
def secgroup_delete(call=None, kwargs=None): """ Deletes the given security group from OpenNebula. Either a name or a secgroup_id must be supplied. .. versionadded:: 2016.3.0 name The name of the security group to delete. Can be used instead of ``secgroup_id``. secgroup_id The ID of the security group to delete. Can be used instead of ``name``. CLI Example: .. code-block:: bash salt-cloud -f secgroup_delete opennebula name=my-secgroup salt-cloud --function secgroup_delete opennebula secgroup_id=100 """ if call != 'function': raise SaltCloudSystemExit('The secgroup_delete function must be called with -f or --function.') # depends on [control=['if'], data=[]] if kwargs is None: kwargs = {} # depends on [control=['if'], data=['kwargs']] name = kwargs.get('name', None) secgroup_id = kwargs.get('secgroup_id', None) if secgroup_id: if name: log.warning("Both the 'secgroup_id' and 'name' arguments were provided. 'secgroup_id' will take precedence.") # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif name: secgroup_id = get_secgroup_id(kwargs={'name': name}) # depends on [control=['if'], data=[]] else: raise SaltCloudSystemExit("The secgroup_delete function requires either a 'name' or a 'secgroup_id' to be provided.") (server, user, password) = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.secgroup.delete(auth, int(secgroup_id)) data = {'action': 'secgroup.delete', 'deleted': response[0], 'secgroup_id': response[1], 'error_code': response[2]} return data
def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split("\n") # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue l = l.replace("\t", " ") tokens += filter(lambda x: len(x) > 0, l.split(" ")) + [''] # find (...) and turn it into a single line ("capture" it) capturing = False captured = [] flattened = [] while len(tokens) > 0: tok = tokens.pop(0) if not capturing and len(tok) == 0: # normal end-of-line if len(captured) > 0: flattened.append(" ".join(captured)) captured = [] continue if tok.startswith("("): # begin grouping tok = tok.lstrip("(") capturing = True if capturing and tok.endswith(")"): # end grouping. next end-of-line will turn this sequence into a flat line tok = tok.rstrip(")") capturing = False captured.append(tok) return "\n".join(flattened)
def function[flatten, parameter[text]]: constant[ Flatten the text: * make sure each record is on one line. * remove parenthesis ] variable[lines] assign[=] call[name[text].split, parameter[constant[ ]]] variable[tokens] assign[=] list[[]] for taget[name[l]] in starred[name[lines]] begin[:] if compare[call[name[len], parameter[name[l]]] equal[==] constant[0]] begin[:] continue variable[l] assign[=] call[name[l].replace, parameter[constant[ ], constant[ ]]] <ast.AugAssign object at 0x7da18f811900> variable[capturing] assign[=] constant[False] variable[captured] assign[=] list[[]] variable[flattened] assign[=] list[[]] while compare[call[name[len], parameter[name[tokens]]] greater[>] constant[0]] begin[:] variable[tok] assign[=] call[name[tokens].pop, parameter[constant[0]]] if <ast.BoolOp object at 0x7da18f8100d0> begin[:] if compare[call[name[len], parameter[name[captured]]] greater[>] constant[0]] begin[:] call[name[flattened].append, parameter[call[constant[ ].join, parameter[name[captured]]]]] variable[captured] assign[=] list[[]] continue if call[name[tok].startswith, parameter[constant[(]]] begin[:] variable[tok] assign[=] call[name[tok].lstrip, parameter[constant[(]]] variable[capturing] assign[=] constant[True] if <ast.BoolOp object at 0x7da204567ee0> begin[:] variable[tok] assign[=] call[name[tok].rstrip, parameter[constant[)]]] variable[capturing] assign[=] constant[False] call[name[captured].append, parameter[name[tok]]] return[call[constant[ ].join, parameter[name[flattened]]]]
keyword[def] identifier[flatten] ( identifier[text] ): literal[string] identifier[lines] = identifier[text] . identifier[split] ( literal[string] ) identifier[tokens] =[] keyword[for] identifier[l] keyword[in] identifier[lines] : keyword[if] identifier[len] ( identifier[l] )== literal[int] : keyword[continue] identifier[l] = identifier[l] . identifier[replace] ( literal[string] , literal[string] ) identifier[tokens] += identifier[filter] ( keyword[lambda] identifier[x] : identifier[len] ( identifier[x] )> literal[int] , identifier[l] . identifier[split] ( literal[string] ))+[ literal[string] ] identifier[capturing] = keyword[False] identifier[captured] =[] identifier[flattened] =[] keyword[while] identifier[len] ( identifier[tokens] )> literal[int] : identifier[tok] = identifier[tokens] . identifier[pop] ( literal[int] ) keyword[if] keyword[not] identifier[capturing] keyword[and] identifier[len] ( identifier[tok] )== literal[int] : keyword[if] identifier[len] ( identifier[captured] )> literal[int] : identifier[flattened] . identifier[append] ( literal[string] . identifier[join] ( identifier[captured] )) identifier[captured] =[] keyword[continue] keyword[if] identifier[tok] . identifier[startswith] ( literal[string] ): identifier[tok] = identifier[tok] . identifier[lstrip] ( literal[string] ) identifier[capturing] = keyword[True] keyword[if] identifier[capturing] keyword[and] identifier[tok] . identifier[endswith] ( literal[string] ): identifier[tok] = identifier[tok] . identifier[rstrip] ( literal[string] ) identifier[capturing] = keyword[False] identifier[captured] . identifier[append] ( identifier[tok] ) keyword[return] literal[string] . identifier[join] ( identifier[flattened] )
def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split('\n') # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue # depends on [control=['if'], data=[]] l = l.replace('\t', ' ') tokens += filter(lambda x: len(x) > 0, l.split(' ')) + [''] # depends on [control=['for'], data=['l']] # find (...) and turn it into a single line ("capture" it) capturing = False captured = [] flattened = [] while len(tokens) > 0: tok = tokens.pop(0) if not capturing and len(tok) == 0: # normal end-of-line if len(captured) > 0: flattened.append(' '.join(captured)) captured = [] # depends on [control=['if'], data=[]] continue # depends on [control=['if'], data=[]] if tok.startswith('('): # begin grouping tok = tok.lstrip('(') capturing = True # depends on [control=['if'], data=[]] if capturing and tok.endswith(')'): # end grouping. next end-of-line will turn this sequence into a flat line tok = tok.rstrip(')') capturing = False # depends on [control=['if'], data=[]] captured.append(tok) # depends on [control=['while'], data=[]] return '\n'.join(flattened)
def graph_branches_from_node(self, node): """ Returns branches that are connected to `node` Args ---- node: GridDing0 Ding0 object (member of graph) Returns ------- :any:`list` List of tuples (node in :obj:`GridDing0`, branch in :obj:`BranchDing0`) :: (node , branch_0 ), ..., (node , branch_N ), """ # TODO: This method can be replaced and speed up by using NetworkX' neighbors() branches = [] branches_dict = self._graph.adj[node] for branch in branches_dict.items(): branches.append(branch) return sorted(branches, key=lambda _: repr(_))
def function[graph_branches_from_node, parameter[self, node]]: constant[ Returns branches that are connected to `node` Args ---- node: GridDing0 Ding0 object (member of graph) Returns ------- :any:`list` List of tuples (node in :obj:`GridDing0`, branch in :obj:`BranchDing0`) :: (node , branch_0 ), ..., (node , branch_N ), ] variable[branches] assign[=] list[[]] variable[branches_dict] assign[=] call[name[self]._graph.adj][name[node]] for taget[name[branch]] in starred[call[name[branches_dict].items, parameter[]]] begin[:] call[name[branches].append, parameter[name[branch]]] return[call[name[sorted], parameter[name[branches]]]]
keyword[def] identifier[graph_branches_from_node] ( identifier[self] , identifier[node] ): literal[string] identifier[branches] =[] identifier[branches_dict] = identifier[self] . identifier[_graph] . identifier[adj] [ identifier[node] ] keyword[for] identifier[branch] keyword[in] identifier[branches_dict] . identifier[items] (): identifier[branches] . identifier[append] ( identifier[branch] ) keyword[return] identifier[sorted] ( identifier[branches] , identifier[key] = keyword[lambda] identifier[_] : identifier[repr] ( identifier[_] ))
def graph_branches_from_node(self, node): """ Returns branches that are connected to `node` Args ---- node: GridDing0 Ding0 object (member of graph) Returns ------- :any:`list` List of tuples (node in :obj:`GridDing0`, branch in :obj:`BranchDing0`) :: (node , branch_0 ), ..., (node , branch_N ), """ # TODO: This method can be replaced and speed up by using NetworkX' neighbors() branches = [] branches_dict = self._graph.adj[node] for branch in branches_dict.items(): branches.append(branch) # depends on [control=['for'], data=['branch']] return sorted(branches, key=lambda _: repr(_))
def _from_dict(cls, _dict): """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} if 'fonts' in _dict: args['fonts'] = [ FontSetting._from_dict(x) for x in (_dict.get('fonts')) ] if 'styles' in _dict: args['styles'] = [ WordStyle._from_dict(x) for x in (_dict.get('styles')) ] return cls(**args)
def function[_from_dict, parameter[cls, _dict]]: constant[Initialize a WordHeadingDetection object from a json dictionary.] variable[args] assign[=] dictionary[[], []] if compare[constant[fonts] in name[_dict]] begin[:] call[name[args]][constant[fonts]] assign[=] <ast.ListComp object at 0x7da20c76fa90> if compare[constant[styles] in name[_dict]] begin[:] call[name[args]][constant[styles]] assign[=] <ast.ListComp object at 0x7da20c76dde0> return[call[name[cls], parameter[]]]
keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ): literal[string] identifier[args] ={} keyword[if] literal[string] keyword[in] identifier[_dict] : identifier[args] [ literal[string] ]=[ identifier[FontSetting] . identifier[_from_dict] ( identifier[x] ) keyword[for] identifier[x] keyword[in] ( identifier[_dict] . identifier[get] ( literal[string] )) ] keyword[if] literal[string] keyword[in] identifier[_dict] : identifier[args] [ literal[string] ]=[ identifier[WordStyle] . identifier[_from_dict] ( identifier[x] ) keyword[for] identifier[x] keyword[in] ( identifier[_dict] . identifier[get] ( literal[string] )) ] keyword[return] identifier[cls] (** identifier[args] )
def _from_dict(cls, _dict): """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} if 'fonts' in _dict: args['fonts'] = [FontSetting._from_dict(x) for x in _dict.get('fonts')] # depends on [control=['if'], data=['_dict']] if 'styles' in _dict: args['styles'] = [WordStyle._from_dict(x) for x in _dict.get('styles')] # depends on [control=['if'], data=['_dict']] return cls(**args)
def get_teams(self, team_filter=''): '''**Description** Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned. **Arguments** - **team_filter**: the team filter to match when returning the list of teams **Success Return Value** The teams that match the filter. ''' res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] ret = [t for t in res.json()['teams'] if team_filter in t['name']] return [True, ret]
def function[get_teams, parameter[self, team_filter]]: constant[**Description** Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned. **Arguments** - **team_filter**: the team filter to match when returning the list of teams **Success Return Value** The teams that match the filter. ] variable[res] assign[=] call[name[requests].get, parameter[binary_operation[name[self].url + constant[/api/teams]]]] if <ast.UnaryOp object at 0x7da2041d9840> begin[:] return[list[[<ast.Constant object at 0x7da2041d9480>, <ast.Attribute object at 0x7da2041dba00>]]] variable[ret] assign[=] <ast.ListComp object at 0x7da2041d9b10> return[list[[<ast.Constant object at 0x7da2041dacb0>, <ast.Name object at 0x7da2041d91b0>]]]
keyword[def] identifier[get_teams] ( identifier[self] , identifier[team_filter] = literal[string] ): literal[string] identifier[res] = identifier[requests] . identifier[get] ( identifier[self] . identifier[url] + literal[string] , identifier[headers] = identifier[self] . identifier[hdrs] , identifier[verify] = identifier[self] . identifier[ssl_verify] ) keyword[if] keyword[not] identifier[self] . identifier[_checkResponse] ( identifier[res] ): keyword[return] [ keyword[False] , identifier[self] . identifier[lasterr] ] identifier[ret] =[ identifier[t] keyword[for] identifier[t] keyword[in] identifier[res] . identifier[json] ()[ literal[string] ] keyword[if] identifier[team_filter] keyword[in] identifier[t] [ literal[string] ]] keyword[return] [ keyword[True] , identifier[ret] ]
def get_teams(self, team_filter=''): """**Description** Return the set of teams that match the filter specified. The *team_filter* should be a substring of the names of the teams to be returned. **Arguments** - **team_filter**: the team filter to match when returning the list of teams **Success Return Value** The teams that match the filter. """ res = requests.get(self.url + '/api/teams', headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] # depends on [control=['if'], data=[]] ret = [t for t in res.json()['teams'] if team_filter in t['name']] return [True, ret]
def vel_sed_diffuser(sed_inputs=sed_dict): """Return the velocity through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (q_diffuser(sed_inputs).magnitude / (w_diffuser_inner(w_tank) * L_diffuser_inner(w_tank)).magnitude)
def function[vel_sed_diffuser, parameter[sed_inputs]]: constant[Return the velocity through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> ] return[binary_operation[call[name[q_diffuser], parameter[name[sed_inputs]]].magnitude / binary_operation[call[name[w_diffuser_inner], parameter[name[w_tank]]] * call[name[L_diffuser_inner], parameter[name[w_tank]]]].magnitude]]
keyword[def] identifier[vel_sed_diffuser] ( identifier[sed_inputs] = identifier[sed_dict] ): literal[string] keyword[return] ( identifier[q_diffuser] ( identifier[sed_inputs] ). identifier[magnitude] /( identifier[w_diffuser_inner] ( identifier[w_tank] )* identifier[L_diffuser_inner] ( identifier[w_tank] )). identifier[magnitude] )
def vel_sed_diffuser(sed_inputs=sed_dict): """Return the velocity through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return q_diffuser(sed_inputs).magnitude / (w_diffuser_inner(w_tank) * L_diffuser_inner(w_tank)).magnitude
def read_udp(self, length): """Read User Datagram Protocol (UDP). Structure of UDP header [RFC 768]: 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--------+ | | | | Length | Checksum | +--------+--------+--------+--------+ | | data octets ... +---------------- ... Octets Bits Name Description 0 0 udp.srcport Source Port 2 16 udp.dstport Destination Port 4 32 udp.len Length (header includes) 6 48 udp.checksum Checksum """ if length is None: length = len(self) _srcp = self._read_unpack(2) _dstp = self._read_unpack(2) _tlen = self._read_unpack(2) _csum = self._read_fileng(2) udp = dict( srcport=_srcp, dstport=_dstp, len=_tlen, checksum=_csum, ) length = udp['len'] - 8 udp['packet'] = self._read_packet(header=8, payload=length) return self._decode_next_layer(udp, None, length)
def function[read_udp, parameter[self, length]]: constant[Read User Datagram Protocol (UDP). Structure of UDP header [RFC 768]: 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--------+ | | | | Length | Checksum | +--------+--------+--------+--------+ | | data octets ... +---------------- ... Octets Bits Name Description 0 0 udp.srcport Source Port 2 16 udp.dstport Destination Port 4 32 udp.len Length (header includes) 6 48 udp.checksum Checksum ] if compare[name[length] is constant[None]] begin[:] variable[length] assign[=] call[name[len], parameter[name[self]]] variable[_srcp] assign[=] call[name[self]._read_unpack, parameter[constant[2]]] variable[_dstp] assign[=] call[name[self]._read_unpack, parameter[constant[2]]] variable[_tlen] assign[=] call[name[self]._read_unpack, parameter[constant[2]]] variable[_csum] assign[=] call[name[self]._read_fileng, parameter[constant[2]]] variable[udp] assign[=] call[name[dict], parameter[]] variable[length] assign[=] binary_operation[call[name[udp]][constant[len]] - constant[8]] call[name[udp]][constant[packet]] assign[=] call[name[self]._read_packet, parameter[]] return[call[name[self]._decode_next_layer, parameter[name[udp], constant[None], name[length]]]]
keyword[def] identifier[read_udp] ( identifier[self] , identifier[length] ): literal[string] keyword[if] identifier[length] keyword[is] keyword[None] : identifier[length] = identifier[len] ( identifier[self] ) identifier[_srcp] = identifier[self] . identifier[_read_unpack] ( literal[int] ) identifier[_dstp] = identifier[self] . identifier[_read_unpack] ( literal[int] ) identifier[_tlen] = identifier[self] . identifier[_read_unpack] ( literal[int] ) identifier[_csum] = identifier[self] . identifier[_read_fileng] ( literal[int] ) identifier[udp] = identifier[dict] ( identifier[srcport] = identifier[_srcp] , identifier[dstport] = identifier[_dstp] , identifier[len] = identifier[_tlen] , identifier[checksum] = identifier[_csum] , ) identifier[length] = identifier[udp] [ literal[string] ]- literal[int] identifier[udp] [ literal[string] ]= identifier[self] . identifier[_read_packet] ( identifier[header] = literal[int] , identifier[payload] = identifier[length] ) keyword[return] identifier[self] . identifier[_decode_next_layer] ( identifier[udp] , keyword[None] , identifier[length] )
def read_udp(self, length): """Read User Datagram Protocol (UDP). Structure of UDP header [RFC 768]: 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--------+ | | | | Length | Checksum | +--------+--------+--------+--------+ | | data octets ... +---------------- ... Octets Bits Name Description 0 0 udp.srcport Source Port 2 16 udp.dstport Destination Port 4 32 udp.len Length (header includes) 6 48 udp.checksum Checksum """ if length is None: length = len(self) # depends on [control=['if'], data=['length']] _srcp = self._read_unpack(2) _dstp = self._read_unpack(2) _tlen = self._read_unpack(2) _csum = self._read_fileng(2) udp = dict(srcport=_srcp, dstport=_dstp, len=_tlen, checksum=_csum) length = udp['len'] - 8 udp['packet'] = self._read_packet(header=8, payload=length) return self._decode_next_layer(udp, None, length)
def _RetryLoop(self, func, timeout=None): """Retries an operation until success or deadline. Args: func: The function to run. Must take a timeout, in seconds, as a single parameter. If it raises grpc.RpcError and deadline has not be reached, it will be run again. timeout: Retries will continue until timeout seconds have passed. """ timeout = timeout or self.DEFAULT_TIMEOUT deadline = time.time() + timeout sleep = 1 while True: try: return func(timeout) except grpc.RpcError: if time.time() + sleep > deadline: raise time.sleep(sleep) sleep *= 2 timeout = deadline - time.time()
def function[_RetryLoop, parameter[self, func, timeout]]: constant[Retries an operation until success or deadline. Args: func: The function to run. Must take a timeout, in seconds, as a single parameter. If it raises grpc.RpcError and deadline has not be reached, it will be run again. timeout: Retries will continue until timeout seconds have passed. ] variable[timeout] assign[=] <ast.BoolOp object at 0x7da18dc99870> variable[deadline] assign[=] binary_operation[call[name[time].time, parameter[]] + name[timeout]] variable[sleep] assign[=] constant[1] while constant[True] begin[:] <ast.Try object at 0x7da2054a7100>
keyword[def] identifier[_RetryLoop] ( identifier[self] , identifier[func] , identifier[timeout] = keyword[None] ): literal[string] identifier[timeout] = identifier[timeout] keyword[or] identifier[self] . identifier[DEFAULT_TIMEOUT] identifier[deadline] = identifier[time] . identifier[time] ()+ identifier[timeout] identifier[sleep] = literal[int] keyword[while] keyword[True] : keyword[try] : keyword[return] identifier[func] ( identifier[timeout] ) keyword[except] identifier[grpc] . identifier[RpcError] : keyword[if] identifier[time] . identifier[time] ()+ identifier[sleep] > identifier[deadline] : keyword[raise] identifier[time] . identifier[sleep] ( identifier[sleep] ) identifier[sleep] *= literal[int] identifier[timeout] = identifier[deadline] - identifier[time] . identifier[time] ()
def _RetryLoop(self, func, timeout=None): """Retries an operation until success or deadline. Args: func: The function to run. Must take a timeout, in seconds, as a single parameter. If it raises grpc.RpcError and deadline has not be reached, it will be run again. timeout: Retries will continue until timeout seconds have passed. """ timeout = timeout or self.DEFAULT_TIMEOUT deadline = time.time() + timeout sleep = 1 while True: try: return func(timeout) # depends on [control=['try'], data=[]] except grpc.RpcError: if time.time() + sleep > deadline: raise # depends on [control=['if'], data=[]] time.sleep(sleep) sleep *= 2 timeout = deadline - time.time() # depends on [control=['except'], data=[]] # depends on [control=['while'], data=[]]
def _detect(self): """ Detect uninitialized local variables Recursively visit the calls Returns: dict: [contract name] = set(local variable uninitialized) """ results = [] self.results = [] self.visited_all_paths = {} for contract in self.slither.contracts: for function in contract.functions: if function.is_implemented and function.contract == contract: if function.contains_assembly: continue # dont consider storage variable, as they are detected by another detector uninitialized_local_variables = [v for v in function.local_variables if not v.is_storage and v.uninitialized] function.entry_point.context[self.key] = uninitialized_local_variables self._detect_uninitialized(function, function.entry_point, []) all_results = list(set(self.results)) for(function, uninitialized_local_variable) in all_results: var_name = uninitialized_local_variable.name info = "{} in {}.{} ({}) is a local variable never initialiazed\n" info = info.format(var_name, function.contract.name, function.name, uninitialized_local_variable.source_mapping_str) json = self.generate_json_result(info) self.add_variable_to_json(uninitialized_local_variable, json) self.add_function_to_json(function, json) results.append(json) return results
def function[_detect, parameter[self]]: constant[ Detect uninitialized local variables Recursively visit the calls Returns: dict: [contract name] = set(local variable uninitialized) ] variable[results] assign[=] list[[]] name[self].results assign[=] list[[]] name[self].visited_all_paths assign[=] dictionary[[], []] for taget[name[contract]] in starred[name[self].slither.contracts] begin[:] for taget[name[function]] in starred[name[contract].functions] begin[:] if <ast.BoolOp object at 0x7da18c4cd180> begin[:] if name[function].contains_assembly begin[:] continue variable[uninitialized_local_variables] assign[=] <ast.ListComp object at 0x7da18c4cde70> call[name[function].entry_point.context][name[self].key] assign[=] name[uninitialized_local_variables] call[name[self]._detect_uninitialized, parameter[name[function], name[function].entry_point, list[[]]]] variable[all_results] assign[=] call[name[list], parameter[call[name[set], parameter[name[self].results]]]] for taget[tuple[[<ast.Name object at 0x7da18c4cc610>, <ast.Name object at 0x7da18c4ce8c0>]]] in starred[name[all_results]] begin[:] variable[var_name] assign[=] name[uninitialized_local_variable].name variable[info] assign[=] constant[{} in {}.{} ({}) is a local variable never initialiazed ] variable[info] assign[=] call[name[info].format, parameter[name[var_name], name[function].contract.name, name[function].name, name[uninitialized_local_variable].source_mapping_str]] variable[json] assign[=] call[name[self].generate_json_result, parameter[name[info]]] call[name[self].add_variable_to_json, parameter[name[uninitialized_local_variable], name[json]]] call[name[self].add_function_to_json, parameter[name[function], name[json]]] call[name[results].append, parameter[name[json]]] return[name[results]]
keyword[def] identifier[_detect] ( identifier[self] ): literal[string] identifier[results] =[] identifier[self] . identifier[results] =[] identifier[self] . identifier[visited_all_paths] ={} keyword[for] identifier[contract] keyword[in] identifier[self] . identifier[slither] . identifier[contracts] : keyword[for] identifier[function] keyword[in] identifier[contract] . identifier[functions] : keyword[if] identifier[function] . identifier[is_implemented] keyword[and] identifier[function] . identifier[contract] == identifier[contract] : keyword[if] identifier[function] . identifier[contains_assembly] : keyword[continue] identifier[uninitialized_local_variables] =[ identifier[v] keyword[for] identifier[v] keyword[in] identifier[function] . identifier[local_variables] keyword[if] keyword[not] identifier[v] . identifier[is_storage] keyword[and] identifier[v] . identifier[uninitialized] ] identifier[function] . identifier[entry_point] . identifier[context] [ identifier[self] . identifier[key] ]= identifier[uninitialized_local_variables] identifier[self] . identifier[_detect_uninitialized] ( identifier[function] , identifier[function] . identifier[entry_point] ,[]) identifier[all_results] = identifier[list] ( identifier[set] ( identifier[self] . identifier[results] )) keyword[for] ( identifier[function] , identifier[uninitialized_local_variable] ) keyword[in] identifier[all_results] : identifier[var_name] = identifier[uninitialized_local_variable] . identifier[name] identifier[info] = literal[string] identifier[info] = identifier[info] . identifier[format] ( identifier[var_name] , identifier[function] . identifier[contract] . identifier[name] , identifier[function] . identifier[name] , identifier[uninitialized_local_variable] . identifier[source_mapping_str] ) identifier[json] = identifier[self] . identifier[generate_json_result] ( identifier[info] ) identifier[self] . identifier[add_variable_to_json] ( identifier[uninitialized_local_variable] , identifier[json] ) identifier[self] . identifier[add_function_to_json] ( identifier[function] , identifier[json] ) identifier[results] . identifier[append] ( identifier[json] ) keyword[return] identifier[results]
def _detect(self): """ Detect uninitialized local variables Recursively visit the calls Returns: dict: [contract name] = set(local variable uninitialized) """ results = [] self.results = [] self.visited_all_paths = {} for contract in self.slither.contracts: for function in contract.functions: if function.is_implemented and function.contract == contract: if function.contains_assembly: continue # depends on [control=['if'], data=[]] # dont consider storage variable, as they are detected by another detector uninitialized_local_variables = [v for v in function.local_variables if not v.is_storage and v.uninitialized] function.entry_point.context[self.key] = uninitialized_local_variables self._detect_uninitialized(function, function.entry_point, []) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['function']] # depends on [control=['for'], data=['contract']] all_results = list(set(self.results)) for (function, uninitialized_local_variable) in all_results: var_name = uninitialized_local_variable.name info = '{} in {}.{} ({}) is a local variable never initialiazed\n' info = info.format(var_name, function.contract.name, function.name, uninitialized_local_variable.source_mapping_str) json = self.generate_json_result(info) self.add_variable_to_json(uninitialized_local_variable, json) self.add_function_to_json(function, json) results.append(json) # depends on [control=['for'], data=[]] return results
def calc_mse(q1, q2): """Compare the results of two simulations""" # Difference in positions between two simulations dq = q2 - q1 # Mean squared error in AUs return np.sqrt(np.mean(dq*dq))/au2m
def function[calc_mse, parameter[q1, q2]]: constant[Compare the results of two simulations] variable[dq] assign[=] binary_operation[name[q2] - name[q1]] return[binary_operation[call[name[np].sqrt, parameter[call[name[np].mean, parameter[binary_operation[name[dq] * name[dq]]]]]] / name[au2m]]]
keyword[def] identifier[calc_mse] ( identifier[q1] , identifier[q2] ): literal[string] identifier[dq] = identifier[q2] - identifier[q1] keyword[return] identifier[np] . identifier[sqrt] ( identifier[np] . identifier[mean] ( identifier[dq] * identifier[dq] ))/ identifier[au2m]
def calc_mse(q1, q2): """Compare the results of two simulations""" # Difference in positions between two simulations dq = q2 - q1 # Mean squared error in AUs return np.sqrt(np.mean(dq * dq)) / au2m
def tab_complete(input_list): """ <Purpose> Gets the list of all valid tab-complete strings from all enabled modules. <Arguments> input_list: The list of words the user entered. <Side Effects> None <Exceptions> None <Returns> A list of valid tab-complete strings """ commands = [] for module in get_enabled_modules(): if 'tab_completer' in module_data[module]: commands += module_data[module]['tab_completer'](input_list) return commands
def function[tab_complete, parameter[input_list]]: constant[ <Purpose> Gets the list of all valid tab-complete strings from all enabled modules. <Arguments> input_list: The list of words the user entered. <Side Effects> None <Exceptions> None <Returns> A list of valid tab-complete strings ] variable[commands] assign[=] list[[]] for taget[name[module]] in starred[call[name[get_enabled_modules], parameter[]]] begin[:] if compare[constant[tab_completer] in call[name[module_data]][name[module]]] begin[:] <ast.AugAssign object at 0x7da1b27ea140> return[name[commands]]
keyword[def] identifier[tab_complete] ( identifier[input_list] ): literal[string] identifier[commands] =[] keyword[for] identifier[module] keyword[in] identifier[get_enabled_modules] (): keyword[if] literal[string] keyword[in] identifier[module_data] [ identifier[module] ]: identifier[commands] += identifier[module_data] [ identifier[module] ][ literal[string] ]( identifier[input_list] ) keyword[return] identifier[commands]
def tab_complete(input_list): """ <Purpose> Gets the list of all valid tab-complete strings from all enabled modules. <Arguments> input_list: The list of words the user entered. <Side Effects> None <Exceptions> None <Returns> A list of valid tab-complete strings """ commands = [] for module in get_enabled_modules(): if 'tab_completer' in module_data[module]: commands += module_data[module]['tab_completer'](input_list) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['module']] return commands
def validate(self): """Validate that the FoldCountContextField is correctly representable.""" if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format( type(self.fold_scope_location), self.fold_scope_location)) if self.fold_scope_location.field != COUNT_META_FIELD_NAME: raise AssertionError(u'Unexpected field in the FoldScopeLocation of this ' u'FoldCountContextField object: {} {}' .format(self.fold_scope_location, self))
def function[validate, parameter[self]]: constant[Validate that the FoldCountContextField is correctly representable.] if <ast.UnaryOp object at 0x7da1b17cdbd0> begin[:] <ast.Raise object at 0x7da1b17cdc60> if compare[name[self].fold_scope_location.field not_equal[!=] name[COUNT_META_FIELD_NAME]] begin[:] <ast.Raise object at 0x7da1b17ccfd0>
keyword[def] identifier[validate] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[fold_scope_location] , identifier[FoldScopeLocation] ): keyword[raise] identifier[TypeError] ( literal[string] . identifier[format] ( identifier[type] ( identifier[self] . identifier[fold_scope_location] ), identifier[self] . identifier[fold_scope_location] )) keyword[if] identifier[self] . identifier[fold_scope_location] . identifier[field] != identifier[COUNT_META_FIELD_NAME] : keyword[raise] identifier[AssertionError] ( literal[string] literal[string] . identifier[format] ( identifier[self] . identifier[fold_scope_location] , identifier[self] ))
def validate(self): """Validate that the FoldCountContextField is correctly representable.""" if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(type(self.fold_scope_location), self.fold_scope_location)) # depends on [control=['if'], data=[]] if self.fold_scope_location.field != COUNT_META_FIELD_NAME: raise AssertionError(u'Unexpected field in the FoldScopeLocation of this FoldCountContextField object: {} {}'.format(self.fold_scope_location, self)) # depends on [control=['if'], data=[]]
def get_dataset(self, dataset): """ Checks to see if the dataset is present. If not, it downloads and unzips it. """ # If the dataset is present, no need to download anything. success = True dataset_path = self.base_dataset_path + dataset if not isdir(dataset_path): # Try 5 times to download. The download page is unreliable, so we need a few tries. was_error = False for iteration in range(5): # Guard against trying again if successful if iteration == 0 or was_error is True: zip_path = dataset_path + ".zip" # Download zip files if they're not there if not isfile(zip_path): try: with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset) as pbar: urlretrieve(self.datasets[dataset]["url"], zip_path, pbar.hook) except Exception as ex: print("Error downloading %s: %s" % (dataset, ex)) was_error = True # Unzip the data files if not isdir(dataset_path): try: with zipfile.ZipFile(zip_path) as zip_archive: zip_archive.extractall(path=dataset_path) zip_archive.close() except Exception as ex: print("Error unzipping %s: %s" % (zip_path, ex)) # Usually the error is caused by a bad zip file. # Delete it so the program will try to download it again. try: remove(zip_path) except FileNotFoundError: pass was_error = True if was_error: print("\nThis recognizer is trained by the CASIA handwriting database.") print("If the download doesn't work, you can get the files at %s" % self.datasets[dataset]["url"]) print("If you have download problems, " "wget may be effective at downloading because of download resuming.") success = False return success
def function[get_dataset, parameter[self, dataset]]: constant[ Checks to see if the dataset is present. If not, it downloads and unzips it. ] variable[success] assign[=] constant[True] variable[dataset_path] assign[=] binary_operation[name[self].base_dataset_path + name[dataset]] if <ast.UnaryOp object at 0x7da20c992680> begin[:] variable[was_error] assign[=] constant[False] for taget[name[iteration]] in starred[call[name[range], parameter[constant[5]]]] begin[:] if <ast.BoolOp object at 0x7da20c992da0> begin[:] variable[zip_path] assign[=] binary_operation[name[dataset_path] + constant[.zip]] if <ast.UnaryOp object at 0x7da20c993310> begin[:] <ast.Try object at 0x7da20c991c30> if <ast.UnaryOp object at 0x7da2044c1780> begin[:] <ast.Try object at 0x7da1b0fecac0> if name[was_error] begin[:] call[name[print], parameter[constant[ This recognizer is trained by the CASIA handwriting database.]]] call[name[print], parameter[binary_operation[constant[If the download doesn't work, you can get the files at %s] <ast.Mod object at 0x7da2590d6920> call[call[name[self].datasets][name[dataset]]][constant[url]]]]] call[name[print], parameter[constant[If you have download problems, wget may be effective at downloading because of download resuming.]]] variable[success] assign[=] constant[False] return[name[success]]
keyword[def] identifier[get_dataset] ( identifier[self] , identifier[dataset] ): literal[string] identifier[success] = keyword[True] identifier[dataset_path] = identifier[self] . identifier[base_dataset_path] + identifier[dataset] keyword[if] keyword[not] identifier[isdir] ( identifier[dataset_path] ): identifier[was_error] = keyword[False] keyword[for] identifier[iteration] keyword[in] identifier[range] ( literal[int] ): keyword[if] identifier[iteration] == literal[int] keyword[or] identifier[was_error] keyword[is] keyword[True] : identifier[zip_path] = identifier[dataset_path] + literal[string] keyword[if] keyword[not] identifier[isfile] ( identifier[zip_path] ): keyword[try] : keyword[with] identifier[DLProgress] ( identifier[unit] = literal[string] , identifier[unit_scale] = keyword[True] , identifier[miniters] = literal[int] , identifier[desc] = identifier[dataset] ) keyword[as] identifier[pbar] : identifier[urlretrieve] ( identifier[self] . identifier[datasets] [ identifier[dataset] ][ literal[string] ], identifier[zip_path] , identifier[pbar] . identifier[hook] ) keyword[except] identifier[Exception] keyword[as] identifier[ex] : identifier[print] ( literal[string] %( identifier[dataset] , identifier[ex] )) identifier[was_error] = keyword[True] keyword[if] keyword[not] identifier[isdir] ( identifier[dataset_path] ): keyword[try] : keyword[with] identifier[zipfile] . identifier[ZipFile] ( identifier[zip_path] ) keyword[as] identifier[zip_archive] : identifier[zip_archive] . identifier[extractall] ( identifier[path] = identifier[dataset_path] ) identifier[zip_archive] . identifier[close] () keyword[except] identifier[Exception] keyword[as] identifier[ex] : identifier[print] ( literal[string] %( identifier[zip_path] , identifier[ex] )) keyword[try] : identifier[remove] ( identifier[zip_path] ) keyword[except] identifier[FileNotFoundError] : keyword[pass] identifier[was_error] = keyword[True] keyword[if] identifier[was_error] : identifier[print] ( literal[string] ) identifier[print] ( literal[string] % identifier[self] . identifier[datasets] [ identifier[dataset] ][ literal[string] ]) identifier[print] ( literal[string] literal[string] ) identifier[success] = keyword[False] keyword[return] identifier[success]
def get_dataset(self, dataset): """ Checks to see if the dataset is present. If not, it downloads and unzips it. """ # If the dataset is present, no need to download anything. success = True dataset_path = self.base_dataset_path + dataset if not isdir(dataset_path): # Try 5 times to download. The download page is unreliable, so we need a few tries. was_error = False for iteration in range(5): # Guard against trying again if successful if iteration == 0 or was_error is True: zip_path = dataset_path + '.zip' # Download zip files if they're not there if not isfile(zip_path): try: with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset) as pbar: urlretrieve(self.datasets[dataset]['url'], zip_path, pbar.hook) # depends on [control=['with'], data=['pbar']] # depends on [control=['try'], data=[]] except Exception as ex: print('Error downloading %s: %s' % (dataset, ex)) was_error = True # depends on [control=['except'], data=['ex']] # depends on [control=['if'], data=[]] # Unzip the data files if not isdir(dataset_path): try: with zipfile.ZipFile(zip_path) as zip_archive: zip_archive.extractall(path=dataset_path) zip_archive.close() # depends on [control=['with'], data=['zip_archive']] # depends on [control=['try'], data=[]] except Exception as ex: print('Error unzipping %s: %s' % (zip_path, ex)) # Usually the error is caused by a bad zip file. # Delete it so the program will try to download it again. try: remove(zip_path) # depends on [control=['try'], data=[]] except FileNotFoundError: pass # depends on [control=['except'], data=[]] was_error = True # depends on [control=['except'], data=['ex']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['iteration']] if was_error: print('\nThis recognizer is trained by the CASIA handwriting database.') print("If the download doesn't work, you can get the files at %s" % self.datasets[dataset]['url']) print('If you have download problems, wget may be effective at downloading because of download resuming.') success = False # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return success
def delete(stack, region, profile): """ Delete the given CloudFormation stack. """ ini_data = {} environment = {} environment['stack_name'] = stack if region: environment['region'] = region else: environment['region'] = find_myself() if profile: environment['profile'] = profile ini_data['environment'] = environment if start_smash(ini_data): sys.exit(0) else: sys.exit(1)
def function[delete, parameter[stack, region, profile]]: constant[ Delete the given CloudFormation stack. ] variable[ini_data] assign[=] dictionary[[], []] variable[environment] assign[=] dictionary[[], []] call[name[environment]][constant[stack_name]] assign[=] name[stack] if name[region] begin[:] call[name[environment]][constant[region]] assign[=] name[region] if name[profile] begin[:] call[name[environment]][constant[profile]] assign[=] name[profile] call[name[ini_data]][constant[environment]] assign[=] name[environment] if call[name[start_smash], parameter[name[ini_data]]] begin[:] call[name[sys].exit, parameter[constant[0]]]
keyword[def] identifier[delete] ( identifier[stack] , identifier[region] , identifier[profile] ): literal[string] identifier[ini_data] ={} identifier[environment] ={} identifier[environment] [ literal[string] ]= identifier[stack] keyword[if] identifier[region] : identifier[environment] [ literal[string] ]= identifier[region] keyword[else] : identifier[environment] [ literal[string] ]= identifier[find_myself] () keyword[if] identifier[profile] : identifier[environment] [ literal[string] ]= identifier[profile] identifier[ini_data] [ literal[string] ]= identifier[environment] keyword[if] identifier[start_smash] ( identifier[ini_data] ): identifier[sys] . identifier[exit] ( literal[int] ) keyword[else] : identifier[sys] . identifier[exit] ( literal[int] )
def delete(stack, region, profile): """ Delete the given CloudFormation stack. """ ini_data = {} environment = {} environment['stack_name'] = stack if region: environment['region'] = region # depends on [control=['if'], data=[]] else: environment['region'] = find_myself() if profile: environment['profile'] = profile # depends on [control=['if'], data=[]] ini_data['environment'] = environment if start_smash(ini_data): sys.exit(0) # depends on [control=['if'], data=[]] else: sys.exit(1)
def send(self, message, timeout=None, tries=3, future=None, callback=None, raw=False): ''' Return a future which will be completed when the message has a response ''' if future is None: future = tornado.concurrent.Future() future.tries = tries future.attempts = 0 future.timeout = timeout # if a future wasn't passed in, we need to serialize the message message = self.serial.dumps(message) if callback is not None: def handle_future(future): response = future.result() self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) # Add this future to the mapping self.send_future_map[message] = future if self.opts.get('detect_mode') is True: timeout = 1 if timeout is not None: send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message) self.send_timeout_map[message] = send_timeout if not self.send_queue: self.io_loop.spawn_callback(self._internal_send_recv) self.send_queue.append(message) return future
def function[send, parameter[self, message, timeout, tries, future, callback, raw]]: constant[ Return a future which will be completed when the message has a response ] if compare[name[future] is constant[None]] begin[:] variable[future] assign[=] call[name[tornado].concurrent.Future, parameter[]] name[future].tries assign[=] name[tries] name[future].attempts assign[=] constant[0] name[future].timeout assign[=] name[timeout] variable[message] assign[=] call[name[self].serial.dumps, parameter[name[message]]] if compare[name[callback] is_not constant[None]] begin[:] def function[handle_future, parameter[future]]: variable[response] assign[=] call[name[future].result, parameter[]] call[name[self].io_loop.add_callback, parameter[name[callback], name[response]]] call[name[future].add_done_callback, parameter[name[handle_future]]] call[name[self].send_future_map][name[message]] assign[=] name[future] if compare[call[name[self].opts.get, parameter[constant[detect_mode]]] is constant[True]] begin[:] variable[timeout] assign[=] constant[1] if compare[name[timeout] is_not constant[None]] begin[:] variable[send_timeout] assign[=] call[name[self].io_loop.call_later, parameter[name[timeout], name[self].timeout_message, name[message]]] call[name[self].send_timeout_map][name[message]] assign[=] name[send_timeout] if <ast.UnaryOp object at 0x7da20c6c4d00> begin[:] call[name[self].io_loop.spawn_callback, parameter[name[self]._internal_send_recv]] call[name[self].send_queue.append, parameter[name[message]]] return[name[future]]
keyword[def] identifier[send] ( identifier[self] , identifier[message] , identifier[timeout] = keyword[None] , identifier[tries] = literal[int] , identifier[future] = keyword[None] , identifier[callback] = keyword[None] , identifier[raw] = keyword[False] ): literal[string] keyword[if] identifier[future] keyword[is] keyword[None] : identifier[future] = identifier[tornado] . identifier[concurrent] . identifier[Future] () identifier[future] . identifier[tries] = identifier[tries] identifier[future] . identifier[attempts] = literal[int] identifier[future] . identifier[timeout] = identifier[timeout] identifier[message] = identifier[self] . identifier[serial] . identifier[dumps] ( identifier[message] ) keyword[if] identifier[callback] keyword[is] keyword[not] keyword[None] : keyword[def] identifier[handle_future] ( identifier[future] ): identifier[response] = identifier[future] . identifier[result] () identifier[self] . identifier[io_loop] . identifier[add_callback] ( identifier[callback] , identifier[response] ) identifier[future] . identifier[add_done_callback] ( identifier[handle_future] ) identifier[self] . identifier[send_future_map] [ identifier[message] ]= identifier[future] keyword[if] identifier[self] . identifier[opts] . identifier[get] ( literal[string] ) keyword[is] keyword[True] : identifier[timeout] = literal[int] keyword[if] identifier[timeout] keyword[is] keyword[not] keyword[None] : identifier[send_timeout] = identifier[self] . identifier[io_loop] . identifier[call_later] ( identifier[timeout] , identifier[self] . identifier[timeout_message] , identifier[message] ) identifier[self] . identifier[send_timeout_map] [ identifier[message] ]= identifier[send_timeout] keyword[if] keyword[not] identifier[self] . identifier[send_queue] : identifier[self] . identifier[io_loop] . identifier[spawn_callback] ( identifier[self] . identifier[_internal_send_recv] ) identifier[self] . identifier[send_queue] . identifier[append] ( identifier[message] ) keyword[return] identifier[future]
def send(self, message, timeout=None, tries=3, future=None, callback=None, raw=False): """ Return a future which will be completed when the message has a response """ if future is None: future = tornado.concurrent.Future() future.tries = tries future.attempts = 0 future.timeout = timeout # if a future wasn't passed in, we need to serialize the message message = self.serial.dumps(message) # depends on [control=['if'], data=['future']] if callback is not None: def handle_future(future): response = future.result() self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) # depends on [control=['if'], data=['callback']] # Add this future to the mapping self.send_future_map[message] = future if self.opts.get('detect_mode') is True: timeout = 1 # depends on [control=['if'], data=[]] if timeout is not None: send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message) self.send_timeout_map[message] = send_timeout # depends on [control=['if'], data=['timeout']] if not self.send_queue: self.io_loop.spawn_callback(self._internal_send_recv) # depends on [control=['if'], data=[]] self.send_queue.append(message) return future
def custom_get(self, outer_id, session, fields=[]): '''taobao.skus.custom.get 根据外部ID取商品SKU 跟据卖家设定的Sku的外部id获取商品,如果一个outer_id对应多个Sku会返回所有符合条件的sku 这个Sku所属卖家从传入的session中获取,需要session绑定(注:iid标签里是num_iid的值,可以用作num_iid使用)''' request = TOPRequest('taobao.skus.custom.get') request['outer_id'] = outer_id if not fields: item = Item() fields = item.fields request['fields'] = fields self.create(self.execute(request, session)) return self.skus
def function[custom_get, parameter[self, outer_id, session, fields]]: constant[taobao.skus.custom.get 根据外部ID取商品SKU 跟据卖家设定的Sku的外部id获取商品,如果一个outer_id对应多个Sku会返回所有符合条件的sku 这个Sku所属卖家从传入的session中获取,需要session绑定(注:iid标签里是num_iid的值,可以用作num_iid使用)] variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.skus.custom.get]]] call[name[request]][constant[outer_id]] assign[=] name[outer_id] if <ast.UnaryOp object at 0x7da1b253fc10> begin[:] variable[item] assign[=] call[name[Item], parameter[]] variable[fields] assign[=] name[item].fields call[name[request]][constant[fields]] assign[=] name[fields] call[name[self].create, parameter[call[name[self].execute, parameter[name[request], name[session]]]]] return[name[self].skus]
keyword[def] identifier[custom_get] ( identifier[self] , identifier[outer_id] , identifier[session] , identifier[fields] =[]): literal[string] identifier[request] = identifier[TOPRequest] ( literal[string] ) identifier[request] [ literal[string] ]= identifier[outer_id] keyword[if] keyword[not] identifier[fields] : identifier[item] = identifier[Item] () identifier[fields] = identifier[item] . identifier[fields] identifier[request] [ literal[string] ]= identifier[fields] identifier[self] . identifier[create] ( identifier[self] . identifier[execute] ( identifier[request] , identifier[session] )) keyword[return] identifier[self] . identifier[skus]
def custom_get(self, outer_id, session, fields=[]): """taobao.skus.custom.get 根据外部ID取商品SKU 跟据卖家设定的Sku的外部id获取商品,如果一个outer_id对应多个Sku会返回所有符合条件的sku 这个Sku所属卖家从传入的session中获取,需要session绑定(注:iid标签里是num_iid的值,可以用作num_iid使用)""" request = TOPRequest('taobao.skus.custom.get') request['outer_id'] = outer_id if not fields: item = Item() fields = item.fields # depends on [control=['if'], data=[]] request['fields'] = fields self.create(self.execute(request, session)) return self.skus
def modify_order_group(self, orderId, entry=None, target=None, stop=None, quantity=None): """Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders only) target: float new target limit price (for unfilled limit orders only) stop: float new stop limit price (for unfilled limit orders only) quantity : int the required quantity of the modified order """ return self.parent.modify_order_group(self, orderId=orderId, entry=entry, target=target, stop=stop, quantity=quantity)
def function[modify_order_group, parameter[self, orderId, entry, target, stop, quantity]]: constant[Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders only) target: float new target limit price (for unfilled limit orders only) stop: float new stop limit price (for unfilled limit orders only) quantity : int the required quantity of the modified order ] return[call[name[self].parent.modify_order_group, parameter[name[self]]]]
keyword[def] identifier[modify_order_group] ( identifier[self] , identifier[orderId] , identifier[entry] = keyword[None] , identifier[target] = keyword[None] , identifier[stop] = keyword[None] , identifier[quantity] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[parent] . identifier[modify_order_group] ( identifier[self] , identifier[orderId] = identifier[orderId] , identifier[entry] = identifier[entry] , identifier[target] = identifier[target] , identifier[stop] = identifier[stop] , identifier[quantity] = identifier[quantity] )
def modify_order_group(self, orderId, entry=None, target=None, stop=None, quantity=None): """Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders only) target: float new target limit price (for unfilled limit orders only) stop: float new stop limit price (for unfilled limit orders only) quantity : int the required quantity of the modified order """ return self.parent.modify_order_group(self, orderId=orderId, entry=entry, target=target, stop=stop, quantity=quantity)
async def on_raw_311(self, message): """ WHOIS user info. """ target, nickname, username, hostname, _, realname = message.params info = { 'username': username, 'hostname': hostname, 'realname': realname } self._sync_user(nickname, info) if nickname in self._pending['whois']: self._whois_info[nickname].update(info)
<ast.AsyncFunctionDef object at 0x7da18f721e40>
keyword[async] keyword[def] identifier[on_raw_311] ( identifier[self] , identifier[message] ): literal[string] identifier[target] , identifier[nickname] , identifier[username] , identifier[hostname] , identifier[_] , identifier[realname] = identifier[message] . identifier[params] identifier[info] ={ literal[string] : identifier[username] , literal[string] : identifier[hostname] , literal[string] : identifier[realname] } identifier[self] . identifier[_sync_user] ( identifier[nickname] , identifier[info] ) keyword[if] identifier[nickname] keyword[in] identifier[self] . identifier[_pending] [ literal[string] ]: identifier[self] . identifier[_whois_info] [ identifier[nickname] ]. identifier[update] ( identifier[info] )
async def on_raw_311(self, message): """ WHOIS user info. """ (target, nickname, username, hostname, _, realname) = message.params info = {'username': username, 'hostname': hostname, 'realname': realname} self._sync_user(nickname, info) if nickname in self._pending['whois']: self._whois_info[nickname].update(info) # depends on [control=['if'], data=['nickname']]
def create_dm_pkg(secret,username): ''' create ikuai dm message''' secret = tools.EncodeString(secret) username = tools.EncodeString(username) pkg_format = '>HHHH32sHH32s' pkg_vals = [ IK_RAD_PKG_VER, IK_RAD_PKG_AUTH, IK_RAD_PKG_USR_PWD_TAG, len(secret), secret.ljust(32,'\x00'), IK_RAD_PKG_CMD_ARGS_TAG, len(username), username.ljust(32,'\x00') ] return struct.pack(pkg_format,*pkg_vals)
def function[create_dm_pkg, parameter[secret, username]]: constant[ create ikuai dm message] variable[secret] assign[=] call[name[tools].EncodeString, parameter[name[secret]]] variable[username] assign[=] call[name[tools].EncodeString, parameter[name[username]]] variable[pkg_format] assign[=] constant[>HHHH32sHH32s] variable[pkg_vals] assign[=] list[[<ast.Name object at 0x7da2054a7a90>, <ast.Name object at 0x7da2054a7fd0>, <ast.Name object at 0x7da2054a4a60>, <ast.Call object at 0x7da2054a5ab0>, <ast.Call object at 0x7da2054a5a20>, <ast.Name object at 0x7da2054a7d60>, <ast.Call object at 0x7da2054a5c90>, <ast.Call object at 0x7da2054a7a00>]] return[call[name[struct].pack, parameter[name[pkg_format], <ast.Starred object at 0x7da18f09ca00>]]]
keyword[def] identifier[create_dm_pkg] ( identifier[secret] , identifier[username] ): literal[string] identifier[secret] = identifier[tools] . identifier[EncodeString] ( identifier[secret] ) identifier[username] = identifier[tools] . identifier[EncodeString] ( identifier[username] ) identifier[pkg_format] = literal[string] identifier[pkg_vals] =[ identifier[IK_RAD_PKG_VER] , identifier[IK_RAD_PKG_AUTH] , identifier[IK_RAD_PKG_USR_PWD_TAG] , identifier[len] ( identifier[secret] ), identifier[secret] . identifier[ljust] ( literal[int] , literal[string] ), identifier[IK_RAD_PKG_CMD_ARGS_TAG] , identifier[len] ( identifier[username] ), identifier[username] . identifier[ljust] ( literal[int] , literal[string] ) ] keyword[return] identifier[struct] . identifier[pack] ( identifier[pkg_format] ,* identifier[pkg_vals] )
def create_dm_pkg(secret, username): """ create ikuai dm message""" secret = tools.EncodeString(secret) username = tools.EncodeString(username) pkg_format = '>HHHH32sHH32s' pkg_vals = [IK_RAD_PKG_VER, IK_RAD_PKG_AUTH, IK_RAD_PKG_USR_PWD_TAG, len(secret), secret.ljust(32, '\x00'), IK_RAD_PKG_CMD_ARGS_TAG, len(username), username.ljust(32, '\x00')] return struct.pack(pkg_format, *pkg_vals)
def share_extension_with_host(self, publisher_name, extension_name, host_type, host_name): """ShareExtensionWithHost. [Preview API] :param str publisher_name: :param str extension_name: :param str host_type: :param str host_name: """ route_values = {} if publisher_name is not None: route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str') if extension_name is not None: route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str') if host_type is not None: route_values['hostType'] = self._serialize.url('host_type', host_type, 'str') if host_name is not None: route_values['hostName'] = self._serialize.url('host_name', host_name, 'str') self._send(http_method='POST', location_id='328a3af8-d124-46e9-9483-01690cd415b9', version='5.0-preview.1', route_values=route_values)
def function[share_extension_with_host, parameter[self, publisher_name, extension_name, host_type, host_name]]: constant[ShareExtensionWithHost. [Preview API] :param str publisher_name: :param str extension_name: :param str host_type: :param str host_name: ] variable[route_values] assign[=] dictionary[[], []] if compare[name[publisher_name] is_not constant[None]] begin[:] call[name[route_values]][constant[publisherName]] assign[=] call[name[self]._serialize.url, parameter[constant[publisher_name], name[publisher_name], constant[str]]] if compare[name[extension_name] is_not constant[None]] begin[:] call[name[route_values]][constant[extensionName]] assign[=] call[name[self]._serialize.url, parameter[constant[extension_name], name[extension_name], constant[str]]] if compare[name[host_type] is_not constant[None]] begin[:] call[name[route_values]][constant[hostType]] assign[=] call[name[self]._serialize.url, parameter[constant[host_type], name[host_type], constant[str]]] if compare[name[host_name] is_not constant[None]] begin[:] call[name[route_values]][constant[hostName]] assign[=] call[name[self]._serialize.url, parameter[constant[host_name], name[host_name], constant[str]]] call[name[self]._send, parameter[]]
keyword[def] identifier[share_extension_with_host] ( identifier[self] , identifier[publisher_name] , identifier[extension_name] , identifier[host_type] , identifier[host_name] ): literal[string] identifier[route_values] ={} keyword[if] identifier[publisher_name] keyword[is] keyword[not] keyword[None] : identifier[route_values] [ literal[string] ]= identifier[self] . identifier[_serialize] . identifier[url] ( literal[string] , identifier[publisher_name] , literal[string] ) keyword[if] identifier[extension_name] keyword[is] keyword[not] keyword[None] : identifier[route_values] [ literal[string] ]= identifier[self] . identifier[_serialize] . identifier[url] ( literal[string] , identifier[extension_name] , literal[string] ) keyword[if] identifier[host_type] keyword[is] keyword[not] keyword[None] : identifier[route_values] [ literal[string] ]= identifier[self] . identifier[_serialize] . identifier[url] ( literal[string] , identifier[host_type] , literal[string] ) keyword[if] identifier[host_name] keyword[is] keyword[not] keyword[None] : identifier[route_values] [ literal[string] ]= identifier[self] . identifier[_serialize] . identifier[url] ( literal[string] , identifier[host_name] , literal[string] ) identifier[self] . identifier[_send] ( identifier[http_method] = literal[string] , identifier[location_id] = literal[string] , identifier[version] = literal[string] , identifier[route_values] = identifier[route_values] )
def share_extension_with_host(self, publisher_name, extension_name, host_type, host_name): """ShareExtensionWithHost. [Preview API] :param str publisher_name: :param str extension_name: :param str host_type: :param str host_name: """ route_values = {} if publisher_name is not None: route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str') # depends on [control=['if'], data=['publisher_name']] if extension_name is not None: route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str') # depends on [control=['if'], data=['extension_name']] if host_type is not None: route_values['hostType'] = self._serialize.url('host_type', host_type, 'str') # depends on [control=['if'], data=['host_type']] if host_name is not None: route_values['hostName'] = self._serialize.url('host_name', host_name, 'str') # depends on [control=['if'], data=['host_name']] self._send(http_method='POST', location_id='328a3af8-d124-46e9-9483-01690cd415b9', version='5.0-preview.1', route_values=route_values)
def _create_session( self, alias, url, headers, cookies, auth, timeout, max_retries, backoff_factor, proxies, verify, debug, disable_warnings): """ Create Session: create a HTTP session to a server ``url`` Base url of the server ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of default headers ``cookies`` Dictionary of cookies ``auth`` List of username & password for HTTP Basic Auth ``timeout`` Connection timeout ``max_retries`` The maximum number of retries each connection should attempt. ``backoff_factor`` The pause between for each retry ``proxies`` Dictionary that contains proxy urls for HTTP and HTTPS communication ``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. ``debug`` Enable http verbosity option more information https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel ``disable_warnings`` Disable requests warning useful when you have large number of testcases """ self.builtin.log('Creating session: %s' % alias, 'DEBUG') s = session = requests.Session() s.headers.update(headers) s.auth = auth if auth else s.auth s.proxies = proxies if proxies else s.proxies try: max_retries = int(max_retries) except ValueError as err: raise ValueError("Error converting max_retries parameter: %s" % err) if max_retries > 0: http = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor)) https = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor)) # Replace the session's original adapters s.mount('http://', http) s.mount('https://', https) # Disable requests warnings, useful when you have large number of testcase # you will observe drastical changes in Robot log.html and output.xml files size if disable_warnings: logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests logging.getLogger().setLevel(logging.ERROR) requests_log = logging.getLogger("requests") requests_log.setLevel(logging.ERROR) requests_log.propagate = True if not verify: requests.packages.urllib3.disable_warnings() # verify can be a Boolean or a String if isinstance(verify, bool): s.verify = verify elif isinstance(verify, str) or isinstance(verify, unicode): if verify.lower() == 'true' or verify.lower() == 'false': s.verify = self.builtin.convert_to_boolean(verify) else: # String for CA_BUNDLE, not a Boolean String s.verify = verify else: # not a Boolean nor a String s.verify = verify # cant pass these into the Session anymore self.timeout = float(timeout) if timeout is not None else None self.cookies = cookies self.verify = verify if self.builtin.convert_to_boolean(verify) != True else None s.url = url # Enable http verbosity if int(debug) >= 1: self.debug = int(debug) httplib.HTTPConnection.debuglevel = self.debug self._cache.register(session, alias=alias) return session
def function[_create_session, parameter[self, alias, url, headers, cookies, auth, timeout, max_retries, backoff_factor, proxies, verify, debug, disable_warnings]]: constant[ Create Session: create a HTTP session to a server ``url`` Base url of the server ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of default headers ``cookies`` Dictionary of cookies ``auth`` List of username & password for HTTP Basic Auth ``timeout`` Connection timeout ``max_retries`` The maximum number of retries each connection should attempt. ``backoff_factor`` The pause between for each retry ``proxies`` Dictionary that contains proxy urls for HTTP and HTTPS communication ``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. ``debug`` Enable http verbosity option more information https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel ``disable_warnings`` Disable requests warning useful when you have large number of testcases ] call[name[self].builtin.log, parameter[binary_operation[constant[Creating session: %s] <ast.Mod object at 0x7da2590d6920> name[alias]], constant[DEBUG]]] variable[s] assign[=] call[name[requests].Session, parameter[]] call[name[s].headers.update, parameter[name[headers]]] name[s].auth assign[=] <ast.IfExp object at 0x7da18dc07880> name[s].proxies assign[=] <ast.IfExp object at 0x7da18dc07a30> <ast.Try object at 0x7da18dc07bb0> if compare[name[max_retries] greater[>] constant[0]] begin[:] variable[http] assign[=] call[name[requests].adapters.HTTPAdapter, parameter[]] variable[https] assign[=] call[name[requests].adapters.HTTPAdapter, parameter[]] call[name[s].mount, parameter[constant[http://], name[http]]] call[name[s].mount, parameter[constant[https://], name[https]]] if name[disable_warnings] begin[:] call[name[logging].basicConfig, parameter[]] call[call[name[logging].getLogger, parameter[]].setLevel, parameter[name[logging].ERROR]] variable[requests_log] assign[=] call[name[logging].getLogger, parameter[constant[requests]]] call[name[requests_log].setLevel, parameter[name[logging].ERROR]] name[requests_log].propagate assign[=] constant[True] if <ast.UnaryOp object at 0x7da18dc05330> begin[:] call[name[requests].packages.urllib3.disable_warnings, parameter[]] if call[name[isinstance], parameter[name[verify], name[bool]]] begin[:] name[s].verify assign[=] name[verify] name[self].timeout assign[=] <ast.IfExp object at 0x7da2045645b0> name[self].cookies assign[=] name[cookies] name[self].verify assign[=] <ast.IfExp object at 0x7da204566920> name[s].url assign[=] name[url] if compare[call[name[int], parameter[name[debug]]] greater_or_equal[>=] constant[1]] begin[:] name[self].debug assign[=] call[name[int], parameter[name[debug]]] name[httplib].HTTPConnection.debuglevel assign[=] name[self].debug call[name[self]._cache.register, parameter[name[session]]] return[name[session]]
keyword[def] identifier[_create_session] ( identifier[self] , identifier[alias] , identifier[url] , identifier[headers] , identifier[cookies] , identifier[auth] , identifier[timeout] , identifier[max_retries] , identifier[backoff_factor] , identifier[proxies] , identifier[verify] , identifier[debug] , identifier[disable_warnings] ): literal[string] identifier[self] . identifier[builtin] . identifier[log] ( literal[string] % identifier[alias] , literal[string] ) identifier[s] = identifier[session] = identifier[requests] . identifier[Session] () identifier[s] . identifier[headers] . identifier[update] ( identifier[headers] ) identifier[s] . identifier[auth] = identifier[auth] keyword[if] identifier[auth] keyword[else] identifier[s] . identifier[auth] identifier[s] . identifier[proxies] = identifier[proxies] keyword[if] identifier[proxies] keyword[else] identifier[s] . identifier[proxies] keyword[try] : identifier[max_retries] = identifier[int] ( identifier[max_retries] ) keyword[except] identifier[ValueError] keyword[as] identifier[err] : keyword[raise] identifier[ValueError] ( literal[string] % identifier[err] ) keyword[if] identifier[max_retries] > literal[int] : identifier[http] = identifier[requests] . identifier[adapters] . identifier[HTTPAdapter] ( identifier[max_retries] = identifier[Retry] ( identifier[total] = identifier[max_retries] , identifier[backoff_factor] = identifier[backoff_factor] )) identifier[https] = identifier[requests] . identifier[adapters] . identifier[HTTPAdapter] ( identifier[max_retries] = identifier[Retry] ( identifier[total] = identifier[max_retries] , identifier[backoff_factor] = identifier[backoff_factor] )) identifier[s] . identifier[mount] ( literal[string] , identifier[http] ) identifier[s] . identifier[mount] ( literal[string] , identifier[https] ) keyword[if] identifier[disable_warnings] : identifier[logging] . identifier[basicConfig] () identifier[logging] . identifier[getLogger] (). identifier[setLevel] ( identifier[logging] . identifier[ERROR] ) identifier[requests_log] = identifier[logging] . identifier[getLogger] ( literal[string] ) identifier[requests_log] . identifier[setLevel] ( identifier[logging] . identifier[ERROR] ) identifier[requests_log] . identifier[propagate] = keyword[True] keyword[if] keyword[not] identifier[verify] : identifier[requests] . identifier[packages] . identifier[urllib3] . identifier[disable_warnings] () keyword[if] identifier[isinstance] ( identifier[verify] , identifier[bool] ): identifier[s] . identifier[verify] = identifier[verify] keyword[elif] identifier[isinstance] ( identifier[verify] , identifier[str] ) keyword[or] identifier[isinstance] ( identifier[verify] , identifier[unicode] ): keyword[if] identifier[verify] . identifier[lower] ()== literal[string] keyword[or] identifier[verify] . identifier[lower] ()== literal[string] : identifier[s] . identifier[verify] = identifier[self] . identifier[builtin] . identifier[convert_to_boolean] ( identifier[verify] ) keyword[else] : identifier[s] . identifier[verify] = identifier[verify] keyword[else] : identifier[s] . identifier[verify] = identifier[verify] identifier[self] . identifier[timeout] = identifier[float] ( identifier[timeout] ) keyword[if] identifier[timeout] keyword[is] keyword[not] keyword[None] keyword[else] keyword[None] identifier[self] . identifier[cookies] = identifier[cookies] identifier[self] . identifier[verify] = identifier[verify] keyword[if] identifier[self] . identifier[builtin] . identifier[convert_to_boolean] ( identifier[verify] )!= keyword[True] keyword[else] keyword[None] identifier[s] . identifier[url] = identifier[url] keyword[if] identifier[int] ( identifier[debug] )>= literal[int] : identifier[self] . identifier[debug] = identifier[int] ( identifier[debug] ) identifier[httplib] . identifier[HTTPConnection] . identifier[debuglevel] = identifier[self] . identifier[debug] identifier[self] . identifier[_cache] . identifier[register] ( identifier[session] , identifier[alias] = identifier[alias] ) keyword[return] identifier[session]
def _create_session(self, alias, url, headers, cookies, auth, timeout, max_retries, backoff_factor, proxies, verify, debug, disable_warnings): """ Create Session: create a HTTP session to a server ``url`` Base url of the server ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of default headers ``cookies`` Dictionary of cookies ``auth`` List of username & password for HTTP Basic Auth ``timeout`` Connection timeout ``max_retries`` The maximum number of retries each connection should attempt. ``backoff_factor`` The pause between for each retry ``proxies`` Dictionary that contains proxy urls for HTTP and HTTPS communication ``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. ``debug`` Enable http verbosity option more information https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel ``disable_warnings`` Disable requests warning useful when you have large number of testcases """ self.builtin.log('Creating session: %s' % alias, 'DEBUG') s = session = requests.Session() s.headers.update(headers) s.auth = auth if auth else s.auth s.proxies = proxies if proxies else s.proxies try: max_retries = int(max_retries) # depends on [control=['try'], data=[]] except ValueError as err: raise ValueError('Error converting max_retries parameter: %s' % err) # depends on [control=['except'], data=['err']] if max_retries > 0: http = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor)) https = requests.adapters.HTTPAdapter(max_retries=Retry(total=max_retries, backoff_factor=backoff_factor)) # Replace the session's original adapters s.mount('http://', http) s.mount('https://', https) # depends on [control=['if'], data=['max_retries']] # Disable requests warnings, useful when you have large number of testcase # you will observe drastical changes in Robot log.html and output.xml files size if disable_warnings: logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests logging.getLogger().setLevel(logging.ERROR) requests_log = logging.getLogger('requests') requests_log.setLevel(logging.ERROR) requests_log.propagate = True if not verify: requests.packages.urllib3.disable_warnings() # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # verify can be a Boolean or a String if isinstance(verify, bool): s.verify = verify # depends on [control=['if'], data=[]] elif isinstance(verify, str) or isinstance(verify, unicode): if verify.lower() == 'true' or verify.lower() == 'false': s.verify = self.builtin.convert_to_boolean(verify) # depends on [control=['if'], data=[]] else: # String for CA_BUNDLE, not a Boolean String s.verify = verify # depends on [control=['if'], data=[]] else: # not a Boolean nor a String s.verify = verify # cant pass these into the Session anymore self.timeout = float(timeout) if timeout is not None else None self.cookies = cookies self.verify = verify if self.builtin.convert_to_boolean(verify) != True else None s.url = url # Enable http verbosity if int(debug) >= 1: self.debug = int(debug) httplib.HTTPConnection.debuglevel = self.debug # depends on [control=['if'], data=[]] self._cache.register(session, alias=alias) return session
def renderfile(filename, options=None, templatePaths=None, default='', silent=False): """ Renders a file to text using the mako template system. To learn more about mako and its usage, see [[www.makotemplates.org]] :return <str> formatted text """ if not mako: logger.debug('mako is not installed') return default if not mako: logger.debug('mako is not installed.') return default if templatePaths is None: templatePaths = [] # use the default mako templates basepath = os.environ.get('MAKO_TEMPLATEPATH', '') if basepath: basetempls = basepath.split(os.path.pathsep) else: basetempls = [] templatePaths += basetempls # include the root path templatePaths.insert(0, os.path.dirname(filename)) templatePaths = map(lambda x: x.replace('\\', '/'), templatePaths) # update the default options scope = dict(os.environ) scope['projex_text'] = projex.text scope['date'] = date scope['datetime'] = datetime scope.update(_macros) scope.update(os.environ) if options is not None: scope.update(options) old_env_path = os.environ.get('MAKO_TEMPLATEPATH', '') os.environ['MAKO_TEMPLATEPATH'] = os.path.pathsep.join(templatePaths) logger.debug('rendering mako file: %s', filename) if templatePaths: lookup = mako.lookup.TemplateLookup(directories=templatePaths) templ = mako.template.Template(filename=filename, lookup=lookup) else: templ = mako.template.Template(filename=filename) try: output = templ.render(**scope) except StandardError: output = default if not silent: logger.exception('Error rendering mako text') os.environ['MAKO_TEMPLATEPATH'] = old_env_path return output
def function[renderfile, parameter[filename, options, templatePaths, default, silent]]: constant[ Renders a file to text using the mako template system. To learn more about mako and its usage, see [[www.makotemplates.org]] :return <str> formatted text ] if <ast.UnaryOp object at 0x7da1b28b0790> begin[:] call[name[logger].debug, parameter[constant[mako is not installed]]] return[name[default]] if <ast.UnaryOp object at 0x7da1b28b3f40> begin[:] call[name[logger].debug, parameter[constant[mako is not installed.]]] return[name[default]] if compare[name[templatePaths] is constant[None]] begin[:] variable[templatePaths] assign[=] list[[]] variable[basepath] assign[=] call[name[os].environ.get, parameter[constant[MAKO_TEMPLATEPATH], constant[]]] if name[basepath] begin[:] variable[basetempls] assign[=] call[name[basepath].split, parameter[name[os].path.pathsep]] <ast.AugAssign object at 0x7da1b28b3fd0> call[name[templatePaths].insert, parameter[constant[0], call[name[os].path.dirname, parameter[name[filename]]]]] variable[templatePaths] assign[=] call[name[map], parameter[<ast.Lambda object at 0x7da1b28b1000>, name[templatePaths]]] variable[scope] assign[=] call[name[dict], parameter[name[os].environ]] call[name[scope]][constant[projex_text]] assign[=] name[projex].text call[name[scope]][constant[date]] assign[=] name[date] call[name[scope]][constant[datetime]] assign[=] name[datetime] call[name[scope].update, parameter[name[_macros]]] call[name[scope].update, parameter[name[os].environ]] if compare[name[options] is_not constant[None]] begin[:] call[name[scope].update, parameter[name[options]]] variable[old_env_path] assign[=] call[name[os].environ.get, parameter[constant[MAKO_TEMPLATEPATH], constant[]]] call[name[os].environ][constant[MAKO_TEMPLATEPATH]] assign[=] call[name[os].path.pathsep.join, parameter[name[templatePaths]]] call[name[logger].debug, parameter[constant[rendering mako file: %s], name[filename]]] if name[templatePaths] begin[:] variable[lookup] assign[=] call[name[mako].lookup.TemplateLookup, parameter[]] variable[templ] assign[=] call[name[mako].template.Template, parameter[]] <ast.Try object at 0x7da1b2886650> call[name[os].environ][constant[MAKO_TEMPLATEPATH]] assign[=] name[old_env_path] return[name[output]]
keyword[def] identifier[renderfile] ( identifier[filename] , identifier[options] = keyword[None] , identifier[templatePaths] = keyword[None] , identifier[default] = literal[string] , identifier[silent] = keyword[False] ): literal[string] keyword[if] keyword[not] identifier[mako] : identifier[logger] . identifier[debug] ( literal[string] ) keyword[return] identifier[default] keyword[if] keyword[not] identifier[mako] : identifier[logger] . identifier[debug] ( literal[string] ) keyword[return] identifier[default] keyword[if] identifier[templatePaths] keyword[is] keyword[None] : identifier[templatePaths] =[] identifier[basepath] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ) keyword[if] identifier[basepath] : identifier[basetempls] = identifier[basepath] . identifier[split] ( identifier[os] . identifier[path] . identifier[pathsep] ) keyword[else] : identifier[basetempls] =[] identifier[templatePaths] += identifier[basetempls] identifier[templatePaths] . identifier[insert] ( literal[int] , identifier[os] . identifier[path] . identifier[dirname] ( identifier[filename] )) identifier[templatePaths] = identifier[map] ( keyword[lambda] identifier[x] : identifier[x] . identifier[replace] ( literal[string] , literal[string] ), identifier[templatePaths] ) identifier[scope] = identifier[dict] ( identifier[os] . identifier[environ] ) identifier[scope] [ literal[string] ]= identifier[projex] . identifier[text] identifier[scope] [ literal[string] ]= identifier[date] identifier[scope] [ literal[string] ]= identifier[datetime] identifier[scope] . identifier[update] ( identifier[_macros] ) identifier[scope] . identifier[update] ( identifier[os] . identifier[environ] ) keyword[if] identifier[options] keyword[is] keyword[not] keyword[None] : identifier[scope] . identifier[update] ( identifier[options] ) identifier[old_env_path] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ) identifier[os] . identifier[environ] [ literal[string] ]= identifier[os] . identifier[path] . identifier[pathsep] . identifier[join] ( identifier[templatePaths] ) identifier[logger] . identifier[debug] ( literal[string] , identifier[filename] ) keyword[if] identifier[templatePaths] : identifier[lookup] = identifier[mako] . identifier[lookup] . identifier[TemplateLookup] ( identifier[directories] = identifier[templatePaths] ) identifier[templ] = identifier[mako] . identifier[template] . identifier[Template] ( identifier[filename] = identifier[filename] , identifier[lookup] = identifier[lookup] ) keyword[else] : identifier[templ] = identifier[mako] . identifier[template] . identifier[Template] ( identifier[filename] = identifier[filename] ) keyword[try] : identifier[output] = identifier[templ] . identifier[render] (** identifier[scope] ) keyword[except] identifier[StandardError] : identifier[output] = identifier[default] keyword[if] keyword[not] identifier[silent] : identifier[logger] . identifier[exception] ( literal[string] ) identifier[os] . identifier[environ] [ literal[string] ]= identifier[old_env_path] keyword[return] identifier[output]
def renderfile(filename, options=None, templatePaths=None, default='', silent=False): """ Renders a file to text using the mako template system. To learn more about mako and its usage, see [[www.makotemplates.org]] :return <str> formatted text """ if not mako: logger.debug('mako is not installed') return default # depends on [control=['if'], data=[]] if not mako: logger.debug('mako is not installed.') return default # depends on [control=['if'], data=[]] if templatePaths is None: templatePaths = [] # depends on [control=['if'], data=['templatePaths']] # use the default mako templates basepath = os.environ.get('MAKO_TEMPLATEPATH', '') if basepath: basetempls = basepath.split(os.path.pathsep) # depends on [control=['if'], data=[]] else: basetempls = [] templatePaths += basetempls # include the root path templatePaths.insert(0, os.path.dirname(filename)) templatePaths = map(lambda x: x.replace('\\', '/'), templatePaths) # update the default options scope = dict(os.environ) scope['projex_text'] = projex.text scope['date'] = date scope['datetime'] = datetime scope.update(_macros) scope.update(os.environ) if options is not None: scope.update(options) # depends on [control=['if'], data=['options']] old_env_path = os.environ.get('MAKO_TEMPLATEPATH', '') os.environ['MAKO_TEMPLATEPATH'] = os.path.pathsep.join(templatePaths) logger.debug('rendering mako file: %s', filename) if templatePaths: lookup = mako.lookup.TemplateLookup(directories=templatePaths) templ = mako.template.Template(filename=filename, lookup=lookup) # depends on [control=['if'], data=[]] else: templ = mako.template.Template(filename=filename) try: output = templ.render(**scope) # depends on [control=['try'], data=[]] except StandardError: output = default if not silent: logger.exception('Error rendering mako text') # depends on [control=['if'], data=[]] # depends on [control=['except'], data=[]] os.environ['MAKO_TEMPLATEPATH'] = old_env_path return output
def _stacklevel_above_module(mod_name): """ Return the stack level (with 1 = caller of this function) of the first caller that is not defined in the specified module (e.g. "pywbem.cim_obj"). The returned stack level can be used directly by the caller of this function as an argument for the stacklevel parameter of warnings.warn(). """ stacklevel = 2 # start with caller of our caller frame = inspect.stack()[stacklevel][0] # stack() level is 0-based while True: if frame.f_globals.get('__name__', None) != mod_name: break stacklevel += 1 frame = frame.f_back del frame return stacklevel
def function[_stacklevel_above_module, parameter[mod_name]]: constant[ Return the stack level (with 1 = caller of this function) of the first caller that is not defined in the specified module (e.g. "pywbem.cim_obj"). The returned stack level can be used directly by the caller of this function as an argument for the stacklevel parameter of warnings.warn(). ] variable[stacklevel] assign[=] constant[2] variable[frame] assign[=] call[call[call[name[inspect].stack, parameter[]]][name[stacklevel]]][constant[0]] while constant[True] begin[:] if compare[call[name[frame].f_globals.get, parameter[constant[__name__], constant[None]]] not_equal[!=] name[mod_name]] begin[:] break <ast.AugAssign object at 0x7da18c4cd6c0> variable[frame] assign[=] name[frame].f_back <ast.Delete object at 0x7da18c4ce6b0> return[name[stacklevel]]
keyword[def] identifier[_stacklevel_above_module] ( identifier[mod_name] ): literal[string] identifier[stacklevel] = literal[int] identifier[frame] = identifier[inspect] . identifier[stack] ()[ identifier[stacklevel] ][ literal[int] ] keyword[while] keyword[True] : keyword[if] identifier[frame] . identifier[f_globals] . identifier[get] ( literal[string] , keyword[None] )!= identifier[mod_name] : keyword[break] identifier[stacklevel] += literal[int] identifier[frame] = identifier[frame] . identifier[f_back] keyword[del] identifier[frame] keyword[return] identifier[stacklevel]
def _stacklevel_above_module(mod_name): """ Return the stack level (with 1 = caller of this function) of the first caller that is not defined in the specified module (e.g. "pywbem.cim_obj"). The returned stack level can be used directly by the caller of this function as an argument for the stacklevel parameter of warnings.warn(). """ stacklevel = 2 # start with caller of our caller frame = inspect.stack()[stacklevel][0] # stack() level is 0-based while True: if frame.f_globals.get('__name__', None) != mod_name: break # depends on [control=['if'], data=[]] stacklevel += 1 frame = frame.f_back # depends on [control=['while'], data=[]] del frame return stacklevel
def write(self, data): """ write data on the OUT endpoint associated to the HID interface """ # report_size = 64 # if self.ep_out: # report_size = self.ep_out.wMaxPacketSize # # for _ in range(report_size - len(data)): # data.append(0) self.read_sem.release() if not self.ep_out: bmRequestType = 0x21 #Host to device request of type Class of Recipient Interface bmRequest = 0x09 #Set_REPORT (HID class-specific request for transferring data over EP0) wValue = 0x200 #Issuing an OUT report wIndex = self.intf_number #mBed Board interface number for HID self.dev.ctrl_transfer(bmRequestType, bmRequest, wValue, wIndex, data) return #raise ValueError('EP_OUT endpoint is NULL') self.ep_out.write(data) #logging.debug('sent: %s', data) return
def function[write, parameter[self, data]]: constant[ write data on the OUT endpoint associated to the HID interface ] call[name[self].read_sem.release, parameter[]] if <ast.UnaryOp object at 0x7da1b06a22f0> begin[:] variable[bmRequestType] assign[=] constant[33] variable[bmRequest] assign[=] constant[9] variable[wValue] assign[=] constant[512] variable[wIndex] assign[=] name[self].intf_number call[name[self].dev.ctrl_transfer, parameter[name[bmRequestType], name[bmRequest], name[wValue], name[wIndex], name[data]]] return[None] call[name[self].ep_out.write, parameter[name[data]]] return[None]
keyword[def] identifier[write] ( identifier[self] , identifier[data] ): literal[string] identifier[self] . identifier[read_sem] . identifier[release] () keyword[if] keyword[not] identifier[self] . identifier[ep_out] : identifier[bmRequestType] = literal[int] identifier[bmRequest] = literal[int] identifier[wValue] = literal[int] identifier[wIndex] = identifier[self] . identifier[intf_number] identifier[self] . identifier[dev] . identifier[ctrl_transfer] ( identifier[bmRequestType] , identifier[bmRequest] , identifier[wValue] , identifier[wIndex] , identifier[data] ) keyword[return] identifier[self] . identifier[ep_out] . identifier[write] ( identifier[data] ) keyword[return]
def write(self, data): """ write data on the OUT endpoint associated to the HID interface """ # report_size = 64 # if self.ep_out: # report_size = self.ep_out.wMaxPacketSize # # for _ in range(report_size - len(data)): # data.append(0) self.read_sem.release() if not self.ep_out: bmRequestType = 33 #Host to device request of type Class of Recipient Interface bmRequest = 9 #Set_REPORT (HID class-specific request for transferring data over EP0) wValue = 512 #Issuing an OUT report wIndex = self.intf_number #mBed Board interface number for HID self.dev.ctrl_transfer(bmRequestType, bmRequest, wValue, wIndex, data) return # depends on [control=['if'], data=[]] #raise ValueError('EP_OUT endpoint is NULL') self.ep_out.write(data) #logging.debug('sent: %s', data) return
def create_user(self, projects=None, tasks=None): """Create and return a new user :param projects: the projects for the user :type projects: list of :class:`jukeboxcore.djadapter.models.Project` :param tasks: the tasks for the user :type tasks: list of :class:`jukeboxcore.djadapter.models.Task` :returns: The created user or None :rtype: None | :class:`jukeboxcore.djadapter.models.User` :raises: None """ projects = projects or [] tasks = tasks or [] dialog = UserCreatorDialog(projects=projects, tasks=tasks, parent=self) dialog.exec_() user = dialog.user if user: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, self.users_model.root) return user
def function[create_user, parameter[self, projects, tasks]]: constant[Create and return a new user :param projects: the projects for the user :type projects: list of :class:`jukeboxcore.djadapter.models.Project` :param tasks: the tasks for the user :type tasks: list of :class:`jukeboxcore.djadapter.models.Task` :returns: The created user or None :rtype: None | :class:`jukeboxcore.djadapter.models.User` :raises: None ] variable[projects] assign[=] <ast.BoolOp object at 0x7da1b1438d60> variable[tasks] assign[=] <ast.BoolOp object at 0x7da1b1438be0> variable[dialog] assign[=] call[name[UserCreatorDialog], parameter[]] call[name[dialog].exec_, parameter[]] variable[user] assign[=] name[dialog].user if name[user] begin[:] variable[userdata] assign[=] call[name[djitemdata].UserItemData, parameter[name[user]]] call[name[treemodel].TreeItem, parameter[name[userdata], name[self].users_model.root]] return[name[user]]
keyword[def] identifier[create_user] ( identifier[self] , identifier[projects] = keyword[None] , identifier[tasks] = keyword[None] ): literal[string] identifier[projects] = identifier[projects] keyword[or] [] identifier[tasks] = identifier[tasks] keyword[or] [] identifier[dialog] = identifier[UserCreatorDialog] ( identifier[projects] = identifier[projects] , identifier[tasks] = identifier[tasks] , identifier[parent] = identifier[self] ) identifier[dialog] . identifier[exec_] () identifier[user] = identifier[dialog] . identifier[user] keyword[if] identifier[user] : identifier[userdata] = identifier[djitemdata] . identifier[UserItemData] ( identifier[user] ) identifier[treemodel] . identifier[TreeItem] ( identifier[userdata] , identifier[self] . identifier[users_model] . identifier[root] ) keyword[return] identifier[user]
def create_user(self, projects=None, tasks=None): """Create and return a new user :param projects: the projects for the user :type projects: list of :class:`jukeboxcore.djadapter.models.Project` :param tasks: the tasks for the user :type tasks: list of :class:`jukeboxcore.djadapter.models.Task` :returns: The created user or None :rtype: None | :class:`jukeboxcore.djadapter.models.User` :raises: None """ projects = projects or [] tasks = tasks or [] dialog = UserCreatorDialog(projects=projects, tasks=tasks, parent=self) dialog.exec_() user = dialog.user if user: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, self.users_model.root) # depends on [control=['if'], data=[]] return user
def MatrixDiagPart(a): """ Batched diag op that returns only the diagonal elements. """ r = np.zeros(a.shape[:-2] + (min(a.shape[-2:]),)) for coord in np.ndindex(a.shape[:-2]): pos = coord + (Ellipsis,) r[pos] = np.diagonal(a[pos]) return r,
def function[MatrixDiagPart, parameter[a]]: constant[ Batched diag op that returns only the diagonal elements. ] variable[r] assign[=] call[name[np].zeros, parameter[binary_operation[call[name[a].shape][<ast.Slice object at 0x7da1b0505f00>] + tuple[[<ast.Call object at 0x7da1b05056f0>]]]]] for taget[name[coord]] in starred[call[name[np].ndindex, parameter[call[name[a].shape][<ast.Slice object at 0x7da1b0505d20>]]]] begin[:] variable[pos] assign[=] binary_operation[name[coord] + tuple[[<ast.Name object at 0x7da1b0505c60>]]] call[name[r]][name[pos]] assign[=] call[name[np].diagonal, parameter[call[name[a]][name[pos]]]] return[tuple[[<ast.Name object at 0x7da1b05064a0>]]]
keyword[def] identifier[MatrixDiagPart] ( identifier[a] ): literal[string] identifier[r] = identifier[np] . identifier[zeros] ( identifier[a] . identifier[shape] [:- literal[int] ]+( identifier[min] ( identifier[a] . identifier[shape] [- literal[int] :]),)) keyword[for] identifier[coord] keyword[in] identifier[np] . identifier[ndindex] ( identifier[a] . identifier[shape] [:- literal[int] ]): identifier[pos] = identifier[coord] +( identifier[Ellipsis] ,) identifier[r] [ identifier[pos] ]= identifier[np] . identifier[diagonal] ( identifier[a] [ identifier[pos] ]) keyword[return] identifier[r] ,
def MatrixDiagPart(a): """ Batched diag op that returns only the diagonal elements. """ r = np.zeros(a.shape[:-2] + (min(a.shape[-2:]),)) for coord in np.ndindex(a.shape[:-2]): pos = coord + (Ellipsis,) r[pos] = np.diagonal(a[pos]) # depends on [control=['for'], data=['coord']] return (r,)
def venv_update( venv=DEFAULT_OPTION_VALUES['venv='], install=DEFAULT_OPTION_VALUES['install='], pip_command=DEFAULT_OPTION_VALUES['pip-command='], bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], ): """we have an arbitrary python interpreter active, (possibly) outside the virtualenv we want. make a fresh venv at the right spot, make sure it has pip-faster, and use it """ # SMELL: mutable argument as return value class return_values(object): venv_path = None try: ensure_virtualenv(venv, return_values) if return_values.venv_path is None: return # invariant: the final virtualenv exists, with the right python version raise_on_failure(lambda: pip_faster(return_values.venv_path, pip_command, install, bootstrap_deps)) except BaseException: mark_venv_invalid(return_values.venv_path) raise else: mark_venv_valid(return_values.venv_path)
def function[venv_update, parameter[venv, install, pip_command, bootstrap_deps]]: constant[we have an arbitrary python interpreter active, (possibly) outside the virtualenv we want. make a fresh venv at the right spot, make sure it has pip-faster, and use it ] class class[return_values, parameter[]] begin[:] variable[venv_path] assign[=] constant[None] <ast.Try object at 0x7da1b1296ce0>
keyword[def] identifier[venv_update] ( identifier[venv] = identifier[DEFAULT_OPTION_VALUES] [ literal[string] ], identifier[install] = identifier[DEFAULT_OPTION_VALUES] [ literal[string] ], identifier[pip_command] = identifier[DEFAULT_OPTION_VALUES] [ literal[string] ], identifier[bootstrap_deps] = identifier[DEFAULT_OPTION_VALUES] [ literal[string] ], ): literal[string] keyword[class] identifier[return_values] ( identifier[object] ): identifier[venv_path] = keyword[None] keyword[try] : identifier[ensure_virtualenv] ( identifier[venv] , identifier[return_values] ) keyword[if] identifier[return_values] . identifier[venv_path] keyword[is] keyword[None] : keyword[return] identifier[raise_on_failure] ( keyword[lambda] : identifier[pip_faster] ( identifier[return_values] . identifier[venv_path] , identifier[pip_command] , identifier[install] , identifier[bootstrap_deps] )) keyword[except] identifier[BaseException] : identifier[mark_venv_invalid] ( identifier[return_values] . identifier[venv_path] ) keyword[raise] keyword[else] : identifier[mark_venv_valid] ( identifier[return_values] . identifier[venv_path] )
def venv_update(venv=DEFAULT_OPTION_VALUES['venv='], install=DEFAULT_OPTION_VALUES['install='], pip_command=DEFAULT_OPTION_VALUES['pip-command='], bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps=']): """we have an arbitrary python interpreter active, (possibly) outside the virtualenv we want. make a fresh venv at the right spot, make sure it has pip-faster, and use it """ # SMELL: mutable argument as return value class return_values(object): venv_path = None try: ensure_virtualenv(venv, return_values) if return_values.venv_path is None: return # depends on [control=['if'], data=[]] # invariant: the final virtualenv exists, with the right python version raise_on_failure(lambda : pip_faster(return_values.venv_path, pip_command, install, bootstrap_deps)) # depends on [control=['try'], data=[]] except BaseException: mark_venv_invalid(return_values.venv_path) raise # depends on [control=['except'], data=[]] else: mark_venv_valid(return_values.venv_path)
def get_http_status_string(v): """Return HTTP response string, e.g. 204 -> ('204 No Content'). The return string always includes descriptive text, to satisfy Apache mod_dav. `v`: status code or DAVError """ code = get_http_status_code(v) try: return ERROR_DESCRIPTIONS[code] except KeyError: return "{} Status".format(code)
def function[get_http_status_string, parameter[v]]: constant[Return HTTP response string, e.g. 204 -> ('204 No Content'). The return string always includes descriptive text, to satisfy Apache mod_dav. `v`: status code or DAVError ] variable[code] assign[=] call[name[get_http_status_code], parameter[name[v]]] <ast.Try object at 0x7da1b01fb1f0>
keyword[def] identifier[get_http_status_string] ( identifier[v] ): literal[string] identifier[code] = identifier[get_http_status_code] ( identifier[v] ) keyword[try] : keyword[return] identifier[ERROR_DESCRIPTIONS] [ identifier[code] ] keyword[except] identifier[KeyError] : keyword[return] literal[string] . identifier[format] ( identifier[code] )
def get_http_status_string(v): """Return HTTP response string, e.g. 204 -> ('204 No Content'). The return string always includes descriptive text, to satisfy Apache mod_dav. `v`: status code or DAVError """ code = get_http_status_code(v) try: return ERROR_DESCRIPTIONS[code] # depends on [control=['try'], data=[]] except KeyError: return '{} Status'.format(code) # depends on [control=['except'], data=[]]
def mcus(): """MCU list.""" ls = [] for h in hwpack_names(): for b in board_names(h): ls += [mcu(b, h)] ls = sorted(list(set(ls))) return ls
def function[mcus, parameter[]]: constant[MCU list.] variable[ls] assign[=] list[[]] for taget[name[h]] in starred[call[name[hwpack_names], parameter[]]] begin[:] for taget[name[b]] in starred[call[name[board_names], parameter[name[h]]]] begin[:] <ast.AugAssign object at 0x7da1b2872b90> variable[ls] assign[=] call[name[sorted], parameter[call[name[list], parameter[call[name[set], parameter[name[ls]]]]]]] return[name[ls]]
keyword[def] identifier[mcus] (): literal[string] identifier[ls] =[] keyword[for] identifier[h] keyword[in] identifier[hwpack_names] (): keyword[for] identifier[b] keyword[in] identifier[board_names] ( identifier[h] ): identifier[ls] +=[ identifier[mcu] ( identifier[b] , identifier[h] )] identifier[ls] = identifier[sorted] ( identifier[list] ( identifier[set] ( identifier[ls] ))) keyword[return] identifier[ls]
def mcus(): """MCU list.""" ls = [] for h in hwpack_names(): for b in board_names(h): ls += [mcu(b, h)] # depends on [control=['for'], data=['b']] # depends on [control=['for'], data=['h']] ls = sorted(list(set(ls))) return ls
def remove_env(environment): """ Remove an environment from the configuration. """ if not environment: print("You need to supply an environment name") return parser = read_config() if not parser.remove_section(environment): print("Unknown environment type '%s'" % environment) return write_config(parser) print("Removed environment '%s'" % environment)
def function[remove_env, parameter[environment]]: constant[ Remove an environment from the configuration. ] if <ast.UnaryOp object at 0x7da18f720100> begin[:] call[name[print], parameter[constant[You need to supply an environment name]]] return[None] variable[parser] assign[=] call[name[read_config], parameter[]] if <ast.UnaryOp object at 0x7da18f58dfc0> begin[:] call[name[print], parameter[binary_operation[constant[Unknown environment type '%s'] <ast.Mod object at 0x7da2590d6920> name[environment]]]] return[None] call[name[write_config], parameter[name[parser]]] call[name[print], parameter[binary_operation[constant[Removed environment '%s'] <ast.Mod object at 0x7da2590d6920> name[environment]]]]
keyword[def] identifier[remove_env] ( identifier[environment] ): literal[string] keyword[if] keyword[not] identifier[environment] : identifier[print] ( literal[string] ) keyword[return] identifier[parser] = identifier[read_config] () keyword[if] keyword[not] identifier[parser] . identifier[remove_section] ( identifier[environment] ): identifier[print] ( literal[string] % identifier[environment] ) keyword[return] identifier[write_config] ( identifier[parser] ) identifier[print] ( literal[string] % identifier[environment] )
def remove_env(environment): """ Remove an environment from the configuration. """ if not environment: print('You need to supply an environment name') return # depends on [control=['if'], data=[]] parser = read_config() if not parser.remove_section(environment): print("Unknown environment type '%s'" % environment) return # depends on [control=['if'], data=[]] write_config(parser) print("Removed environment '%s'" % environment)
def tableToTsv(self, model): """ Takes a model class and attempts to create a table in TSV format that can be imported into a spreadsheet program. """ first = True for item in model.select(): if first: header = "".join( ["{}\t".format(x) for x in model._meta.fields.keys()]) print(header) first = False row = "".join( ["{}\t".format( getattr(item, key)) for key in model._meta.fields.keys()]) print(row)
def function[tableToTsv, parameter[self, model]]: constant[ Takes a model class and attempts to create a table in TSV format that can be imported into a spreadsheet program. ] variable[first] assign[=] constant[True] for taget[name[item]] in starred[call[name[model].select, parameter[]]] begin[:] if name[first] begin[:] variable[header] assign[=] call[constant[].join, parameter[<ast.ListComp object at 0x7da18f58dc30>]] call[name[print], parameter[name[header]]] variable[first] assign[=] constant[False] variable[row] assign[=] call[constant[].join, parameter[<ast.ListComp object at 0x7da1b26aecb0>]] call[name[print], parameter[name[row]]]
keyword[def] identifier[tableToTsv] ( identifier[self] , identifier[model] ): literal[string] identifier[first] = keyword[True] keyword[for] identifier[item] keyword[in] identifier[model] . identifier[select] (): keyword[if] identifier[first] : identifier[header] = literal[string] . identifier[join] ( [ literal[string] . identifier[format] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[model] . identifier[_meta] . identifier[fields] . identifier[keys] ()]) identifier[print] ( identifier[header] ) identifier[first] = keyword[False] identifier[row] = literal[string] . identifier[join] ( [ literal[string] . identifier[format] ( identifier[getattr] ( identifier[item] , identifier[key] )) keyword[for] identifier[key] keyword[in] identifier[model] . identifier[_meta] . identifier[fields] . identifier[keys] ()]) identifier[print] ( identifier[row] )
def tableToTsv(self, model): """ Takes a model class and attempts to create a table in TSV format that can be imported into a spreadsheet program. """ first = True for item in model.select(): if first: header = ''.join(['{}\t'.format(x) for x in model._meta.fields.keys()]) print(header) first = False # depends on [control=['if'], data=[]] row = ''.join(['{}\t'.format(getattr(item, key)) for key in model._meta.fields.keys()]) print(row) # depends on [control=['for'], data=['item']]
def get_previous_dagrun(self, session=None): """The previous DagRun, if there is one""" return session.query(DagRun).filter( DagRun.dag_id == self.dag_id, DagRun.execution_date < self.execution_date ).order_by( DagRun.execution_date.desc() ).first()
def function[get_previous_dagrun, parameter[self, session]]: constant[The previous DagRun, if there is one] return[call[call[call[call[name[session].query, parameter[name[DagRun]]].filter, parameter[compare[name[DagRun].dag_id equal[==] name[self].dag_id], compare[name[DagRun].execution_date less[<] name[self].execution_date]]].order_by, parameter[call[name[DagRun].execution_date.desc, parameter[]]]].first, parameter[]]]
keyword[def] identifier[get_previous_dagrun] ( identifier[self] , identifier[session] = keyword[None] ): literal[string] keyword[return] identifier[session] . identifier[query] ( identifier[DagRun] ). identifier[filter] ( identifier[DagRun] . identifier[dag_id] == identifier[self] . identifier[dag_id] , identifier[DagRun] . identifier[execution_date] < identifier[self] . identifier[execution_date] ). identifier[order_by] ( identifier[DagRun] . identifier[execution_date] . identifier[desc] () ). identifier[first] ()
def get_previous_dagrun(self, session=None): """The previous DagRun, if there is one""" return session.query(DagRun).filter(DagRun.dag_id == self.dag_id, DagRun.execution_date < self.execution_date).order_by(DagRun.execution_date.desc()).first()
def setVisible(self, state): """ Sets whether or not this toolbar is visible. If shown, it will rebuild. :param state | <bool> """ super(XDockToolbar, self).setVisible(state) if state: self.rebuild() self.setCurrentAction(None)
def function[setVisible, parameter[self, state]]: constant[ Sets whether or not this toolbar is visible. If shown, it will rebuild. :param state | <bool> ] call[call[name[super], parameter[name[XDockToolbar], name[self]]].setVisible, parameter[name[state]]] if name[state] begin[:] call[name[self].rebuild, parameter[]] call[name[self].setCurrentAction, parameter[constant[None]]]
keyword[def] identifier[setVisible] ( identifier[self] , identifier[state] ): literal[string] identifier[super] ( identifier[XDockToolbar] , identifier[self] ). identifier[setVisible] ( identifier[state] ) keyword[if] identifier[state] : identifier[self] . identifier[rebuild] () identifier[self] . identifier[setCurrentAction] ( keyword[None] )
def setVisible(self, state): """ Sets whether or not this toolbar is visible. If shown, it will rebuild. :param state | <bool> """ super(XDockToolbar, self).setVisible(state) if state: self.rebuild() self.setCurrentAction(None) # depends on [control=['if'], data=[]]
def init(name, *args, **kwargs): """Instantiate a timeframe from the catalog. """ if name in _TIMEFRAME_CATALOG: if rapport.config.get_int("rapport", "verbosity") >= 2: print("Initialize timeframe {0}: {1} {2}".format(name, args, kwargs)) try: return _TIMEFRAME_CATALOG[name](*args, **kwargs) except ValueError as e: print("Failed to initialize timeframe {0}: {1}!".format(name, e), file=sys.stderr) else: print("Failed to initialize timeframe {0}: Not in catalog!".format(name), file=sys.stderr) sys.exit(1)
def function[init, parameter[name]]: constant[Instantiate a timeframe from the catalog. ] if compare[name[name] in name[_TIMEFRAME_CATALOG]] begin[:] if compare[call[name[rapport].config.get_int, parameter[constant[rapport], constant[verbosity]]] greater_or_equal[>=] constant[2]] begin[:] call[name[print], parameter[call[constant[Initialize timeframe {0}: {1} {2}].format, parameter[name[name], name[args], name[kwargs]]]]] <ast.Try object at 0x7da18f723ca0>
keyword[def] identifier[init] ( identifier[name] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[name] keyword[in] identifier[_TIMEFRAME_CATALOG] : keyword[if] identifier[rapport] . identifier[config] . identifier[get_int] ( literal[string] , literal[string] )>= literal[int] : identifier[print] ( literal[string] . identifier[format] ( identifier[name] , identifier[args] , identifier[kwargs] )) keyword[try] : keyword[return] identifier[_TIMEFRAME_CATALOG] [ identifier[name] ](* identifier[args] ,** identifier[kwargs] ) keyword[except] identifier[ValueError] keyword[as] identifier[e] : identifier[print] ( literal[string] . identifier[format] ( identifier[name] , identifier[e] ), identifier[file] = identifier[sys] . identifier[stderr] ) keyword[else] : identifier[print] ( literal[string] . identifier[format] ( identifier[name] ), identifier[file] = identifier[sys] . identifier[stderr] ) identifier[sys] . identifier[exit] ( literal[int] )
def init(name, *args, **kwargs): """Instantiate a timeframe from the catalog. """ if name in _TIMEFRAME_CATALOG: if rapport.config.get_int('rapport', 'verbosity') >= 2: print('Initialize timeframe {0}: {1} {2}'.format(name, args, kwargs)) # depends on [control=['if'], data=[]] try: return _TIMEFRAME_CATALOG[name](*args, **kwargs) # depends on [control=['try'], data=[]] except ValueError as e: print('Failed to initialize timeframe {0}: {1}!'.format(name, e), file=sys.stderr) # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=['name', '_TIMEFRAME_CATALOG']] else: print('Failed to initialize timeframe {0}: Not in catalog!'.format(name), file=sys.stderr) sys.exit(1)
def get_mark_css(aes_name, css_value): """Generate CSS class for <mark> tag. Parameters ---------- aes_name: str The name of the class. css_value: str The value for the CSS property defined by aes_name. Returns ------- list of str The CSS codeblocks """ css_prop = AES_CSS_MAP[aes_name] if isinstance(css_value, list): return get_mark_css_for_rules(aes_name, css_prop, css_value) else: return get_mark_simple_css(aes_name, css_prop, css_value)
def function[get_mark_css, parameter[aes_name, css_value]]: constant[Generate CSS class for <mark> tag. Parameters ---------- aes_name: str The name of the class. css_value: str The value for the CSS property defined by aes_name. Returns ------- list of str The CSS codeblocks ] variable[css_prop] assign[=] call[name[AES_CSS_MAP]][name[aes_name]] if call[name[isinstance], parameter[name[css_value], name[list]]] begin[:] return[call[name[get_mark_css_for_rules], parameter[name[aes_name], name[css_prop], name[css_value]]]]
keyword[def] identifier[get_mark_css] ( identifier[aes_name] , identifier[css_value] ): literal[string] identifier[css_prop] = identifier[AES_CSS_MAP] [ identifier[aes_name] ] keyword[if] identifier[isinstance] ( identifier[css_value] , identifier[list] ): keyword[return] identifier[get_mark_css_for_rules] ( identifier[aes_name] , identifier[css_prop] , identifier[css_value] ) keyword[else] : keyword[return] identifier[get_mark_simple_css] ( identifier[aes_name] , identifier[css_prop] , identifier[css_value] )
def get_mark_css(aes_name, css_value): """Generate CSS class for <mark> tag. Parameters ---------- aes_name: str The name of the class. css_value: str The value for the CSS property defined by aes_name. Returns ------- list of str The CSS codeblocks """ css_prop = AES_CSS_MAP[aes_name] if isinstance(css_value, list): return get_mark_css_for_rules(aes_name, css_prop, css_value) # depends on [control=['if'], data=[]] else: return get_mark_simple_css(aes_name, css_prop, css_value)
def rst_table(data, schema=None): """ Creates a reStructuredText simple table (list of strings) from a list of lists. """ # Process multi-rows (replaced by rows with empty columns when needed) pdata = [] for row in data: prow = [el if isinstance(el, list) else [el] for el in row] pdata.extend(pr for pr in xzip_longest(*prow, fillvalue="")) # Find the columns sizes sizes = [max(len("{0}".format(el)) for el in column) for column in xzip(*pdata)] sizes = [max(size, len(sch)) for size, sch in xzip(sizes, schema)] # Creates the title and border rows if schema is None: schema = pdata[0] pdata = pdata[1:] border = " ".join("=" * size for size in sizes) titles = " ".join("{1:^{0}}".format(*pair) for pair in xzip(sizes, schema)) # Creates the full table and returns rows = [border, titles, border] rows.extend(" ".join("{1:<{0}}".format(*pair) for pair in xzip(sizes, row)) for row in pdata) rows.append(border) return rows
def function[rst_table, parameter[data, schema]]: constant[ Creates a reStructuredText simple table (list of strings) from a list of lists. ] variable[pdata] assign[=] list[[]] for taget[name[row]] in starred[name[data]] begin[:] variable[prow] assign[=] <ast.ListComp object at 0x7da1b06e8400> call[name[pdata].extend, parameter[<ast.GeneratorExp object at 0x7da1b06e9db0>]] variable[sizes] assign[=] <ast.ListComp object at 0x7da1b06e9690> variable[sizes] assign[=] <ast.ListComp object at 0x7da1b06ea380> if compare[name[schema] is constant[None]] begin[:] variable[schema] assign[=] call[name[pdata]][constant[0]] variable[pdata] assign[=] call[name[pdata]][<ast.Slice object at 0x7da1b06e9a20>] variable[border] assign[=] call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da1b06e9ba0>]] variable[titles] assign[=] call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da1b06eb9d0>]] variable[rows] assign[=] list[[<ast.Name object at 0x7da1b0619b40>, <ast.Name object at 0x7da1b0619d20>, <ast.Name object at 0x7da1b0619b70>]] call[name[rows].extend, parameter[<ast.GeneratorExp object at 0x7da1b06192a0>]] call[name[rows].append, parameter[name[border]]] return[name[rows]]
keyword[def] identifier[rst_table] ( identifier[data] , identifier[schema] = keyword[None] ): literal[string] identifier[pdata] =[] keyword[for] identifier[row] keyword[in] identifier[data] : identifier[prow] =[ identifier[el] keyword[if] identifier[isinstance] ( identifier[el] , identifier[list] ) keyword[else] [ identifier[el] ] keyword[for] identifier[el] keyword[in] identifier[row] ] identifier[pdata] . identifier[extend] ( identifier[pr] keyword[for] identifier[pr] keyword[in] identifier[xzip_longest] (* identifier[prow] , identifier[fillvalue] = literal[string] )) identifier[sizes] =[ identifier[max] ( identifier[len] ( literal[string] . identifier[format] ( identifier[el] )) keyword[for] identifier[el] keyword[in] identifier[column] ) keyword[for] identifier[column] keyword[in] identifier[xzip] (* identifier[pdata] )] identifier[sizes] =[ identifier[max] ( identifier[size] , identifier[len] ( identifier[sch] )) keyword[for] identifier[size] , identifier[sch] keyword[in] identifier[xzip] ( identifier[sizes] , identifier[schema] )] keyword[if] identifier[schema] keyword[is] keyword[None] : identifier[schema] = identifier[pdata] [ literal[int] ] identifier[pdata] = identifier[pdata] [ literal[int] :] identifier[border] = literal[string] . identifier[join] ( literal[string] * identifier[size] keyword[for] identifier[size] keyword[in] identifier[sizes] ) identifier[titles] = literal[string] . identifier[join] ( literal[string] . identifier[format] (* identifier[pair] ) keyword[for] identifier[pair] keyword[in] identifier[xzip] ( identifier[sizes] , identifier[schema] )) identifier[rows] =[ identifier[border] , identifier[titles] , identifier[border] ] identifier[rows] . identifier[extend] ( literal[string] . identifier[join] ( literal[string] . identifier[format] (* identifier[pair] ) keyword[for] identifier[pair] keyword[in] identifier[xzip] ( identifier[sizes] , identifier[row] )) keyword[for] identifier[row] keyword[in] identifier[pdata] ) identifier[rows] . identifier[append] ( identifier[border] ) keyword[return] identifier[rows]
def rst_table(data, schema=None): """ Creates a reStructuredText simple table (list of strings) from a list of lists. """ # Process multi-rows (replaced by rows with empty columns when needed) pdata = [] for row in data: prow = [el if isinstance(el, list) else [el] for el in row] pdata.extend((pr for pr in xzip_longest(*prow, fillvalue=''))) # depends on [control=['for'], data=['row']] # Find the columns sizes sizes = [max((len('{0}'.format(el)) for el in column)) for column in xzip(*pdata)] sizes = [max(size, len(sch)) for (size, sch) in xzip(sizes, schema)] # Creates the title and border rows if schema is None: schema = pdata[0] pdata = pdata[1:] # depends on [control=['if'], data=['schema']] border = ' '.join(('=' * size for size in sizes)) titles = ' '.join(('{1:^{0}}'.format(*pair) for pair in xzip(sizes, schema))) # Creates the full table and returns rows = [border, titles, border] rows.extend((' '.join(('{1:<{0}}'.format(*pair) for pair in xzip(sizes, row))) for row in pdata)) rows.append(border) return rows
def custom_pygments_guess_lexer_for_filename(_fn, _text, **options): """Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.""" fn = basename(_fn) primary = {} matching_lexers = set() for lexer in _iter_lexerclasses(): for filename in lexer.filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = True for filename in lexer.alias_filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = False if not matching_lexers: raise ClassNotFound('no lexer for filename %r found' % fn) if len(matching_lexers) == 1: return matching_lexers.pop()(**options) result = [] for lexer in matching_lexers: rv = lexer.analyse_text(_text) if rv == 1.0: return lexer(**options) result.append(customize_lexer_priority(_fn, rv, lexer)) matlab = list(filter(lambda x: x[2].name.lower() == 'matlab', result)) if len(matlab) > 0: objc = list(filter(lambda x: x[2].name.lower() == 'objective-c', result)) if objc and objc[0][0] == matlab[0][0]: raise SkipHeartbeat('Skipping because not enough language accuracy.') def type_sort(t): # sort by: # - analyse score # - is primary filename pattern? # - priority # - last resort: class name return (t[0], primary[t[2]], t[1], t[2].__name__) result.sort(key=type_sort) return result[-1][2](**options)
def function[custom_pygments_guess_lexer_for_filename, parameter[_fn, _text]]: constant[Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.] variable[fn] assign[=] call[name[basename], parameter[name[_fn]]] variable[primary] assign[=] dictionary[[], []] variable[matching_lexers] assign[=] call[name[set], parameter[]] for taget[name[lexer]] in starred[call[name[_iter_lexerclasses], parameter[]]] begin[:] for taget[name[filename]] in starred[name[lexer].filenames] begin[:] if call[name[_fn_matches], parameter[name[fn], name[filename]]] begin[:] call[name[matching_lexers].add, parameter[name[lexer]]] call[name[primary]][name[lexer]] assign[=] constant[True] for taget[name[filename]] in starred[name[lexer].alias_filenames] begin[:] if call[name[_fn_matches], parameter[name[fn], name[filename]]] begin[:] call[name[matching_lexers].add, parameter[name[lexer]]] call[name[primary]][name[lexer]] assign[=] constant[False] if <ast.UnaryOp object at 0x7da2047ea3e0> begin[:] <ast.Raise object at 0x7da2047e9780> if compare[call[name[len], parameter[name[matching_lexers]]] equal[==] constant[1]] begin[:] return[call[call[name[matching_lexers].pop, parameter[]], parameter[]]] variable[result] assign[=] list[[]] for taget[name[lexer]] in starred[name[matching_lexers]] begin[:] variable[rv] assign[=] call[name[lexer].analyse_text, parameter[name[_text]]] if compare[name[rv] equal[==] constant[1.0]] begin[:] return[call[name[lexer], parameter[]]] call[name[result].append, parameter[call[name[customize_lexer_priority], parameter[name[_fn], name[rv], name[lexer]]]]] variable[matlab] assign[=] call[name[list], parameter[call[name[filter], parameter[<ast.Lambda object at 0x7da20c6a9bd0>, name[result]]]]] if compare[call[name[len], parameter[name[matlab]]] greater[>] constant[0]] begin[:] variable[objc] assign[=] call[name[list], parameter[call[name[filter], parameter[<ast.Lambda object at 0x7da20c6aa410>, name[result]]]]] if <ast.BoolOp object at 0x7da20c6a9420> begin[:] <ast.Raise object at 0x7da20c6ab2b0> def function[type_sort, parameter[t]]: return[tuple[[<ast.Subscript object at 0x7da20c6ab9a0>, <ast.Subscript object at 0x7da20c6abdc0>, <ast.Subscript object at 0x7da20c6aa5f0>, <ast.Attribute object at 0x7da20c6aa230>]]] call[name[result].sort, parameter[]] return[call[call[call[name[result]][<ast.UnaryOp object at 0x7da20c6a8af0>]][constant[2]], parameter[]]]
keyword[def] identifier[custom_pygments_guess_lexer_for_filename] ( identifier[_fn] , identifier[_text] ,** identifier[options] ): literal[string] identifier[fn] = identifier[basename] ( identifier[_fn] ) identifier[primary] ={} identifier[matching_lexers] = identifier[set] () keyword[for] identifier[lexer] keyword[in] identifier[_iter_lexerclasses] (): keyword[for] identifier[filename] keyword[in] identifier[lexer] . identifier[filenames] : keyword[if] identifier[_fn_matches] ( identifier[fn] , identifier[filename] ): identifier[matching_lexers] . identifier[add] ( identifier[lexer] ) identifier[primary] [ identifier[lexer] ]= keyword[True] keyword[for] identifier[filename] keyword[in] identifier[lexer] . identifier[alias_filenames] : keyword[if] identifier[_fn_matches] ( identifier[fn] , identifier[filename] ): identifier[matching_lexers] . identifier[add] ( identifier[lexer] ) identifier[primary] [ identifier[lexer] ]= keyword[False] keyword[if] keyword[not] identifier[matching_lexers] : keyword[raise] identifier[ClassNotFound] ( literal[string] % identifier[fn] ) keyword[if] identifier[len] ( identifier[matching_lexers] )== literal[int] : keyword[return] identifier[matching_lexers] . identifier[pop] ()(** identifier[options] ) identifier[result] =[] keyword[for] identifier[lexer] keyword[in] identifier[matching_lexers] : identifier[rv] = identifier[lexer] . identifier[analyse_text] ( identifier[_text] ) keyword[if] identifier[rv] == literal[int] : keyword[return] identifier[lexer] (** identifier[options] ) identifier[result] . identifier[append] ( identifier[customize_lexer_priority] ( identifier[_fn] , identifier[rv] , identifier[lexer] )) identifier[matlab] = identifier[list] ( identifier[filter] ( keyword[lambda] identifier[x] : identifier[x] [ literal[int] ]. identifier[name] . identifier[lower] ()== literal[string] , identifier[result] )) keyword[if] identifier[len] ( identifier[matlab] )> literal[int] : identifier[objc] = identifier[list] ( identifier[filter] ( keyword[lambda] identifier[x] : identifier[x] [ literal[int] ]. identifier[name] . identifier[lower] ()== literal[string] , identifier[result] )) keyword[if] identifier[objc] keyword[and] identifier[objc] [ literal[int] ][ literal[int] ]== identifier[matlab] [ literal[int] ][ literal[int] ]: keyword[raise] identifier[SkipHeartbeat] ( literal[string] ) keyword[def] identifier[type_sort] ( identifier[t] ): keyword[return] ( identifier[t] [ literal[int] ], identifier[primary] [ identifier[t] [ literal[int] ]], identifier[t] [ literal[int] ], identifier[t] [ literal[int] ]. identifier[__name__] ) identifier[result] . identifier[sort] ( identifier[key] = identifier[type_sort] ) keyword[return] identifier[result] [- literal[int] ][ literal[int] ](** identifier[options] )
def custom_pygments_guess_lexer_for_filename(_fn, _text, **options): """Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.""" fn = basename(_fn) primary = {} matching_lexers = set() for lexer in _iter_lexerclasses(): for filename in lexer.filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['filename']] for filename in lexer.alias_filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = False # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['filename']] # depends on [control=['for'], data=['lexer']] if not matching_lexers: raise ClassNotFound('no lexer for filename %r found' % fn) # depends on [control=['if'], data=[]] if len(matching_lexers) == 1: return matching_lexers.pop()(**options) # depends on [control=['if'], data=[]] result = [] for lexer in matching_lexers: rv = lexer.analyse_text(_text) if rv == 1.0: return lexer(**options) # depends on [control=['if'], data=[]] result.append(customize_lexer_priority(_fn, rv, lexer)) # depends on [control=['for'], data=['lexer']] matlab = list(filter(lambda x: x[2].name.lower() == 'matlab', result)) if len(matlab) > 0: objc = list(filter(lambda x: x[2].name.lower() == 'objective-c', result)) if objc and objc[0][0] == matlab[0][0]: raise SkipHeartbeat('Skipping because not enough language accuracy.') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] def type_sort(t): # sort by: # - analyse score # - is primary filename pattern? # - priority # - last resort: class name return (t[0], primary[t[2]], t[1], t[2].__name__) result.sort(key=type_sort) return result[-1][2](**options)
def set_controller_state(self, name, value): # type: (str, bool) -> None """ Sets the state of the controller with the given name :param name: The name of the controller :param value: The new value of the controller """ with self._lock: self._controllers_state[name] = value self.__safe_handlers_callback("on_controller_change", name, value)
def function[set_controller_state, parameter[self, name, value]]: constant[ Sets the state of the controller with the given name :param name: The name of the controller :param value: The new value of the controller ] with name[self]._lock begin[:] call[name[self]._controllers_state][name[name]] assign[=] name[value] call[name[self].__safe_handlers_callback, parameter[constant[on_controller_change], name[name], name[value]]]
keyword[def] identifier[set_controller_state] ( identifier[self] , identifier[name] , identifier[value] ): literal[string] keyword[with] identifier[self] . identifier[_lock] : identifier[self] . identifier[_controllers_state] [ identifier[name] ]= identifier[value] identifier[self] . identifier[__safe_handlers_callback] ( literal[string] , identifier[name] , identifier[value] )
def set_controller_state(self, name, value): # type: (str, bool) -> None '\n Sets the state of the controller with the given name\n\n :param name: The name of the controller\n :param value: The new value of the controller\n ' with self._lock: self._controllers_state[name] = value self.__safe_handlers_callback('on_controller_change', name, value) # depends on [control=['with'], data=[]]
def scalarVectorDecorator(func): """Decorator to return scalar outputs as a set""" @wraps(func) def scalar_wrapper(*args,**kwargs): if numpy.array(args[1]).shape == () \ and numpy.array(args[2]).shape == (): #only if both R and z are scalars scalarOut= True args= (args[0],numpy.array([args[1]]),numpy.array([args[2]])) elif numpy.array(args[1]).shape == () \ and not numpy.array(args[2]).shape == (): #R scalar, z vector scalarOut= False args= (args[0],args[1]*numpy.ones_like(args[2]),args[2]) elif not numpy.array(args[1]).shape == () \ and numpy.array(args[2]).shape == (): #R vector, z scalar scalarOut= False args= (args[0],args[1],args[2]*numpy.ones_like(args[1])) else: scalarOut= False result= func(*args,**kwargs) if scalarOut: return result[0] else: return result return scalar_wrapper
def function[scalarVectorDecorator, parameter[func]]: constant[Decorator to return scalar outputs as a set] def function[scalar_wrapper, parameter[]]: if <ast.BoolOp object at 0x7da1b0c4f130> begin[:] variable[scalarOut] assign[=] constant[True] variable[args] assign[=] tuple[[<ast.Subscript object at 0x7da1b0c4d870>, <ast.Call object at 0x7da1b0c4d7b0>, <ast.Call object at 0x7da1b0c4d690>]] variable[result] assign[=] call[name[func], parameter[<ast.Starred object at 0x7da1b0c4ebc0>]] if name[scalarOut] begin[:] return[call[name[result]][constant[0]]] return[name[scalar_wrapper]]
keyword[def] identifier[scalarVectorDecorator] ( identifier[func] ): literal[string] @ identifier[wraps] ( identifier[func] ) keyword[def] identifier[scalar_wrapper] (* identifier[args] ,** identifier[kwargs] ): keyword[if] identifier[numpy] . identifier[array] ( identifier[args] [ literal[int] ]). identifier[shape] ==() keyword[and] identifier[numpy] . identifier[array] ( identifier[args] [ literal[int] ]). identifier[shape] ==(): identifier[scalarOut] = keyword[True] identifier[args] =( identifier[args] [ literal[int] ], identifier[numpy] . identifier[array] ([ identifier[args] [ literal[int] ]]), identifier[numpy] . identifier[array] ([ identifier[args] [ literal[int] ]])) keyword[elif] identifier[numpy] . identifier[array] ( identifier[args] [ literal[int] ]). identifier[shape] ==() keyword[and] keyword[not] identifier[numpy] . identifier[array] ( identifier[args] [ literal[int] ]). identifier[shape] ==(): identifier[scalarOut] = keyword[False] identifier[args] =( identifier[args] [ literal[int] ], identifier[args] [ literal[int] ]* identifier[numpy] . identifier[ones_like] ( identifier[args] [ literal[int] ]), identifier[args] [ literal[int] ]) keyword[elif] keyword[not] identifier[numpy] . identifier[array] ( identifier[args] [ literal[int] ]). identifier[shape] ==() keyword[and] identifier[numpy] . identifier[array] ( identifier[args] [ literal[int] ]). identifier[shape] ==(): identifier[scalarOut] = keyword[False] identifier[args] =( identifier[args] [ literal[int] ], identifier[args] [ literal[int] ], identifier[args] [ literal[int] ]* identifier[numpy] . identifier[ones_like] ( identifier[args] [ literal[int] ])) keyword[else] : identifier[scalarOut] = keyword[False] identifier[result] = identifier[func] (* identifier[args] ,** identifier[kwargs] ) keyword[if] identifier[scalarOut] : keyword[return] identifier[result] [ literal[int] ] keyword[else] : keyword[return] identifier[result] keyword[return] identifier[scalar_wrapper]
def scalarVectorDecorator(func): """Decorator to return scalar outputs as a set""" @wraps(func) def scalar_wrapper(*args, **kwargs): if numpy.array(args[1]).shape == () and numpy.array(args[2]).shape == (): #only if both R and z are scalars scalarOut = True args = (args[0], numpy.array([args[1]]), numpy.array([args[2]])) # depends on [control=['if'], data=[]] elif numpy.array(args[1]).shape == () and (not numpy.array(args[2]).shape == ()): #R scalar, z vector scalarOut = False args = (args[0], args[1] * numpy.ones_like(args[2]), args[2]) # depends on [control=['if'], data=[]] elif not numpy.array(args[1]).shape == () and numpy.array(args[2]).shape == (): #R vector, z scalar scalarOut = False args = (args[0], args[1], args[2] * numpy.ones_like(args[1])) # depends on [control=['if'], data=[]] else: scalarOut = False result = func(*args, **kwargs) if scalarOut: return result[0] # depends on [control=['if'], data=[]] else: return result return scalar_wrapper
def _get_application_module(self, controller, application): """Return the module for an application. If it's a entry-point registered application name, return the module name from the entry points data. If not, the passed in application name is returned. :param str controller: The controller type :param str application: The application name or module :rtype: str """ for pkg in self._get_applications(controller): if pkg.name == application: return pkg.module_name return application
def function[_get_application_module, parameter[self, controller, application]]: constant[Return the module for an application. If it's a entry-point registered application name, return the module name from the entry points data. If not, the passed in application name is returned. :param str controller: The controller type :param str application: The application name or module :rtype: str ] for taget[name[pkg]] in starred[call[name[self]._get_applications, parameter[name[controller]]]] begin[:] if compare[name[pkg].name equal[==] name[application]] begin[:] return[name[pkg].module_name] return[name[application]]
keyword[def] identifier[_get_application_module] ( identifier[self] , identifier[controller] , identifier[application] ): literal[string] keyword[for] identifier[pkg] keyword[in] identifier[self] . identifier[_get_applications] ( identifier[controller] ): keyword[if] identifier[pkg] . identifier[name] == identifier[application] : keyword[return] identifier[pkg] . identifier[module_name] keyword[return] identifier[application]
def _get_application_module(self, controller, application): """Return the module for an application. If it's a entry-point registered application name, return the module name from the entry points data. If not, the passed in application name is returned. :param str controller: The controller type :param str application: The application name or module :rtype: str """ for pkg in self._get_applications(controller): if pkg.name == application: return pkg.module_name # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['pkg']] return application
def sys_deallocate(self, cpu, addr, size): """ deallocate - remove allocations The deallocate system call deletes the allocations for the specified address range, and causes further references to the addresses within the range to generate invalid memory accesses. The region is also automatically deallocated when the process is terminated. The address addr must be a multiple of the page size. The length parameter specifies the size of the region to be deallocated in bytes. All pages containing a part of the indicated range are deallocated, and subsequent references will terminate the process. It is not an error if the indicated range does not contain any allocated pages. The deallocate function is invoked through system call number 6. :param cpu: current CPU :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return 0 On success EINVAL addr is not page aligned. EINVAL length is zero. EINVAL any part of the region being deallocated is outside the valid address range of the process. :param cpu: current CPU. :return: C{0} on success. """ logger.info("DEALLOCATE(0x%08x, %d)" % (addr, size)) if addr & 0xfff != 0: logger.info("DEALLOCATE: addr is not page aligned") return Decree.CGC_EINVAL if size == 0: logger.info("DEALLOCATE:length is zero") return Decree.CGC_EINVAL # unlikely AND WRONG!!! # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX: # logger.info("DEALLOCATE: part of the region being deallocated is outside the valid address range of the process") # return Decree.CGC_EINVAL cpu.memory.munmap(addr, size) self.syscall_trace.append(("_deallocate", -1, size)) return 0
def function[sys_deallocate, parameter[self, cpu, addr, size]]: constant[ deallocate - remove allocations The deallocate system call deletes the allocations for the specified address range, and causes further references to the addresses within the range to generate invalid memory accesses. The region is also automatically deallocated when the process is terminated. The address addr must be a multiple of the page size. The length parameter specifies the size of the region to be deallocated in bytes. All pages containing a part of the indicated range are deallocated, and subsequent references will terminate the process. It is not an error if the indicated range does not contain any allocated pages. The deallocate function is invoked through system call number 6. :param cpu: current CPU :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return 0 On success EINVAL addr is not page aligned. EINVAL length is zero. EINVAL any part of the region being deallocated is outside the valid address range of the process. :param cpu: current CPU. :return: C{0} on success. ] call[name[logger].info, parameter[binary_operation[constant[DEALLOCATE(0x%08x, %d)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18f812a70>, <ast.Name object at 0x7da18f810b50>]]]]] if compare[binary_operation[name[addr] <ast.BitAnd object at 0x7da2590d6b60> constant[4095]] not_equal[!=] constant[0]] begin[:] call[name[logger].info, parameter[constant[DEALLOCATE: addr is not page aligned]]] return[name[Decree].CGC_EINVAL] if compare[name[size] equal[==] constant[0]] begin[:] call[name[logger].info, parameter[constant[DEALLOCATE:length is zero]]] return[name[Decree].CGC_EINVAL] call[name[cpu].memory.munmap, parameter[name[addr], name[size]]] call[name[self].syscall_trace.append, parameter[tuple[[<ast.Constant object at 0x7da18f8132e0>, <ast.UnaryOp object at 0x7da18f813c10>, <ast.Name object at 0x7da18f8125f0>]]]] return[constant[0]]
keyword[def] identifier[sys_deallocate] ( identifier[self] , identifier[cpu] , identifier[addr] , identifier[size] ): literal[string] identifier[logger] . identifier[info] ( literal[string] %( identifier[addr] , identifier[size] )) keyword[if] identifier[addr] & literal[int] != literal[int] : identifier[logger] . identifier[info] ( literal[string] ) keyword[return] identifier[Decree] . identifier[CGC_EINVAL] keyword[if] identifier[size] == literal[int] : identifier[logger] . identifier[info] ( literal[string] ) keyword[return] identifier[Decree] . identifier[CGC_EINVAL] identifier[cpu] . identifier[memory] . identifier[munmap] ( identifier[addr] , identifier[size] ) identifier[self] . identifier[syscall_trace] . identifier[append] (( literal[string] ,- literal[int] , identifier[size] )) keyword[return] literal[int]
def sys_deallocate(self, cpu, addr, size): """ deallocate - remove allocations The deallocate system call deletes the allocations for the specified address range, and causes further references to the addresses within the range to generate invalid memory accesses. The region is also automatically deallocated when the process is terminated. The address addr must be a multiple of the page size. The length parameter specifies the size of the region to be deallocated in bytes. All pages containing a part of the indicated range are deallocated, and subsequent references will terminate the process. It is not an error if the indicated range does not contain any allocated pages. The deallocate function is invoked through system call number 6. :param cpu: current CPU :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return 0 On success EINVAL addr is not page aligned. EINVAL length is zero. EINVAL any part of the region being deallocated is outside the valid address range of the process. :param cpu: current CPU. :return: C{0} on success. """ logger.info('DEALLOCATE(0x%08x, %d)' % (addr, size)) if addr & 4095 != 0: logger.info('DEALLOCATE: addr is not page aligned') return Decree.CGC_EINVAL # depends on [control=['if'], data=[]] if size == 0: logger.info('DEALLOCATE:length is zero') return Decree.CGC_EINVAL # depends on [control=['if'], data=[]] # unlikely AND WRONG!!! # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX: # logger.info("DEALLOCATE: part of the region being deallocated is outside the valid address range of the process") # return Decree.CGC_EINVAL cpu.memory.munmap(addr, size) self.syscall_trace.append(('_deallocate', -1, size)) return 0
def _load_hdf5(self, filename, parent_level="CellpyData"): """Load a cellpy-file. Args: filename (str): Name of the cellpy file. parent_level (str) (optional): name of the parent level (defaults to "CellpyData") Returns: loaded datasets (DataSet-object) """ if not os.path.isfile(filename): self.logger.info(f"file does not exist: {filename}") raise IOError store = pd.HDFStore(filename) # required_keys = ['dfdata', 'dfsummary', 'fidtable', 'info'] required_keys = ['dfdata', 'dfsummary', 'info'] required_keys = ["/" + parent_level + "/" + _ for _ in required_keys] for key in required_keys: if key not in store.keys(): self.logger.info(f"This hdf-file is not good enough - " f"at least one key is missing: {key}") raise Exception(f"OH MY GOD! At least one crucial key" f"is missing {key}!") self.logger.debug(f"Keys in current hdf5-file: {store.keys()}") data = DataSet() if parent_level != "CellpyData": self.logger.debug("Using non-default parent label for the " "hdf-store: {}".format(parent_level)) # checking file version infotable = store.select(parent_level + "/info") try: data.cellpy_file_version = \ self._extract_from_dict(infotable, "cellpy_file_version") except Exception as e: data.cellpy_file_version = 0 warnings.warn(f"Unhandled exception raised: {e}") if data.cellpy_file_version < MINIMUM_CELLPY_FILE_VERSION: raise WrongFileVersion if data.cellpy_file_version > CELLPY_FILE_VERSION: raise WrongFileVersion data.dfsummary = store.select(parent_level + "/dfsummary") data.dfdata = store.select(parent_level + "/dfdata") try: data.step_table = store.select(parent_level + "/step_table") except Exception as e: self.logging.debug("could not get step_table from cellpy-file") data.step_table = pd.DataFrame() warnings.warn(f"Unhandled exception raised: {e}") try: fidtable = store.select( parent_level + "/fidtable") # remark! changed spelling from # lower letter to camel-case! fidtable_selected = True except Exception as e: self.logging.debug("could not get fid-table from cellpy-file") fidtable = [] warnings.warn("no fidtable - you should update your hdf5-file") fidtable_selected = False self.logger.debug(" h5") # this does not yet allow multiple sets newtests = [] # but this is ready when that time comes # The infotable stores "meta-data". The follwing statements loads the # content of infotable and updates div. DataSet attributes. # Maybe better use it as dict? data = self._load_infotable(data, infotable, filename) if fidtable_selected: data.raw_data_files, data.raw_data_files_length = \ self._convert2fid_list(fidtable) else: data.raw_data_files = None data.raw_data_files_length = None newtests.append(data) store.close() # self.datasets.append(data) return newtests
def function[_load_hdf5, parameter[self, filename, parent_level]]: constant[Load a cellpy-file. Args: filename (str): Name of the cellpy file. parent_level (str) (optional): name of the parent level (defaults to "CellpyData") Returns: loaded datasets (DataSet-object) ] if <ast.UnaryOp object at 0x7da2044c1a80> begin[:] call[name[self].logger.info, parameter[<ast.JoinedStr object at 0x7da2044c3670>]] <ast.Raise object at 0x7da2044c3820> variable[store] assign[=] call[name[pd].HDFStore, parameter[name[filename]]] variable[required_keys] assign[=] list[[<ast.Constant object at 0x7da2044c0e20>, <ast.Constant object at 0x7da2044c3f70>, <ast.Constant object at 0x7da2044c0790>]] variable[required_keys] assign[=] <ast.ListComp object at 0x7da2044c1db0> for taget[name[key]] in starred[name[required_keys]] begin[:] if compare[name[key] <ast.NotIn object at 0x7da2590d7190> call[name[store].keys, parameter[]]] begin[:] call[name[self].logger.info, parameter[<ast.JoinedStr object at 0x7da2044c1600>]] <ast.Raise object at 0x7da2044c06d0> call[name[self].logger.debug, parameter[<ast.JoinedStr object at 0x7da1b192e770>]] variable[data] assign[=] call[name[DataSet], parameter[]] if compare[name[parent_level] not_equal[!=] constant[CellpyData]] begin[:] call[name[self].logger.debug, parameter[call[constant[Using non-default parent label for the hdf-store: {}].format, parameter[name[parent_level]]]]] variable[infotable] assign[=] call[name[store].select, parameter[binary_operation[name[parent_level] + constant[/info]]]] <ast.Try object at 0x7da2044c2710> if compare[name[data].cellpy_file_version less[<] name[MINIMUM_CELLPY_FILE_VERSION]] begin[:] <ast.Raise object at 0x7da2044c38e0> if compare[name[data].cellpy_file_version greater[>] name[CELLPY_FILE_VERSION]] begin[:] <ast.Raise object at 0x7da2044c0a30> name[data].dfsummary assign[=] call[name[store].select, parameter[binary_operation[name[parent_level] + constant[/dfsummary]]]] name[data].dfdata assign[=] call[name[store].select, parameter[binary_operation[name[parent_level] + constant[/dfdata]]]] <ast.Try object at 0x7da2044c1930> <ast.Try object at 0x7da2044c0850> call[name[self].logger.debug, parameter[constant[ h5]]] variable[newtests] assign[=] list[[]] variable[data] assign[=] call[name[self]._load_infotable, parameter[name[data], name[infotable], name[filename]]] if name[fidtable_selected] begin[:] <ast.Tuple object at 0x7da1b1a1e290> assign[=] call[name[self]._convert2fid_list, parameter[name[fidtable]]] call[name[newtests].append, parameter[name[data]]] call[name[store].close, parameter[]] return[name[newtests]]
keyword[def] identifier[_load_hdf5] ( identifier[self] , identifier[filename] , identifier[parent_level] = literal[string] ): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[filename] ): identifier[self] . identifier[logger] . identifier[info] ( literal[string] ) keyword[raise] identifier[IOError] identifier[store] = identifier[pd] . identifier[HDFStore] ( identifier[filename] ) identifier[required_keys] =[ literal[string] , literal[string] , literal[string] ] identifier[required_keys] =[ literal[string] + identifier[parent_level] + literal[string] + identifier[_] keyword[for] identifier[_] keyword[in] identifier[required_keys] ] keyword[for] identifier[key] keyword[in] identifier[required_keys] : keyword[if] identifier[key] keyword[not] keyword[in] identifier[store] . identifier[keys] (): identifier[self] . identifier[logger] . identifier[info] ( literal[string] literal[string] ) keyword[raise] identifier[Exception] ( literal[string] literal[string] ) identifier[self] . identifier[logger] . identifier[debug] ( literal[string] ) identifier[data] = identifier[DataSet] () keyword[if] identifier[parent_level] != literal[string] : identifier[self] . identifier[logger] . identifier[debug] ( literal[string] literal[string] . identifier[format] ( identifier[parent_level] )) identifier[infotable] = identifier[store] . identifier[select] ( identifier[parent_level] + literal[string] ) keyword[try] : identifier[data] . identifier[cellpy_file_version] = identifier[self] . identifier[_extract_from_dict] ( identifier[infotable] , literal[string] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[data] . identifier[cellpy_file_version] = literal[int] identifier[warnings] . identifier[warn] ( literal[string] ) keyword[if] identifier[data] . identifier[cellpy_file_version] < identifier[MINIMUM_CELLPY_FILE_VERSION] : keyword[raise] identifier[WrongFileVersion] keyword[if] identifier[data] . identifier[cellpy_file_version] > identifier[CELLPY_FILE_VERSION] : keyword[raise] identifier[WrongFileVersion] identifier[data] . identifier[dfsummary] = identifier[store] . identifier[select] ( identifier[parent_level] + literal[string] ) identifier[data] . identifier[dfdata] = identifier[store] . identifier[select] ( identifier[parent_level] + literal[string] ) keyword[try] : identifier[data] . identifier[step_table] = identifier[store] . identifier[select] ( identifier[parent_level] + literal[string] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[logging] . identifier[debug] ( literal[string] ) identifier[data] . identifier[step_table] = identifier[pd] . identifier[DataFrame] () identifier[warnings] . identifier[warn] ( literal[string] ) keyword[try] : identifier[fidtable] = identifier[store] . identifier[select] ( identifier[parent_level] + literal[string] ) identifier[fidtable_selected] = keyword[True] keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[logging] . identifier[debug] ( literal[string] ) identifier[fidtable] =[] identifier[warnings] . identifier[warn] ( literal[string] ) identifier[fidtable_selected] = keyword[False] identifier[self] . identifier[logger] . identifier[debug] ( literal[string] ) identifier[newtests] =[] identifier[data] = identifier[self] . identifier[_load_infotable] ( identifier[data] , identifier[infotable] , identifier[filename] ) keyword[if] identifier[fidtable_selected] : identifier[data] . identifier[raw_data_files] , identifier[data] . identifier[raw_data_files_length] = identifier[self] . identifier[_convert2fid_list] ( identifier[fidtable] ) keyword[else] : identifier[data] . identifier[raw_data_files] = keyword[None] identifier[data] . identifier[raw_data_files_length] = keyword[None] identifier[newtests] . identifier[append] ( identifier[data] ) identifier[store] . identifier[close] () keyword[return] identifier[newtests]
def _load_hdf5(self, filename, parent_level='CellpyData'): """Load a cellpy-file. Args: filename (str): Name of the cellpy file. parent_level (str) (optional): name of the parent level (defaults to "CellpyData") Returns: loaded datasets (DataSet-object) """ if not os.path.isfile(filename): self.logger.info(f'file does not exist: {filename}') raise IOError # depends on [control=['if'], data=[]] store = pd.HDFStore(filename) # required_keys = ['dfdata', 'dfsummary', 'fidtable', 'info'] required_keys = ['dfdata', 'dfsummary', 'info'] required_keys = ['/' + parent_level + '/' + _ for _ in required_keys] for key in required_keys: if key not in store.keys(): self.logger.info(f'This hdf-file is not good enough - at least one key is missing: {key}') raise Exception(f'OH MY GOD! At least one crucial keyis missing {key}!') # depends on [control=['if'], data=['key']] # depends on [control=['for'], data=['key']] self.logger.debug(f'Keys in current hdf5-file: {store.keys()}') data = DataSet() if parent_level != 'CellpyData': self.logger.debug('Using non-default parent label for the hdf-store: {}'.format(parent_level)) # depends on [control=['if'], data=['parent_level']] # checking file version infotable = store.select(parent_level + '/info') try: data.cellpy_file_version = self._extract_from_dict(infotable, 'cellpy_file_version') # depends on [control=['try'], data=[]] except Exception as e: data.cellpy_file_version = 0 warnings.warn(f'Unhandled exception raised: {e}') # depends on [control=['except'], data=['e']] if data.cellpy_file_version < MINIMUM_CELLPY_FILE_VERSION: raise WrongFileVersion # depends on [control=['if'], data=[]] if data.cellpy_file_version > CELLPY_FILE_VERSION: raise WrongFileVersion # depends on [control=['if'], data=[]] data.dfsummary = store.select(parent_level + '/dfsummary') data.dfdata = store.select(parent_level + '/dfdata') try: data.step_table = store.select(parent_level + '/step_table') # depends on [control=['try'], data=[]] except Exception as e: self.logging.debug('could not get step_table from cellpy-file') data.step_table = pd.DataFrame() warnings.warn(f'Unhandled exception raised: {e}') # depends on [control=['except'], data=['e']] try: fidtable = store.select(parent_level + '/fidtable') # remark! changed spelling from # lower letter to camel-case! fidtable_selected = True # depends on [control=['try'], data=[]] except Exception as e: self.logging.debug('could not get fid-table from cellpy-file') fidtable = [] warnings.warn('no fidtable - you should update your hdf5-file') fidtable_selected = False # depends on [control=['except'], data=[]] self.logger.debug(' h5') # this does not yet allow multiple sets newtests = [] # but this is ready when that time comes # The infotable stores "meta-data". The follwing statements loads the # content of infotable and updates div. DataSet attributes. # Maybe better use it as dict? data = self._load_infotable(data, infotable, filename) if fidtable_selected: (data.raw_data_files, data.raw_data_files_length) = self._convert2fid_list(fidtable) # depends on [control=['if'], data=[]] else: data.raw_data_files = None data.raw_data_files_length = None newtests.append(data) store.close() # self.datasets.append(data) return newtests
def resolve_relpath(self, fullname, level): """Given an ImportFrom AST node, guess the prefix that should be tacked on to an alias name to produce a canonical name. `fullname` is the name of the module in which the ImportFrom appears. """ mod = sys.modules.get(fullname, None) if hasattr(mod, '__path__'): fullname += '.__init__' if level == 0 or not fullname: return '' bits = fullname.split('.') if len(bits) <= level: # This would be an ImportError in real code. return '' return '.'.join(bits[:-level]) + '.'
def function[resolve_relpath, parameter[self, fullname, level]]: constant[Given an ImportFrom AST node, guess the prefix that should be tacked on to an alias name to produce a canonical name. `fullname` is the name of the module in which the ImportFrom appears. ] variable[mod] assign[=] call[name[sys].modules.get, parameter[name[fullname], constant[None]]] if call[name[hasattr], parameter[name[mod], constant[__path__]]] begin[:] <ast.AugAssign object at 0x7da1b1d0f730> if <ast.BoolOp object at 0x7da1b1d0d480> begin[:] return[constant[]] variable[bits] assign[=] call[name[fullname].split, parameter[constant[.]]] if compare[call[name[len], parameter[name[bits]]] less_or_equal[<=] name[level]] begin[:] return[constant[]] return[binary_operation[call[constant[.].join, parameter[call[name[bits]][<ast.Slice object at 0x7da1b1d0c280>]]] + constant[.]]]
keyword[def] identifier[resolve_relpath] ( identifier[self] , identifier[fullname] , identifier[level] ): literal[string] identifier[mod] = identifier[sys] . identifier[modules] . identifier[get] ( identifier[fullname] , keyword[None] ) keyword[if] identifier[hasattr] ( identifier[mod] , literal[string] ): identifier[fullname] += literal[string] keyword[if] identifier[level] == literal[int] keyword[or] keyword[not] identifier[fullname] : keyword[return] literal[string] identifier[bits] = identifier[fullname] . identifier[split] ( literal[string] ) keyword[if] identifier[len] ( identifier[bits] )<= identifier[level] : keyword[return] literal[string] keyword[return] literal[string] . identifier[join] ( identifier[bits] [:- identifier[level] ])+ literal[string]
def resolve_relpath(self, fullname, level): """Given an ImportFrom AST node, guess the prefix that should be tacked on to an alias name to produce a canonical name. `fullname` is the name of the module in which the ImportFrom appears. """ mod = sys.modules.get(fullname, None) if hasattr(mod, '__path__'): fullname += '.__init__' # depends on [control=['if'], data=[]] if level == 0 or not fullname: return '' # depends on [control=['if'], data=[]] bits = fullname.split('.') if len(bits) <= level: # This would be an ImportError in real code. return '' # depends on [control=['if'], data=[]] return '.'.join(bits[:-level]) + '.'
def recv_exit_status(self, command, timeout=10, get_pty=False): """ Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @type get_pty: bool @return: the exit code of the process or None in case of timeout @rtype: int or None """ status = None self.last_command = command stdin, stdout, stderr = self.cli.exec_command(command, get_pty=get_pty) if stdout and stderr and stdin: for _ in range(timeout): if stdout.channel.exit_status_ready(): status = stdout.channel.recv_exit_status() break time.sleep(1) self.last_stdout = stdout.read() self.last_stderr = stderr.read() stdin.close() stdout.close() stderr.close() return status
def function[recv_exit_status, parameter[self, command, timeout, get_pty]]: constant[ Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @type get_pty: bool @return: the exit code of the process or None in case of timeout @rtype: int or None ] variable[status] assign[=] constant[None] name[self].last_command assign[=] name[command] <ast.Tuple object at 0x7da1b18bb2b0> assign[=] call[name[self].cli.exec_command, parameter[name[command]]] if <ast.BoolOp object at 0x7da1b18ba1a0> begin[:] for taget[name[_]] in starred[call[name[range], parameter[name[timeout]]]] begin[:] if call[name[stdout].channel.exit_status_ready, parameter[]] begin[:] variable[status] assign[=] call[name[stdout].channel.recv_exit_status, parameter[]] break call[name[time].sleep, parameter[constant[1]]] name[self].last_stdout assign[=] call[name[stdout].read, parameter[]] name[self].last_stderr assign[=] call[name[stderr].read, parameter[]] call[name[stdin].close, parameter[]] call[name[stdout].close, parameter[]] call[name[stderr].close, parameter[]] return[name[status]]
keyword[def] identifier[recv_exit_status] ( identifier[self] , identifier[command] , identifier[timeout] = literal[int] , identifier[get_pty] = keyword[False] ): literal[string] identifier[status] = keyword[None] identifier[self] . identifier[last_command] = identifier[command] identifier[stdin] , identifier[stdout] , identifier[stderr] = identifier[self] . identifier[cli] . identifier[exec_command] ( identifier[command] , identifier[get_pty] = identifier[get_pty] ) keyword[if] identifier[stdout] keyword[and] identifier[stderr] keyword[and] identifier[stdin] : keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[timeout] ): keyword[if] identifier[stdout] . identifier[channel] . identifier[exit_status_ready] (): identifier[status] = identifier[stdout] . identifier[channel] . identifier[recv_exit_status] () keyword[break] identifier[time] . identifier[sleep] ( literal[int] ) identifier[self] . identifier[last_stdout] = identifier[stdout] . identifier[read] () identifier[self] . identifier[last_stderr] = identifier[stderr] . identifier[read] () identifier[stdin] . identifier[close] () identifier[stdout] . identifier[close] () identifier[stderr] . identifier[close] () keyword[return] identifier[status]
def recv_exit_status(self, command, timeout=10, get_pty=False): """ Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @type get_pty: bool @return: the exit code of the process or None in case of timeout @rtype: int or None """ status = None self.last_command = command (stdin, stdout, stderr) = self.cli.exec_command(command, get_pty=get_pty) if stdout and stderr and stdin: for _ in range(timeout): if stdout.channel.exit_status_ready(): status = stdout.channel.recv_exit_status() break # depends on [control=['if'], data=[]] time.sleep(1) # depends on [control=['for'], data=[]] self.last_stdout = stdout.read() self.last_stderr = stderr.read() stdin.close() stdout.close() stderr.close() # depends on [control=['if'], data=[]] return status
def remove(self, force=False): """ Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to remove. """ return self.client.api.remove_volume(self.id, force=force)
def function[remove, parameter[self, force]]: constant[ Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to remove. ] return[call[name[self].client.api.remove_volume, parameter[name[self].id]]]
keyword[def] identifier[remove] ( identifier[self] , identifier[force] = keyword[False] ): literal[string] keyword[return] identifier[self] . identifier[client] . identifier[api] . identifier[remove_volume] ( identifier[self] . identifier[id] , identifier[force] = identifier[force] )
def remove(self, force=False): """ Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to remove. """ return self.client.api.remove_volume(self.id, force=force)
def has_parent_books(self, book_id): """Tests if the ``Book`` has any parents. arg: book_id (osid.id.Id): a book ``Id`` return: (boolean) - ``true`` if the book has parents, f ``alse`` otherwise raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinHierarchySession.has_parent_bins if self._catalog_session is not None: return self._catalog_session.has_parent_catalogs(catalog_id=book_id) return self._hierarchy_session.has_parents(id_=book_id)
def function[has_parent_books, parameter[self, book_id]]: constant[Tests if the ``Book`` has any parents. arg: book_id (osid.id.Id): a book ``Id`` return: (boolean) - ``true`` if the book has parents, f ``alse`` otherwise raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* ] if compare[name[self]._catalog_session is_not constant[None]] begin[:] return[call[name[self]._catalog_session.has_parent_catalogs, parameter[]]] return[call[name[self]._hierarchy_session.has_parents, parameter[]]]
keyword[def] identifier[has_parent_books] ( identifier[self] , identifier[book_id] ): literal[string] keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[self] . identifier[_catalog_session] . identifier[has_parent_catalogs] ( identifier[catalog_id] = identifier[book_id] ) keyword[return] identifier[self] . identifier[_hierarchy_session] . identifier[has_parents] ( identifier[id_] = identifier[book_id] )
def has_parent_books(self, book_id): """Tests if the ``Book`` has any parents. arg: book_id (osid.id.Id): a book ``Id`` return: (boolean) - ``true`` if the book has parents, f ``alse`` otherwise raise: NotFound - ``book_id`` is not found raise: NullArgument - ``book_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinHierarchySession.has_parent_bins if self._catalog_session is not None: return self._catalog_session.has_parent_catalogs(catalog_id=book_id) # depends on [control=['if'], data=[]] return self._hierarchy_session.has_parents(id_=book_id)
def get_eta(self, mag, std): """ Return Eta feature. Parameters ---------- mag : array_like An array of magnitudes. std : array_like A standard deviation of magnitudes. Returns ------- eta : float The value of Eta index. """ diff = mag[1:] - mag[:len(mag) - 1] eta = np.sum(diff * diff) / (len(mag) - 1.) / std / std return eta
def function[get_eta, parameter[self, mag, std]]: constant[ Return Eta feature. Parameters ---------- mag : array_like An array of magnitudes. std : array_like A standard deviation of magnitudes. Returns ------- eta : float The value of Eta index. ] variable[diff] assign[=] binary_operation[call[name[mag]][<ast.Slice object at 0x7da207f03100>] - call[name[mag]][<ast.Slice object at 0x7da207f02590>]] variable[eta] assign[=] binary_operation[binary_operation[binary_operation[call[name[np].sum, parameter[binary_operation[name[diff] * name[diff]]]] / binary_operation[call[name[len], parameter[name[mag]]] - constant[1.0]]] / name[std]] / name[std]] return[name[eta]]
keyword[def] identifier[get_eta] ( identifier[self] , identifier[mag] , identifier[std] ): literal[string] identifier[diff] = identifier[mag] [ literal[int] :]- identifier[mag] [: identifier[len] ( identifier[mag] )- literal[int] ] identifier[eta] = identifier[np] . identifier[sum] ( identifier[diff] * identifier[diff] )/( identifier[len] ( identifier[mag] )- literal[int] )/ identifier[std] / identifier[std] keyword[return] identifier[eta]
def get_eta(self, mag, std): """ Return Eta feature. Parameters ---------- mag : array_like An array of magnitudes. std : array_like A standard deviation of magnitudes. Returns ------- eta : float The value of Eta index. """ diff = mag[1:] - mag[:len(mag) - 1] eta = np.sum(diff * diff) / (len(mag) - 1.0) / std / std return eta
def organizations(self, organization, include=None): """ Retrieve the tickets for this organization. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param organization: Organization object or id """ return self._query_zendesk(self.endpoint.organizations, 'ticket', id=organization, include=include)
def function[organizations, parameter[self, organization, include]]: constant[ Retrieve the tickets for this organization. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param organization: Organization object or id ] return[call[name[self]._query_zendesk, parameter[name[self].endpoint.organizations, constant[ticket]]]]
keyword[def] identifier[organizations] ( identifier[self] , identifier[organization] , identifier[include] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[_query_zendesk] ( identifier[self] . identifier[endpoint] . identifier[organizations] , literal[string] , identifier[id] = identifier[organization] , identifier[include] = identifier[include] )
def organizations(self, organization, include=None): """ Retrieve the tickets for this organization. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param organization: Organization object or id """ return self._query_zendesk(self.endpoint.organizations, 'ticket', id=organization, include=include)
def amplitude_from_frequencyseries(htilde): """Returns the amplitude of the given frequency-domain waveform as a FrequencySeries. Parameters ---------- htilde : FrequencySeries The waveform to get the amplitude of. Returns ------- FrequencySeries The amplitude of the waveform as a function of frequency. """ amp = abs(htilde.data).astype(real_same_precision_as(htilde)) return FrequencySeries(amp, delta_f=htilde.delta_f, epoch=htilde.epoch, copy=False)
def function[amplitude_from_frequencyseries, parameter[htilde]]: constant[Returns the amplitude of the given frequency-domain waveform as a FrequencySeries. Parameters ---------- htilde : FrequencySeries The waveform to get the amplitude of. Returns ------- FrequencySeries The amplitude of the waveform as a function of frequency. ] variable[amp] assign[=] call[call[name[abs], parameter[name[htilde].data]].astype, parameter[call[name[real_same_precision_as], parameter[name[htilde]]]]] return[call[name[FrequencySeries], parameter[name[amp]]]]
keyword[def] identifier[amplitude_from_frequencyseries] ( identifier[htilde] ): literal[string] identifier[amp] = identifier[abs] ( identifier[htilde] . identifier[data] ). identifier[astype] ( identifier[real_same_precision_as] ( identifier[htilde] )) keyword[return] identifier[FrequencySeries] ( identifier[amp] , identifier[delta_f] = identifier[htilde] . identifier[delta_f] , identifier[epoch] = identifier[htilde] . identifier[epoch] , identifier[copy] = keyword[False] )
def amplitude_from_frequencyseries(htilde): """Returns the amplitude of the given frequency-domain waveform as a FrequencySeries. Parameters ---------- htilde : FrequencySeries The waveform to get the amplitude of. Returns ------- FrequencySeries The amplitude of the waveform as a function of frequency. """ amp = abs(htilde.data).astype(real_same_precision_as(htilde)) return FrequencySeries(amp, delta_f=htilde.delta_f, epoch=htilde.epoch, copy=False)
def _geocode(self, pq): """ :arg PlaceQuery pq: PlaceQuery object to use for geocoding :returns: list of location Candidates """ #: List of desired output fields #: See `ESRI docs <https://developers.arcgis.com/rest/geocode/api-reference/geocoding-geocode-addresses.htm>_` for details outFields = ('Loc_name', # 'Shape', 'Score', 'Match_addr', # based on address standards for the country # 'Address', # returned by default # 'Country' # 3-digit ISO 3166-1 code for a country. Example: Canada = "CAN" # 'Admin', # 'DepAdmin', # 'SubAdmin', # 'Locality', # 'Postal', # 'PostalExt', 'Addr_type', # 'Type', # 'Rank', 'AddNum', 'StPreDir', 'StPreType', 'StName', 'StType', 'StDir', # 'Side', # 'AddNumFrom', # 'AddNumTo', # 'AddBldg', 'City', 'Subregion', 'Region', 'Postal', 'Country', # 'Ymax', # 'Ymin', # 'Xmin', # 'Xmax', # 'X', # 'Y', 'DisplayX', 'DisplayY', # 'LangCode', # 'Status', ) outFields = ','.join(outFields) query = dict(f='json', # default HTML. Other options are JSON and KMZ. outFields=outFields, # outSR=WKID, defaults to 4326 maxLocations=20, # default 1; max is 20 ) # Postal-code only searches work in the single-line but not multipart geocoder # Remember that with the default postprocessors, postcode-level results will be eliminated if pq.query == pq.address == '' and pq.postal != '': pq.query = pq.postal if pq.query == '': # multipart query = dict(query, Address=pq.address, # commonly represents the house number and street name of a complete address Neighborhood=pq.neighborhood, City=pq.city, Subregion=pq.subregion, Region=pq.state, Postal=pq.postal, # PostalExt= CountryCode=pq.country, # full country name or ISO 3166-1 2- or 3-digit country code ) else: # single-line magic_key = pq.key if hasattr(pq, 'key') else '' query = dict(query, singleLine=pq.query, # This can be a street address, place name, postal code, or POI. sourceCountry=pq.country, # full country name or ISO 3166-1 2- or 3-digit country code ) if magic_key: query['magicKey'] = magic_key # This is a lookup key returned from the suggest endpoint. if pq.bounded and pq.viewbox is not None: query = dict(query, searchExtent=pq.viewbox.to_esri_wgs_json()) if self._authenticated: if self._token is None or self._token_expiration < datetime.utcnow(): expiration = timedelta(hours=2) self._token = self.get_token(expiration) self._token_expiration = datetime.utcnow() + expiration query['token'] = self._token if getattr(pq, 'for_storage', False): query['forStorage'] = 'true' endpoint = self._endpoint + '/findAddressCandidates' response_obj = self._get_json_obj(endpoint, query) returned_candidates = [] # this will be the list returned try: locations = response_obj['candidates'] for location in locations: c = Candidate() attributes = location['attributes'] c.match_addr = attributes['Match_addr'] c.locator = attributes['Loc_name'] c.locator_type = attributes['Addr_type'] c.score = attributes['Score'] c.x = attributes['DisplayX'] # represents the actual location of the address. c.y = attributes['DisplayY'] c.wkid = response_obj['spatialReference']['wkid'] c.geoservice = self.__class__.__name__ # Optional address component fields. for in_key, out_key in [('City', 'match_city'), ('Subregion', 'match_subregion'), ('Region', 'match_region'), ('Postal', 'match_postal'), ('Country', 'match_country')]: setattr(c, out_key, attributes.get(in_key, '')) setattr(c, 'match_streetaddr', self._street_addr_from_response(attributes)) returned_candidates.append(c) except KeyError: pass return returned_candidates
def function[_geocode, parameter[self, pq]]: constant[ :arg PlaceQuery pq: PlaceQuery object to use for geocoding :returns: list of location Candidates ] variable[outFields] assign[=] tuple[[<ast.Constant object at 0x7da20c796440>, <ast.Constant object at 0x7da20c796b00>, <ast.Constant object at 0x7da20c794a00>, <ast.Constant object at 0x7da20c7952a0>, <ast.Constant object at 0x7da20c795000>, <ast.Constant object at 0x7da20c796890>, <ast.Constant object at 0x7da20c795480>, <ast.Constant object at 0x7da20c796140>, <ast.Constant object at 0x7da20c794e20>, <ast.Constant object at 0x7da20c794c40>, <ast.Constant object at 0x7da20c7961d0>, <ast.Constant object at 0x7da20c796050>, <ast.Constant object at 0x7da20c7954b0>, <ast.Constant object at 0x7da20c7969e0>, <ast.Constant object at 0x7da20c794eb0>, <ast.Constant object at 0x7da20c795c90>, <ast.Constant object at 0x7da20c795bd0>]] variable[outFields] assign[=] call[constant[,].join, parameter[name[outFields]]] variable[query] assign[=] call[name[dict], parameter[]] if <ast.BoolOp object at 0x7da20c794430> begin[:] name[pq].query assign[=] name[pq].postal if compare[name[pq].query equal[==] constant[]] begin[:] variable[query] assign[=] call[name[dict], parameter[name[query]]] if <ast.BoolOp object at 0x7da20c794cd0> begin[:] variable[query] assign[=] call[name[dict], parameter[name[query]]] if name[self]._authenticated begin[:] if <ast.BoolOp object at 0x7da20c794bb0> begin[:] variable[expiration] assign[=] call[name[timedelta], parameter[]] name[self]._token assign[=] call[name[self].get_token, parameter[name[expiration]]] name[self]._token_expiration assign[=] binary_operation[call[name[datetime].utcnow, parameter[]] + name[expiration]] call[name[query]][constant[token]] assign[=] name[self]._token if call[name[getattr], parameter[name[pq], constant[for_storage], constant[False]]] begin[:] call[name[query]][constant[forStorage]] assign[=] constant[true] variable[endpoint] assign[=] binary_operation[name[self]._endpoint + constant[/findAddressCandidates]] variable[response_obj] assign[=] call[name[self]._get_json_obj, parameter[name[endpoint], name[query]]] variable[returned_candidates] assign[=] list[[]] <ast.Try object at 0x7da20c991d20> return[name[returned_candidates]]
keyword[def] identifier[_geocode] ( identifier[self] , identifier[pq] ): literal[string] identifier[outFields] =( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , ) identifier[outFields] = literal[string] . identifier[join] ( identifier[outFields] ) identifier[query] = identifier[dict] ( identifier[f] = literal[string] , identifier[outFields] = identifier[outFields] , identifier[maxLocations] = literal[int] , ) keyword[if] identifier[pq] . identifier[query] == identifier[pq] . identifier[address] == literal[string] keyword[and] identifier[pq] . identifier[postal] != literal[string] : identifier[pq] . identifier[query] = identifier[pq] . identifier[postal] keyword[if] identifier[pq] . identifier[query] == literal[string] : identifier[query] = identifier[dict] ( identifier[query] , identifier[Address] = identifier[pq] . identifier[address] , identifier[Neighborhood] = identifier[pq] . identifier[neighborhood] , identifier[City] = identifier[pq] . identifier[city] , identifier[Subregion] = identifier[pq] . identifier[subregion] , identifier[Region] = identifier[pq] . identifier[state] , identifier[Postal] = identifier[pq] . identifier[postal] , identifier[CountryCode] = identifier[pq] . identifier[country] , ) keyword[else] : identifier[magic_key] = identifier[pq] . identifier[key] keyword[if] identifier[hasattr] ( identifier[pq] , literal[string] ) keyword[else] literal[string] identifier[query] = identifier[dict] ( identifier[query] , identifier[singleLine] = identifier[pq] . identifier[query] , identifier[sourceCountry] = identifier[pq] . identifier[country] , ) keyword[if] identifier[magic_key] : identifier[query] [ literal[string] ]= identifier[magic_key] keyword[if] identifier[pq] . identifier[bounded] keyword[and] identifier[pq] . identifier[viewbox] keyword[is] keyword[not] keyword[None] : identifier[query] = identifier[dict] ( identifier[query] , identifier[searchExtent] = identifier[pq] . identifier[viewbox] . identifier[to_esri_wgs_json] ()) keyword[if] identifier[self] . identifier[_authenticated] : keyword[if] identifier[self] . identifier[_token] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[_token_expiration] < identifier[datetime] . identifier[utcnow] (): identifier[expiration] = identifier[timedelta] ( identifier[hours] = literal[int] ) identifier[self] . identifier[_token] = identifier[self] . identifier[get_token] ( identifier[expiration] ) identifier[self] . identifier[_token_expiration] = identifier[datetime] . identifier[utcnow] ()+ identifier[expiration] identifier[query] [ literal[string] ]= identifier[self] . identifier[_token] keyword[if] identifier[getattr] ( identifier[pq] , literal[string] , keyword[False] ): identifier[query] [ literal[string] ]= literal[string] identifier[endpoint] = identifier[self] . identifier[_endpoint] + literal[string] identifier[response_obj] = identifier[self] . identifier[_get_json_obj] ( identifier[endpoint] , identifier[query] ) identifier[returned_candidates] =[] keyword[try] : identifier[locations] = identifier[response_obj] [ literal[string] ] keyword[for] identifier[location] keyword[in] identifier[locations] : identifier[c] = identifier[Candidate] () identifier[attributes] = identifier[location] [ literal[string] ] identifier[c] . identifier[match_addr] = identifier[attributes] [ literal[string] ] identifier[c] . identifier[locator] = identifier[attributes] [ literal[string] ] identifier[c] . identifier[locator_type] = identifier[attributes] [ literal[string] ] identifier[c] . identifier[score] = identifier[attributes] [ literal[string] ] identifier[c] . identifier[x] = identifier[attributes] [ literal[string] ] identifier[c] . identifier[y] = identifier[attributes] [ literal[string] ] identifier[c] . identifier[wkid] = identifier[response_obj] [ literal[string] ][ literal[string] ] identifier[c] . identifier[geoservice] = identifier[self] . identifier[__class__] . identifier[__name__] keyword[for] identifier[in_key] , identifier[out_key] keyword[in] [( literal[string] , literal[string] ),( literal[string] , literal[string] ), ( literal[string] , literal[string] ),( literal[string] , literal[string] ), ( literal[string] , literal[string] )]: identifier[setattr] ( identifier[c] , identifier[out_key] , identifier[attributes] . identifier[get] ( identifier[in_key] , literal[string] )) identifier[setattr] ( identifier[c] , literal[string] , identifier[self] . identifier[_street_addr_from_response] ( identifier[attributes] )) identifier[returned_candidates] . identifier[append] ( identifier[c] ) keyword[except] identifier[KeyError] : keyword[pass] keyword[return] identifier[returned_candidates]
def _geocode(self, pq): """ :arg PlaceQuery pq: PlaceQuery object to use for geocoding :returns: list of location Candidates """ #: List of desired output fields #: See `ESRI docs <https://developers.arcgis.com/rest/geocode/api-reference/geocoding-geocode-addresses.htm>_` for details # 'Shape', # based on address standards for the country # 'Address', # returned by default # 'Country' # 3-digit ISO 3166-1 code for a country. Example: Canada = "CAN" # 'Admin', # 'DepAdmin', # 'SubAdmin', # 'Locality', # 'Postal', # 'PostalExt', # 'Type', # 'Rank', # 'Side', # 'AddNumFrom', # 'AddNumTo', # 'AddBldg', # 'Ymax', # 'Ymin', # 'Xmin', # 'Xmax', # 'X', # 'Y', # 'LangCode', # 'Status', outFields = ('Loc_name', 'Score', 'Match_addr', 'Addr_type', 'AddNum', 'StPreDir', 'StPreType', 'StName', 'StType', 'StDir', 'City', 'Subregion', 'Region', 'Postal', 'Country', 'DisplayX', 'DisplayY') outFields = ','.join(outFields) # default HTML. Other options are JSON and KMZ. # outSR=WKID, defaults to 4326 # default 1; max is 20 query = dict(f='json', outFields=outFields, maxLocations=20) # Postal-code only searches work in the single-line but not multipart geocoder # Remember that with the default postprocessors, postcode-level results will be eliminated if pq.query == pq.address == '' and pq.postal != '': pq.query = pq.postal # depends on [control=['if'], data=[]] if pq.query == '': # multipart # commonly represents the house number and street name of a complete address # PostalExt= # full country name or ISO 3166-1 2- or 3-digit country code query = dict(query, Address=pq.address, Neighborhood=pq.neighborhood, City=pq.city, Subregion=pq.subregion, Region=pq.state, Postal=pq.postal, CountryCode=pq.country) # depends on [control=['if'], data=[]] else: # single-line magic_key = pq.key if hasattr(pq, 'key') else '' # This can be a street address, place name, postal code, or POI. # full country name or ISO 3166-1 2- or 3-digit country code query = dict(query, singleLine=pq.query, sourceCountry=pq.country) if magic_key: query['magicKey'] = magic_key # This is a lookup key returned from the suggest endpoint. # depends on [control=['if'], data=[]] if pq.bounded and pq.viewbox is not None: query = dict(query, searchExtent=pq.viewbox.to_esri_wgs_json()) # depends on [control=['if'], data=[]] if self._authenticated: if self._token is None or self._token_expiration < datetime.utcnow(): expiration = timedelta(hours=2) self._token = self.get_token(expiration) self._token_expiration = datetime.utcnow() + expiration # depends on [control=['if'], data=[]] query['token'] = self._token # depends on [control=['if'], data=[]] if getattr(pq, 'for_storage', False): query['forStorage'] = 'true' # depends on [control=['if'], data=[]] endpoint = self._endpoint + '/findAddressCandidates' response_obj = self._get_json_obj(endpoint, query) returned_candidates = [] # this will be the list returned try: locations = response_obj['candidates'] for location in locations: c = Candidate() attributes = location['attributes'] c.match_addr = attributes['Match_addr'] c.locator = attributes['Loc_name'] c.locator_type = attributes['Addr_type'] c.score = attributes['Score'] c.x = attributes['DisplayX'] # represents the actual location of the address. c.y = attributes['DisplayY'] c.wkid = response_obj['spatialReference']['wkid'] c.geoservice = self.__class__.__name__ # Optional address component fields. for (in_key, out_key) in [('City', 'match_city'), ('Subregion', 'match_subregion'), ('Region', 'match_region'), ('Postal', 'match_postal'), ('Country', 'match_country')]: setattr(c, out_key, attributes.get(in_key, '')) # depends on [control=['for'], data=[]] setattr(c, 'match_streetaddr', self._street_addr_from_response(attributes)) returned_candidates.append(c) # depends on [control=['for'], data=['location']] # depends on [control=['try'], data=[]] except KeyError: pass # depends on [control=['except'], data=[]] return returned_candidates
def create_cluster(settings): """ Creates a new Nydus cluster from the given settings. :param settings: Dictionary of the cluster settings. :returns: Configured instance of ``nydus.db.base.Cluster``. >>> redis = create_cluster({ >>> 'backend': 'nydus.db.backends.redis.Redis', >>> 'router': 'nydus.db.routers.redis.PartitionRouter', >>> 'defaults': { >>> 'host': 'localhost', >>> 'port': 6379, >>> }, >>> 'hosts': { >>> 0: {'db': 0}, >>> 1: {'db': 1}, >>> 2: {'db': 2}, >>> } >>> }) """ # Pull in our client settings = copy.deepcopy(settings) backend = settings.pop('engine', settings.pop('backend', None)) if isinstance(backend, basestring): Conn = import_string(backend) elif backend: Conn = backend else: raise KeyError('backend') # Pull in our cluster cluster = settings.pop('cluster', None) if not cluster: Cluster = Conn.get_cluster() elif isinstance(cluster, basestring): Cluster = import_string(cluster) else: Cluster = cluster # Pull in our router router = settings.pop('router', None) if not router: Router = BaseRouter elif isinstance(router, basestring): Router = import_string(router) else: Router = router # Build the connection cluster return Cluster( router=Router, backend=Conn, **settings )
def function[create_cluster, parameter[settings]]: constant[ Creates a new Nydus cluster from the given settings. :param settings: Dictionary of the cluster settings. :returns: Configured instance of ``nydus.db.base.Cluster``. >>> redis = create_cluster({ >>> 'backend': 'nydus.db.backends.redis.Redis', >>> 'router': 'nydus.db.routers.redis.PartitionRouter', >>> 'defaults': { >>> 'host': 'localhost', >>> 'port': 6379, >>> }, >>> 'hosts': { >>> 0: {'db': 0}, >>> 1: {'db': 1}, >>> 2: {'db': 2}, >>> } >>> }) ] variable[settings] assign[=] call[name[copy].deepcopy, parameter[name[settings]]] variable[backend] assign[=] call[name[settings].pop, parameter[constant[engine], call[name[settings].pop, parameter[constant[backend], constant[None]]]]] if call[name[isinstance], parameter[name[backend], name[basestring]]] begin[:] variable[Conn] assign[=] call[name[import_string], parameter[name[backend]]] variable[cluster] assign[=] call[name[settings].pop, parameter[constant[cluster], constant[None]]] if <ast.UnaryOp object at 0x7da2054a5720> begin[:] variable[Cluster] assign[=] call[name[Conn].get_cluster, parameter[]] variable[router] assign[=] call[name[settings].pop, parameter[constant[router], constant[None]]] if <ast.UnaryOp object at 0x7da2054a5c00> begin[:] variable[Router] assign[=] name[BaseRouter] return[call[name[Cluster], parameter[]]]
keyword[def] identifier[create_cluster] ( identifier[settings] ): literal[string] identifier[settings] = identifier[copy] . identifier[deepcopy] ( identifier[settings] ) identifier[backend] = identifier[settings] . identifier[pop] ( literal[string] , identifier[settings] . identifier[pop] ( literal[string] , keyword[None] )) keyword[if] identifier[isinstance] ( identifier[backend] , identifier[basestring] ): identifier[Conn] = identifier[import_string] ( identifier[backend] ) keyword[elif] identifier[backend] : identifier[Conn] = identifier[backend] keyword[else] : keyword[raise] identifier[KeyError] ( literal[string] ) identifier[cluster] = identifier[settings] . identifier[pop] ( literal[string] , keyword[None] ) keyword[if] keyword[not] identifier[cluster] : identifier[Cluster] = identifier[Conn] . identifier[get_cluster] () keyword[elif] identifier[isinstance] ( identifier[cluster] , identifier[basestring] ): identifier[Cluster] = identifier[import_string] ( identifier[cluster] ) keyword[else] : identifier[Cluster] = identifier[cluster] identifier[router] = identifier[settings] . identifier[pop] ( literal[string] , keyword[None] ) keyword[if] keyword[not] identifier[router] : identifier[Router] = identifier[BaseRouter] keyword[elif] identifier[isinstance] ( identifier[router] , identifier[basestring] ): identifier[Router] = identifier[import_string] ( identifier[router] ) keyword[else] : identifier[Router] = identifier[router] keyword[return] identifier[Cluster] ( identifier[router] = identifier[Router] , identifier[backend] = identifier[Conn] , ** identifier[settings] )
def create_cluster(settings): """ Creates a new Nydus cluster from the given settings. :param settings: Dictionary of the cluster settings. :returns: Configured instance of ``nydus.db.base.Cluster``. >>> redis = create_cluster({ >>> 'backend': 'nydus.db.backends.redis.Redis', >>> 'router': 'nydus.db.routers.redis.PartitionRouter', >>> 'defaults': { >>> 'host': 'localhost', >>> 'port': 6379, >>> }, >>> 'hosts': { >>> 0: {'db': 0}, >>> 1: {'db': 1}, >>> 2: {'db': 2}, >>> } >>> }) """ # Pull in our client settings = copy.deepcopy(settings) backend = settings.pop('engine', settings.pop('backend', None)) if isinstance(backend, basestring): Conn = import_string(backend) # depends on [control=['if'], data=[]] elif backend: Conn = backend # depends on [control=['if'], data=[]] else: raise KeyError('backend') # Pull in our cluster cluster = settings.pop('cluster', None) if not cluster: Cluster = Conn.get_cluster() # depends on [control=['if'], data=[]] elif isinstance(cluster, basestring): Cluster = import_string(cluster) # depends on [control=['if'], data=[]] else: Cluster = cluster # Pull in our router router = settings.pop('router', None) if not router: Router = BaseRouter # depends on [control=['if'], data=[]] elif isinstance(router, basestring): Router = import_string(router) # depends on [control=['if'], data=[]] else: Router = router # Build the connection cluster return Cluster(router=Router, backend=Conn, **settings)
def _substitute(self, var_map, safe=False): """Implementation of :meth:`substitute`. For internal use, the `safe` keyword argument allows to perform a substitution on the `args` and `kwargs` of the expression only, guaranteeing that the type of the expression does not change, at the cost of possibly not returning a maximally simplified expression. The `safe` keyword is not handled recursively, i.e. any `args`/`kwargs` will be fully simplified, possibly changing their types. """ if self in var_map: if not safe or (type(var_map[self]) == type(self)): return var_map[self] if isinstance(self.__class__, Singleton): return self new_args = [substitute(arg, var_map) for arg in self.args] new_kwargs = {key: substitute(val, var_map) for (key, val) in self.kwargs.items()} if safe: return self.__class__(*new_args, **new_kwargs) else: return self.create(*new_args, **new_kwargs)
def function[_substitute, parameter[self, var_map, safe]]: constant[Implementation of :meth:`substitute`. For internal use, the `safe` keyword argument allows to perform a substitution on the `args` and `kwargs` of the expression only, guaranteeing that the type of the expression does not change, at the cost of possibly not returning a maximally simplified expression. The `safe` keyword is not handled recursively, i.e. any `args`/`kwargs` will be fully simplified, possibly changing their types. ] if compare[name[self] in name[var_map]] begin[:] if <ast.BoolOp object at 0x7da20c6ab9a0> begin[:] return[call[name[var_map]][name[self]]] if call[name[isinstance], parameter[name[self].__class__, name[Singleton]]] begin[:] return[name[self]] variable[new_args] assign[=] <ast.ListComp object at 0x7da20c6a9660> variable[new_kwargs] assign[=] <ast.DictComp object at 0x7da20c6ab850> if name[safe] begin[:] return[call[name[self].__class__, parameter[<ast.Starred object at 0x7da18c4cc6d0>]]]
keyword[def] identifier[_substitute] ( identifier[self] , identifier[var_map] , identifier[safe] = keyword[False] ): literal[string] keyword[if] identifier[self] keyword[in] identifier[var_map] : keyword[if] keyword[not] identifier[safe] keyword[or] ( identifier[type] ( identifier[var_map] [ identifier[self] ])== identifier[type] ( identifier[self] )): keyword[return] identifier[var_map] [ identifier[self] ] keyword[if] identifier[isinstance] ( identifier[self] . identifier[__class__] , identifier[Singleton] ): keyword[return] identifier[self] identifier[new_args] =[ identifier[substitute] ( identifier[arg] , identifier[var_map] ) keyword[for] identifier[arg] keyword[in] identifier[self] . identifier[args] ] identifier[new_kwargs] ={ identifier[key] : identifier[substitute] ( identifier[val] , identifier[var_map] ) keyword[for] ( identifier[key] , identifier[val] ) keyword[in] identifier[self] . identifier[kwargs] . identifier[items] ()} keyword[if] identifier[safe] : keyword[return] identifier[self] . identifier[__class__] (* identifier[new_args] ,** identifier[new_kwargs] ) keyword[else] : keyword[return] identifier[self] . identifier[create] (* identifier[new_args] ,** identifier[new_kwargs] )
def _substitute(self, var_map, safe=False): """Implementation of :meth:`substitute`. For internal use, the `safe` keyword argument allows to perform a substitution on the `args` and `kwargs` of the expression only, guaranteeing that the type of the expression does not change, at the cost of possibly not returning a maximally simplified expression. The `safe` keyword is not handled recursively, i.e. any `args`/`kwargs` will be fully simplified, possibly changing their types. """ if self in var_map: if not safe or type(var_map[self]) == type(self): return var_map[self] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['self', 'var_map']] if isinstance(self.__class__, Singleton): return self # depends on [control=['if'], data=[]] new_args = [substitute(arg, var_map) for arg in self.args] new_kwargs = {key: substitute(val, var_map) for (key, val) in self.kwargs.items()} if safe: return self.__class__(*new_args, **new_kwargs) # depends on [control=['if'], data=[]] else: return self.create(*new_args, **new_kwargs)
def model_to_dict(instance, **options): "Takes a model instance and converts it into a dict." options = _defaults(options) attrs = {} if options['prehook']: if isinstance(options['prehook'], collections.Callable): instance = options['prehook'](instance) if instance is None: return attrs # Items in the `fields` list are the output aliases, not the raw # accessors (field, method, property names) for alias in options['fields']: # Get the accessor for the object accessor = options['aliases'].get(alias, alias) # Create the key that will be used in the output dict key = options['prefix'] + alias # Optionally camelcase the key if options['camelcase']: key = convert_to_camel(key) # Get the field value. Use the mapped value to the actually property or # method name. `value` may be a number of things, so the various types # are checked below. value = get_field_value(instance, accessor, allow_missing=options['allow_missing']) # Related objects, perform some checks on their options if isinstance(value, (models.Model, QuerySet)): _options = _defaults(options['related'].get(accessor, {})) # If the `prefix` follows the below template, generate the # `prefix` for the related object if '%(accessor)s' in _options['prefix']: _options['prefix'] = _options['prefix'] % {'accessor': alias} if isinstance(value, models.Model): if len(_options['fields']) == 1 and _options['flat'] \ and not _options['merge']: value = list(serialize(value, **_options).values())[0] else: # Recurse, get the dict representation _attrs = serialize(value, **_options) # Check if this object should be merged into the parent, # otherwise nest it under the accessor name if _options['merge']: attrs.update(_attrs) continue value = _attrs else: value = serialize(value, **_options) attrs[key] = value # Apply post-hook to serialized attributes if options['posthook']: attrs = options['posthook'](instance, attrs) return attrs
def function[model_to_dict, parameter[instance]]: constant[Takes a model instance and converts it into a dict.] variable[options] assign[=] call[name[_defaults], parameter[name[options]]] variable[attrs] assign[=] dictionary[[], []] if call[name[options]][constant[prehook]] begin[:] if call[name[isinstance], parameter[call[name[options]][constant[prehook]], name[collections].Callable]] begin[:] variable[instance] assign[=] call[call[name[options]][constant[prehook]], parameter[name[instance]]] if compare[name[instance] is constant[None]] begin[:] return[name[attrs]] for taget[name[alias]] in starred[call[name[options]][constant[fields]]] begin[:] variable[accessor] assign[=] call[call[name[options]][constant[aliases]].get, parameter[name[alias], name[alias]]] variable[key] assign[=] binary_operation[call[name[options]][constant[prefix]] + name[alias]] if call[name[options]][constant[camelcase]] begin[:] variable[key] assign[=] call[name[convert_to_camel], parameter[name[key]]] variable[value] assign[=] call[name[get_field_value], parameter[name[instance], name[accessor]]] if call[name[isinstance], parameter[name[value], tuple[[<ast.Attribute object at 0x7da1b255e860>, <ast.Name object at 0x7da1b255d9f0>]]]] begin[:] variable[_options] assign[=] call[name[_defaults], parameter[call[call[name[options]][constant[related]].get, parameter[name[accessor], dictionary[[], []]]]]] if compare[constant[%(accessor)s] in call[name[_options]][constant[prefix]]] begin[:] call[name[_options]][constant[prefix]] assign[=] binary_operation[call[name[_options]][constant[prefix]] <ast.Mod object at 0x7da2590d6920> dictionary[[<ast.Constant object at 0x7da1b255c100>], [<ast.Name object at 0x7da1b255dc00>]]] if call[name[isinstance], parameter[name[value], name[models].Model]] begin[:] if <ast.BoolOp object at 0x7da1b255db40> begin[:] variable[value] assign[=] call[call[name[list], parameter[call[call[name[serialize], parameter[name[value]]].values, parameter[]]]]][constant[0]] call[name[attrs]][name[key]] assign[=] name[value] if call[name[options]][constant[posthook]] begin[:] variable[attrs] assign[=] call[call[name[options]][constant[posthook]], parameter[name[instance], name[attrs]]] return[name[attrs]]
keyword[def] identifier[model_to_dict] ( identifier[instance] ,** identifier[options] ): literal[string] identifier[options] = identifier[_defaults] ( identifier[options] ) identifier[attrs] ={} keyword[if] identifier[options] [ literal[string] ]: keyword[if] identifier[isinstance] ( identifier[options] [ literal[string] ], identifier[collections] . identifier[Callable] ): identifier[instance] = identifier[options] [ literal[string] ]( identifier[instance] ) keyword[if] identifier[instance] keyword[is] keyword[None] : keyword[return] identifier[attrs] keyword[for] identifier[alias] keyword[in] identifier[options] [ literal[string] ]: identifier[accessor] = identifier[options] [ literal[string] ]. identifier[get] ( identifier[alias] , identifier[alias] ) identifier[key] = identifier[options] [ literal[string] ]+ identifier[alias] keyword[if] identifier[options] [ literal[string] ]: identifier[key] = identifier[convert_to_camel] ( identifier[key] ) identifier[value] = identifier[get_field_value] ( identifier[instance] , identifier[accessor] , identifier[allow_missing] = identifier[options] [ literal[string] ]) keyword[if] identifier[isinstance] ( identifier[value] ,( identifier[models] . identifier[Model] , identifier[QuerySet] )): identifier[_options] = identifier[_defaults] ( identifier[options] [ literal[string] ]. identifier[get] ( identifier[accessor] ,{})) keyword[if] literal[string] keyword[in] identifier[_options] [ literal[string] ]: identifier[_options] [ literal[string] ]= identifier[_options] [ literal[string] ]%{ literal[string] : identifier[alias] } keyword[if] identifier[isinstance] ( identifier[value] , identifier[models] . identifier[Model] ): keyword[if] identifier[len] ( identifier[_options] [ literal[string] ])== literal[int] keyword[and] identifier[_options] [ literal[string] ] keyword[and] keyword[not] identifier[_options] [ literal[string] ]: identifier[value] = identifier[list] ( identifier[serialize] ( identifier[value] ,** identifier[_options] ). identifier[values] ())[ literal[int] ] keyword[else] : identifier[_attrs] = identifier[serialize] ( identifier[value] ,** identifier[_options] ) keyword[if] identifier[_options] [ literal[string] ]: identifier[attrs] . identifier[update] ( identifier[_attrs] ) keyword[continue] identifier[value] = identifier[_attrs] keyword[else] : identifier[value] = identifier[serialize] ( identifier[value] ,** identifier[_options] ) identifier[attrs] [ identifier[key] ]= identifier[value] keyword[if] identifier[options] [ literal[string] ]: identifier[attrs] = identifier[options] [ literal[string] ]( identifier[instance] , identifier[attrs] ) keyword[return] identifier[attrs]
def model_to_dict(instance, **options): """Takes a model instance and converts it into a dict.""" options = _defaults(options) attrs = {} if options['prehook']: if isinstance(options['prehook'], collections.Callable): instance = options['prehook'](instance) if instance is None: return attrs # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # Items in the `fields` list are the output aliases, not the raw # accessors (field, method, property names) for alias in options['fields']: # Get the accessor for the object accessor = options['aliases'].get(alias, alias) # Create the key that will be used in the output dict key = options['prefix'] + alias # Optionally camelcase the key if options['camelcase']: key = convert_to_camel(key) # depends on [control=['if'], data=[]] # Get the field value. Use the mapped value to the actually property or # method name. `value` may be a number of things, so the various types # are checked below. value = get_field_value(instance, accessor, allow_missing=options['allow_missing']) # Related objects, perform some checks on their options if isinstance(value, (models.Model, QuerySet)): _options = _defaults(options['related'].get(accessor, {})) # If the `prefix` follows the below template, generate the # `prefix` for the related object if '%(accessor)s' in _options['prefix']: _options['prefix'] = _options['prefix'] % {'accessor': alias} # depends on [control=['if'], data=[]] if isinstance(value, models.Model): if len(_options['fields']) == 1 and _options['flat'] and (not _options['merge']): value = list(serialize(value, **_options).values())[0] # depends on [control=['if'], data=[]] else: # Recurse, get the dict representation _attrs = serialize(value, **_options) # Check if this object should be merged into the parent, # otherwise nest it under the accessor name if _options['merge']: attrs.update(_attrs) continue # depends on [control=['if'], data=[]] value = _attrs # depends on [control=['if'], data=[]] else: value = serialize(value, **_options) # depends on [control=['if'], data=[]] attrs[key] = value # depends on [control=['for'], data=['alias']] # Apply post-hook to serialized attributes if options['posthook']: attrs = options['posthook'](instance, attrs) # depends on [control=['if'], data=[]] return attrs
def load_projections(folder, indices=None): """Load geometry and data stored in Mayo format from folder. Parameters ---------- folder : str Path to the folder where the Mayo DICOM files are stored. indices : optional Indices of the projections to load. Accepts advanced indexing such as slice or list of indices. Returns ------- geometry : ConeFlatGeometry Geometry corresponding to the Mayo projector. proj_data : `numpy.ndarray` Projection data, given as the line integral of the linear attenuation coefficient (g/cm^3). Its unit is thus g/cm^2. """ datasets, data_array = _read_projections(folder, indices) # Get the angles angles = [d.DetectorFocalCenterAngularPosition for d in datasets] angles = -np.unwrap(angles) - np.pi # different defintion of angles # Set minimum and maximum corners shape = np.array([datasets[0].NumberofDetectorColumns, datasets[0].NumberofDetectorRows]) pixel_size = np.array([datasets[0].DetectorElementTransverseSpacing, datasets[0].DetectorElementAxialSpacing]) # Correct from center of pixel to corner of pixel minp = -(np.array(datasets[0].DetectorCentralElement) - 0.5) * pixel_size maxp = minp + shape * pixel_size # Select geometry parameters src_radius = datasets[0].DetectorFocalCenterRadialDistance det_radius = (datasets[0].ConstantRadialDistance - datasets[0].DetectorFocalCenterRadialDistance) # For unknown reasons, mayo does not include the tag # "TableFeedPerRotation", which is what we want. # Instead we manually compute the pitch pitch = ((datasets[-1].DetectorFocalCenterAxialPosition - datasets[0].DetectorFocalCenterAxialPosition) / ((np.max(angles) - np.min(angles)) / (2 * np.pi))) # Get flying focal spot data offset_axial = np.array([d.SourceAxialPositionShift for d in datasets]) offset_angular = np.array([d.SourceAngularPositionShift for d in datasets]) offset_radial = np.array([d.SourceRadialDistanceShift for d in datasets]) # TODO(adler-j): Implement proper handling of flying focal spot. # Currently we do not fully account for it, merely making some "first # order corrections" to the detector position and radial offset. # Update angles with flying focal spot (in plane direction). # This increases the resolution of the reconstructions. angles = angles - offset_angular # We correct for the mean offset due to the rotated angles, we need to # shift the detector. offset_detector_by_angles = det_radius * np.mean(offset_angular) minp[0] -= offset_detector_by_angles maxp[0] -= offset_detector_by_angles # We currently apply only the mean of the offsets src_radius = src_radius + np.mean(offset_radial) # Partially compensate for a movement of the source by moving the object # instead. We need to rescale by the magnification to get the correct # change in the detector. This approximation is only exactly valid on the # axis of rotation. mean_offset_along_axis_for_ffz = np.mean(offset_axial) * ( src_radius / (src_radius + det_radius)) # Create partition for detector detector_partition = odl.uniform_partition(minp, maxp, shape) # Convert offset to odl defintions offset_along_axis = (mean_offset_along_axis_for_ffz + datasets[0].DetectorFocalCenterAxialPosition - angles[0] / (2 * np.pi) * pitch) # Assemble geometry angle_partition = odl.nonuniform_partition(angles) geometry = odl.tomo.ConeFlatGeometry(angle_partition, detector_partition, src_radius=src_radius, det_radius=det_radius, pitch=pitch, offset_along_axis=offset_along_axis) # Create a *temporary* ray transform (we need its range) spc = odl.uniform_discr([-1] * 3, [1] * 3, [32] * 3) ray_trafo = odl.tomo.RayTransform(spc, geometry, interp='linear') # convert coordinates theta, up, vp = ray_trafo.range.grid.meshgrid d = src_radius + det_radius u = d * np.arctan(up / d) v = d / np.sqrt(d**2 + up**2) * vp # Calculate projection data in rectangular coordinates since we have no # backend that supports cylindrical proj_data_cylinder = ray_trafo.range.element(data_array) interpolated_values = proj_data_cylinder.interpolation((theta, u, v)) proj_data = ray_trafo.range.element(interpolated_values) return geometry, proj_data.asarray()
def function[load_projections, parameter[folder, indices]]: constant[Load geometry and data stored in Mayo format from folder. Parameters ---------- folder : str Path to the folder where the Mayo DICOM files are stored. indices : optional Indices of the projections to load. Accepts advanced indexing such as slice or list of indices. Returns ------- geometry : ConeFlatGeometry Geometry corresponding to the Mayo projector. proj_data : `numpy.ndarray` Projection data, given as the line integral of the linear attenuation coefficient (g/cm^3). Its unit is thus g/cm^2. ] <ast.Tuple object at 0x7da18f58de40> assign[=] call[name[_read_projections], parameter[name[folder], name[indices]]] variable[angles] assign[=] <ast.ListComp object at 0x7da18f58f7f0> variable[angles] assign[=] binary_operation[<ast.UnaryOp object at 0x7da18f58d7b0> - name[np].pi] variable[shape] assign[=] call[name[np].array, parameter[list[[<ast.Attribute object at 0x7da18f58f3d0>, <ast.Attribute object at 0x7da18f58eaa0>]]]] variable[pixel_size] assign[=] call[name[np].array, parameter[list[[<ast.Attribute object at 0x7da18f58d4e0>, <ast.Attribute object at 0x7da18f58d390>]]]] variable[minp] assign[=] binary_operation[<ast.UnaryOp object at 0x7da18f58e920> * name[pixel_size]] variable[maxp] assign[=] binary_operation[name[minp] + binary_operation[name[shape] * name[pixel_size]]] variable[src_radius] assign[=] call[name[datasets]][constant[0]].DetectorFocalCenterRadialDistance variable[det_radius] assign[=] binary_operation[call[name[datasets]][constant[0]].ConstantRadialDistance - call[name[datasets]][constant[0]].DetectorFocalCenterRadialDistance] variable[pitch] assign[=] binary_operation[binary_operation[call[name[datasets]][<ast.UnaryOp object at 0x7da1b1e5ac20>].DetectorFocalCenterAxialPosition - call[name[datasets]][constant[0]].DetectorFocalCenterAxialPosition] / binary_operation[binary_operation[call[name[np].max, parameter[name[angles]]] - call[name[np].min, parameter[name[angles]]]] / binary_operation[constant[2] * name[np].pi]]] variable[offset_axial] assign[=] call[name[np].array, parameter[<ast.ListComp object at 0x7da1b1e58550>]] variable[offset_angular] assign[=] call[name[np].array, parameter[<ast.ListComp object at 0x7da1b1e58460>]] variable[offset_radial] assign[=] call[name[np].array, parameter[<ast.ListComp object at 0x7da1b1e58820>]] variable[angles] assign[=] binary_operation[name[angles] - name[offset_angular]] variable[offset_detector_by_angles] assign[=] binary_operation[name[det_radius] * call[name[np].mean, parameter[name[offset_angular]]]] <ast.AugAssign object at 0x7da1b1e595d0> <ast.AugAssign object at 0x7da1b1e59030> variable[src_radius] assign[=] binary_operation[name[src_radius] + call[name[np].mean, parameter[name[offset_radial]]]] variable[mean_offset_along_axis_for_ffz] assign[=] binary_operation[call[name[np].mean, parameter[name[offset_axial]]] * binary_operation[name[src_radius] / binary_operation[name[src_radius] + name[det_radius]]]] variable[detector_partition] assign[=] call[name[odl].uniform_partition, parameter[name[minp], name[maxp], name[shape]]] variable[offset_along_axis] assign[=] binary_operation[binary_operation[name[mean_offset_along_axis_for_ffz] + call[name[datasets]][constant[0]].DetectorFocalCenterAxialPosition] - binary_operation[binary_operation[call[name[angles]][constant[0]] / binary_operation[constant[2] * name[np].pi]] * name[pitch]]] variable[angle_partition] assign[=] call[name[odl].nonuniform_partition, parameter[name[angles]]] variable[geometry] assign[=] call[name[odl].tomo.ConeFlatGeometry, parameter[name[angle_partition], name[detector_partition]]] variable[spc] assign[=] call[name[odl].uniform_discr, parameter[binary_operation[list[[<ast.UnaryOp object at 0x7da1b1d0cac0>]] * constant[3]], binary_operation[list[[<ast.Constant object at 0x7da1b1d0c910>]] * constant[3]], binary_operation[list[[<ast.Constant object at 0x7da1b1d0eda0>]] * constant[3]]]] variable[ray_trafo] assign[=] call[name[odl].tomo.RayTransform, parameter[name[spc], name[geometry]]] <ast.Tuple object at 0x7da1b1e9bc70> assign[=] name[ray_trafo].range.grid.meshgrid variable[d] assign[=] binary_operation[name[src_radius] + name[det_radius]] variable[u] assign[=] binary_operation[name[d] * call[name[np].arctan, parameter[binary_operation[name[up] / name[d]]]]] variable[v] assign[=] binary_operation[binary_operation[name[d] / call[name[np].sqrt, parameter[binary_operation[binary_operation[name[d] ** constant[2]] + binary_operation[name[up] ** constant[2]]]]]] * name[vp]] variable[proj_data_cylinder] assign[=] call[name[ray_trafo].range.element, parameter[name[data_array]]] variable[interpolated_values] assign[=] call[name[proj_data_cylinder].interpolation, parameter[tuple[[<ast.Name object at 0x7da1b1e9b730>, <ast.Name object at 0x7da1b1e98580>, <ast.Name object at 0x7da1b1e983a0>]]]] variable[proj_data] assign[=] call[name[ray_trafo].range.element, parameter[name[interpolated_values]]] return[tuple[[<ast.Name object at 0x7da1b1e9a200>, <ast.Call object at 0x7da1b1e9bc40>]]]
keyword[def] identifier[load_projections] ( identifier[folder] , identifier[indices] = keyword[None] ): literal[string] identifier[datasets] , identifier[data_array] = identifier[_read_projections] ( identifier[folder] , identifier[indices] ) identifier[angles] =[ identifier[d] . identifier[DetectorFocalCenterAngularPosition] keyword[for] identifier[d] keyword[in] identifier[datasets] ] identifier[angles] =- identifier[np] . identifier[unwrap] ( identifier[angles] )- identifier[np] . identifier[pi] identifier[shape] = identifier[np] . identifier[array] ([ identifier[datasets] [ literal[int] ]. identifier[NumberofDetectorColumns] , identifier[datasets] [ literal[int] ]. identifier[NumberofDetectorRows] ]) identifier[pixel_size] = identifier[np] . identifier[array] ([ identifier[datasets] [ literal[int] ]. identifier[DetectorElementTransverseSpacing] , identifier[datasets] [ literal[int] ]. identifier[DetectorElementAxialSpacing] ]) identifier[minp] =-( identifier[np] . identifier[array] ( identifier[datasets] [ literal[int] ]. identifier[DetectorCentralElement] )- literal[int] )* identifier[pixel_size] identifier[maxp] = identifier[minp] + identifier[shape] * identifier[pixel_size] identifier[src_radius] = identifier[datasets] [ literal[int] ]. identifier[DetectorFocalCenterRadialDistance] identifier[det_radius] =( identifier[datasets] [ literal[int] ]. identifier[ConstantRadialDistance] - identifier[datasets] [ literal[int] ]. identifier[DetectorFocalCenterRadialDistance] ) identifier[pitch] =(( identifier[datasets] [- literal[int] ]. identifier[DetectorFocalCenterAxialPosition] - identifier[datasets] [ literal[int] ]. identifier[DetectorFocalCenterAxialPosition] )/ (( identifier[np] . identifier[max] ( identifier[angles] )- identifier[np] . identifier[min] ( identifier[angles] ))/( literal[int] * identifier[np] . identifier[pi] ))) identifier[offset_axial] = identifier[np] . identifier[array] ([ identifier[d] . identifier[SourceAxialPositionShift] keyword[for] identifier[d] keyword[in] identifier[datasets] ]) identifier[offset_angular] = identifier[np] . identifier[array] ([ identifier[d] . identifier[SourceAngularPositionShift] keyword[for] identifier[d] keyword[in] identifier[datasets] ]) identifier[offset_radial] = identifier[np] . identifier[array] ([ identifier[d] . identifier[SourceRadialDistanceShift] keyword[for] identifier[d] keyword[in] identifier[datasets] ]) identifier[angles] = identifier[angles] - identifier[offset_angular] identifier[offset_detector_by_angles] = identifier[det_radius] * identifier[np] . identifier[mean] ( identifier[offset_angular] ) identifier[minp] [ literal[int] ]-= identifier[offset_detector_by_angles] identifier[maxp] [ literal[int] ]-= identifier[offset_detector_by_angles] identifier[src_radius] = identifier[src_radius] + identifier[np] . identifier[mean] ( identifier[offset_radial] ) identifier[mean_offset_along_axis_for_ffz] = identifier[np] . identifier[mean] ( identifier[offset_axial] )*( identifier[src_radius] /( identifier[src_radius] + identifier[det_radius] )) identifier[detector_partition] = identifier[odl] . identifier[uniform_partition] ( identifier[minp] , identifier[maxp] , identifier[shape] ) identifier[offset_along_axis] =( identifier[mean_offset_along_axis_for_ffz] + identifier[datasets] [ literal[int] ]. identifier[DetectorFocalCenterAxialPosition] - identifier[angles] [ literal[int] ]/( literal[int] * identifier[np] . identifier[pi] )* identifier[pitch] ) identifier[angle_partition] = identifier[odl] . identifier[nonuniform_partition] ( identifier[angles] ) identifier[geometry] = identifier[odl] . identifier[tomo] . identifier[ConeFlatGeometry] ( identifier[angle_partition] , identifier[detector_partition] , identifier[src_radius] = identifier[src_radius] , identifier[det_radius] = identifier[det_radius] , identifier[pitch] = identifier[pitch] , identifier[offset_along_axis] = identifier[offset_along_axis] ) identifier[spc] = identifier[odl] . identifier[uniform_discr] ([- literal[int] ]* literal[int] ,[ literal[int] ]* literal[int] ,[ literal[int] ]* literal[int] ) identifier[ray_trafo] = identifier[odl] . identifier[tomo] . identifier[RayTransform] ( identifier[spc] , identifier[geometry] , identifier[interp] = literal[string] ) identifier[theta] , identifier[up] , identifier[vp] = identifier[ray_trafo] . identifier[range] . identifier[grid] . identifier[meshgrid] identifier[d] = identifier[src_radius] + identifier[det_radius] identifier[u] = identifier[d] * identifier[np] . identifier[arctan] ( identifier[up] / identifier[d] ) identifier[v] = identifier[d] / identifier[np] . identifier[sqrt] ( identifier[d] ** literal[int] + identifier[up] ** literal[int] )* identifier[vp] identifier[proj_data_cylinder] = identifier[ray_trafo] . identifier[range] . identifier[element] ( identifier[data_array] ) identifier[interpolated_values] = identifier[proj_data_cylinder] . identifier[interpolation] (( identifier[theta] , identifier[u] , identifier[v] )) identifier[proj_data] = identifier[ray_trafo] . identifier[range] . identifier[element] ( identifier[interpolated_values] ) keyword[return] identifier[geometry] , identifier[proj_data] . identifier[asarray] ()
def load_projections(folder, indices=None): """Load geometry and data stored in Mayo format from folder. Parameters ---------- folder : str Path to the folder where the Mayo DICOM files are stored. indices : optional Indices of the projections to load. Accepts advanced indexing such as slice or list of indices. Returns ------- geometry : ConeFlatGeometry Geometry corresponding to the Mayo projector. proj_data : `numpy.ndarray` Projection data, given as the line integral of the linear attenuation coefficient (g/cm^3). Its unit is thus g/cm^2. """ (datasets, data_array) = _read_projections(folder, indices) # Get the angles angles = [d.DetectorFocalCenterAngularPosition for d in datasets] angles = -np.unwrap(angles) - np.pi # different defintion of angles # Set minimum and maximum corners shape = np.array([datasets[0].NumberofDetectorColumns, datasets[0].NumberofDetectorRows]) pixel_size = np.array([datasets[0].DetectorElementTransverseSpacing, datasets[0].DetectorElementAxialSpacing]) # Correct from center of pixel to corner of pixel minp = -(np.array(datasets[0].DetectorCentralElement) - 0.5) * pixel_size maxp = minp + shape * pixel_size # Select geometry parameters src_radius = datasets[0].DetectorFocalCenterRadialDistance det_radius = datasets[0].ConstantRadialDistance - datasets[0].DetectorFocalCenterRadialDistance # For unknown reasons, mayo does not include the tag # "TableFeedPerRotation", which is what we want. # Instead we manually compute the pitch pitch = (datasets[-1].DetectorFocalCenterAxialPosition - datasets[0].DetectorFocalCenterAxialPosition) / ((np.max(angles) - np.min(angles)) / (2 * np.pi)) # Get flying focal spot data offset_axial = np.array([d.SourceAxialPositionShift for d in datasets]) offset_angular = np.array([d.SourceAngularPositionShift for d in datasets]) offset_radial = np.array([d.SourceRadialDistanceShift for d in datasets]) # TODO(adler-j): Implement proper handling of flying focal spot. # Currently we do not fully account for it, merely making some "first # order corrections" to the detector position and radial offset. # Update angles with flying focal spot (in plane direction). # This increases the resolution of the reconstructions. angles = angles - offset_angular # We correct for the mean offset due to the rotated angles, we need to # shift the detector. offset_detector_by_angles = det_radius * np.mean(offset_angular) minp[0] -= offset_detector_by_angles maxp[0] -= offset_detector_by_angles # We currently apply only the mean of the offsets src_radius = src_radius + np.mean(offset_radial) # Partially compensate for a movement of the source by moving the object # instead. We need to rescale by the magnification to get the correct # change in the detector. This approximation is only exactly valid on the # axis of rotation. mean_offset_along_axis_for_ffz = np.mean(offset_axial) * (src_radius / (src_radius + det_radius)) # Create partition for detector detector_partition = odl.uniform_partition(minp, maxp, shape) # Convert offset to odl defintions offset_along_axis = mean_offset_along_axis_for_ffz + datasets[0].DetectorFocalCenterAxialPosition - angles[0] / (2 * np.pi) * pitch # Assemble geometry angle_partition = odl.nonuniform_partition(angles) geometry = odl.tomo.ConeFlatGeometry(angle_partition, detector_partition, src_radius=src_radius, det_radius=det_radius, pitch=pitch, offset_along_axis=offset_along_axis) # Create a *temporary* ray transform (we need its range) spc = odl.uniform_discr([-1] * 3, [1] * 3, [32] * 3) ray_trafo = odl.tomo.RayTransform(spc, geometry, interp='linear') # convert coordinates (theta, up, vp) = ray_trafo.range.grid.meshgrid d = src_radius + det_radius u = d * np.arctan(up / d) v = d / np.sqrt(d ** 2 + up ** 2) * vp # Calculate projection data in rectangular coordinates since we have no # backend that supports cylindrical proj_data_cylinder = ray_trafo.range.element(data_array) interpolated_values = proj_data_cylinder.interpolation((theta, u, v)) proj_data = ray_trafo.range.element(interpolated_values) return (geometry, proj_data.asarray())
def get_files(data): """Retrieve pre-installed viral reference files. """ all_files = glob.glob(os.path.normpath(os.path.join(os.path.dirname(dd.get_ref_file(data)), os.pardir, "viral", "*"))) return sorted(all_files)
def function[get_files, parameter[data]]: constant[Retrieve pre-installed viral reference files. ] variable[all_files] assign[=] call[name[glob].glob, parameter[call[name[os].path.normpath, parameter[call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[call[name[dd].get_ref_file, parameter[name[data]]]]], name[os].pardir, constant[viral], constant[*]]]]]]] return[call[name[sorted], parameter[name[all_files]]]]
keyword[def] identifier[get_files] ( identifier[data] ): literal[string] identifier[all_files] = identifier[glob] . identifier[glob] ( identifier[os] . identifier[path] . identifier[normpath] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[dd] . identifier[get_ref_file] ( identifier[data] )), identifier[os] . identifier[pardir] , literal[string] , literal[string] ))) keyword[return] identifier[sorted] ( identifier[all_files] )
def get_files(data): """Retrieve pre-installed viral reference files. """ all_files = glob.glob(os.path.normpath(os.path.join(os.path.dirname(dd.get_ref_file(data)), os.pardir, 'viral', '*'))) return sorted(all_files)
def _negate_compare_text(atok: asttokens.ASTTokens, node: ast.Compare) -> str: """ Generate the text representing the negation of the comparison node. :param atok: parsing obtained with ``asttokens`` so that we can access the last tokens of a node. The standard ``ast`` module provides only the first token of an AST node. In lack of concrete syntax tree, getting text from first to last token is currently the simplest approach. :param node: AST node representing the comparison in a condition :return: text representation of the node's negation """ assert len(node.ops) == 1, "A single comparison expected, but got: {}".format(len(node.ops)) assert len(node.comparators) == 1, "A single comparator expected, but got: {}".format(len(node.comparators)) operator = node.ops[0] left = node.left right = node.comparators[0] left_text = atok.get_text(node=left) right_text = atok.get_text(node=right) text = '' if isinstance(operator, ast.Eq): text = '{} != {}'.format(left_text, right_text) elif isinstance(operator, ast.NotEq): text = '{} == {}'.format(left_text, right_text) elif isinstance(operator, ast.Lt): text = '{} >= {}'.format(left_text, right_text) elif isinstance(operator, ast.LtE): text = '{} > {}'.format(left_text, right_text) elif isinstance(operator, ast.Gt): text = '{} <= {}'.format(left_text, right_text) elif isinstance(operator, ast.GtE): text = '{} < {}'.format(left_text, right_text) elif isinstance(operator, ast.Is): text = '{} is not {}'.format(left_text, right_text) elif isinstance(operator, ast.IsNot): text = '{} is {}'.format(left_text, right_text) elif isinstance(operator, ast.In): text = '{} not in {}'.format(left_text, right_text) elif isinstance(operator, ast.NotIn): text = '{} in {}'.format(left_text, right_text) else: raise NotImplementedError("Unhandled comparison operator: {}".format(operator)) return text
def function[_negate_compare_text, parameter[atok, node]]: constant[ Generate the text representing the negation of the comparison node. :param atok: parsing obtained with ``asttokens`` so that we can access the last tokens of a node. The standard ``ast`` module provides only the first token of an AST node. In lack of concrete syntax tree, getting text from first to last token is currently the simplest approach. :param node: AST node representing the comparison in a condition :return: text representation of the node's negation ] assert[compare[call[name[len], parameter[name[node].ops]] equal[==] constant[1]]] assert[compare[call[name[len], parameter[name[node].comparators]] equal[==] constant[1]]] variable[operator] assign[=] call[name[node].ops][constant[0]] variable[left] assign[=] name[node].left variable[right] assign[=] call[name[node].comparators][constant[0]] variable[left_text] assign[=] call[name[atok].get_text, parameter[]] variable[right_text] assign[=] call[name[atok].get_text, parameter[]] variable[text] assign[=] constant[] if call[name[isinstance], parameter[name[operator], name[ast].Eq]] begin[:] variable[text] assign[=] call[constant[{} != {}].format, parameter[name[left_text], name[right_text]]] return[name[text]]
keyword[def] identifier[_negate_compare_text] ( identifier[atok] : identifier[asttokens] . identifier[ASTTokens] , identifier[node] : identifier[ast] . identifier[Compare] )-> identifier[str] : literal[string] keyword[assert] identifier[len] ( identifier[node] . identifier[ops] )== literal[int] , literal[string] . identifier[format] ( identifier[len] ( identifier[node] . identifier[ops] )) keyword[assert] identifier[len] ( identifier[node] . identifier[comparators] )== literal[int] , literal[string] . identifier[format] ( identifier[len] ( identifier[node] . identifier[comparators] )) identifier[operator] = identifier[node] . identifier[ops] [ literal[int] ] identifier[left] = identifier[node] . identifier[left] identifier[right] = identifier[node] . identifier[comparators] [ literal[int] ] identifier[left_text] = identifier[atok] . identifier[get_text] ( identifier[node] = identifier[left] ) identifier[right_text] = identifier[atok] . identifier[get_text] ( identifier[node] = identifier[right] ) identifier[text] = literal[string] keyword[if] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[Eq] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[NotEq] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[Lt] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[LtE] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[Gt] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[GtE] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[Is] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[IsNot] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[In] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[elif] identifier[isinstance] ( identifier[operator] , identifier[ast] . identifier[NotIn] ): identifier[text] = literal[string] . identifier[format] ( identifier[left_text] , identifier[right_text] ) keyword[else] : keyword[raise] identifier[NotImplementedError] ( literal[string] . identifier[format] ( identifier[operator] )) keyword[return] identifier[text]
def _negate_compare_text(atok: asttokens.ASTTokens, node: ast.Compare) -> str: """ Generate the text representing the negation of the comparison node. :param atok: parsing obtained with ``asttokens`` so that we can access the last tokens of a node. The standard ``ast`` module provides only the first token of an AST node. In lack of concrete syntax tree, getting text from first to last token is currently the simplest approach. :param node: AST node representing the comparison in a condition :return: text representation of the node's negation """ assert len(node.ops) == 1, 'A single comparison expected, but got: {}'.format(len(node.ops)) assert len(node.comparators) == 1, 'A single comparator expected, but got: {}'.format(len(node.comparators)) operator = node.ops[0] left = node.left right = node.comparators[0] left_text = atok.get_text(node=left) right_text = atok.get_text(node=right) text = '' if isinstance(operator, ast.Eq): text = '{} != {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.NotEq): text = '{} == {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.Lt): text = '{} >= {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.LtE): text = '{} > {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.Gt): text = '{} <= {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.GtE): text = '{} < {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.Is): text = '{} is not {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.IsNot): text = '{} is {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.In): text = '{} not in {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] elif isinstance(operator, ast.NotIn): text = '{} in {}'.format(left_text, right_text) # depends on [control=['if'], data=[]] else: raise NotImplementedError('Unhandled comparison operator: {}'.format(operator)) return text
def get_document(self, doc_id): '''Download the document given the id.''' conn = self.agency._database.get_connection() return conn.get_document(doc_id)
def function[get_document, parameter[self, doc_id]]: constant[Download the document given the id.] variable[conn] assign[=] call[name[self].agency._database.get_connection, parameter[]] return[call[name[conn].get_document, parameter[name[doc_id]]]]
keyword[def] identifier[get_document] ( identifier[self] , identifier[doc_id] ): literal[string] identifier[conn] = identifier[self] . identifier[agency] . identifier[_database] . identifier[get_connection] () keyword[return] identifier[conn] . identifier[get_document] ( identifier[doc_id] )
def get_document(self, doc_id): """Download the document given the id.""" conn = self.agency._database.get_connection() return conn.get_document(doc_id)
def reset(self): """ Resets the state of the robot and clears: * Deck * Instruments * Command queue * Runtime warnings Examples -------- >>> from opentrons import robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP """ self._actuators = { 'left': { 'carriage': Mover( driver=self._driver, src=pose_tracker.ROOT, dst=id(self.config.gantry_calibration), axis_mapping={'z': 'Z'}), 'plunger': Mover( driver=self._driver, src=pose_tracker.ROOT, dst='volume-calibration-left', axis_mapping={'x': 'B'}) }, 'right': { 'carriage': Mover( driver=self._driver, src=pose_tracker.ROOT, dst=id(self.config.gantry_calibration), axis_mapping={'z': 'A'}), 'plunger': Mover( driver=self._driver, src=pose_tracker.ROOT, dst='volume-calibration-right', axis_mapping={'x': 'C'}) } } self.clear_tips() self.poses = pose_tracker.init() self._runtime_warnings = [] self._deck = containers.Deck() self._fixed_trash = None self.setup_deck() self.setup_gantry() self._instruments = {} self._use_safest_height = False self._previous_instrument = None self._prev_container = None # TODO: Move homing info to driver self.axis_homed = { 'x': False, 'y': False, 'z': False, 'a': False, 'b': False} self.clear_commands() # update the position of each Mover self._driver.update_position() for mount in self._actuators.values(): for mover in mount.values(): self.poses = mover.update_pose_from_driver(self.poses) self.cache_instrument_models() return self
def function[reset, parameter[self]]: constant[ Resets the state of the robot and clears: * Deck * Instruments * Command queue * Runtime warnings Examples -------- >>> from opentrons import robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP ] name[self]._actuators assign[=] dictionary[[<ast.Constant object at 0x7da1b09255a0>, <ast.Constant object at 0x7da1b09255d0>], [<ast.Dict object at 0x7da1b0924550>, <ast.Dict object at 0x7da1b0926710>]] call[name[self].clear_tips, parameter[]] name[self].poses assign[=] call[name[pose_tracker].init, parameter[]] name[self]._runtime_warnings assign[=] list[[]] name[self]._deck assign[=] call[name[containers].Deck, parameter[]] name[self]._fixed_trash assign[=] constant[None] call[name[self].setup_deck, parameter[]] call[name[self].setup_gantry, parameter[]] name[self]._instruments assign[=] dictionary[[], []] name[self]._use_safest_height assign[=] constant[False] name[self]._previous_instrument assign[=] constant[None] name[self]._prev_container assign[=] constant[None] name[self].axis_homed assign[=] dictionary[[<ast.Constant object at 0x7da1b0924940>, <ast.Constant object at 0x7da1b0924970>, <ast.Constant object at 0x7da1b09249a0>, <ast.Constant object at 0x7da1b09249d0>, <ast.Constant object at 0x7da1b0924a00>], [<ast.Constant object at 0x7da1b0924a60>, <ast.Constant object at 0x7da1b0924a90>, <ast.Constant object at 0x7da1b0924ac0>, <ast.Constant object at 0x7da1b0924af0>, <ast.Constant object at 0x7da1b0924b20>]] call[name[self].clear_commands, parameter[]] call[name[self]._driver.update_position, parameter[]] for taget[name[mount]] in starred[call[name[self]._actuators.values, parameter[]]] begin[:] for taget[name[mover]] in starred[call[name[mount].values, parameter[]]] begin[:] name[self].poses assign[=] call[name[mover].update_pose_from_driver, parameter[name[self].poses]] call[name[self].cache_instrument_models, parameter[]] return[name[self]]
keyword[def] identifier[reset] ( identifier[self] ): literal[string] identifier[self] . identifier[_actuators] ={ literal[string] :{ literal[string] : identifier[Mover] ( identifier[driver] = identifier[self] . identifier[_driver] , identifier[src] = identifier[pose_tracker] . identifier[ROOT] , identifier[dst] = identifier[id] ( identifier[self] . identifier[config] . identifier[gantry_calibration] ), identifier[axis_mapping] ={ literal[string] : literal[string] }), literal[string] : identifier[Mover] ( identifier[driver] = identifier[self] . identifier[_driver] , identifier[src] = identifier[pose_tracker] . identifier[ROOT] , identifier[dst] = literal[string] , identifier[axis_mapping] ={ literal[string] : literal[string] }) }, literal[string] :{ literal[string] : identifier[Mover] ( identifier[driver] = identifier[self] . identifier[_driver] , identifier[src] = identifier[pose_tracker] . identifier[ROOT] , identifier[dst] = identifier[id] ( identifier[self] . identifier[config] . identifier[gantry_calibration] ), identifier[axis_mapping] ={ literal[string] : literal[string] }), literal[string] : identifier[Mover] ( identifier[driver] = identifier[self] . identifier[_driver] , identifier[src] = identifier[pose_tracker] . identifier[ROOT] , identifier[dst] = literal[string] , identifier[axis_mapping] ={ literal[string] : literal[string] }) } } identifier[self] . identifier[clear_tips] () identifier[self] . identifier[poses] = identifier[pose_tracker] . identifier[init] () identifier[self] . identifier[_runtime_warnings] =[] identifier[self] . identifier[_deck] = identifier[containers] . identifier[Deck] () identifier[self] . identifier[_fixed_trash] = keyword[None] identifier[self] . identifier[setup_deck] () identifier[self] . identifier[setup_gantry] () identifier[self] . identifier[_instruments] ={} identifier[self] . identifier[_use_safest_height] = keyword[False] identifier[self] . identifier[_previous_instrument] = keyword[None] identifier[self] . identifier[_prev_container] = keyword[None] identifier[self] . identifier[axis_homed] ={ literal[string] : keyword[False] , literal[string] : keyword[False] , literal[string] : keyword[False] , literal[string] : keyword[False] , literal[string] : keyword[False] } identifier[self] . identifier[clear_commands] () identifier[self] . identifier[_driver] . identifier[update_position] () keyword[for] identifier[mount] keyword[in] identifier[self] . identifier[_actuators] . identifier[values] (): keyword[for] identifier[mover] keyword[in] identifier[mount] . identifier[values] (): identifier[self] . identifier[poses] = identifier[mover] . identifier[update_pose_from_driver] ( identifier[self] . identifier[poses] ) identifier[self] . identifier[cache_instrument_models] () keyword[return] identifier[self]
def reset(self): """ Resets the state of the robot and clears: * Deck * Instruments * Command queue * Runtime warnings Examples -------- >>> from opentrons import robot # doctest: +SKIP >>> robot.reset() # doctest: +SKIP """ self._actuators = {'left': {'carriage': Mover(driver=self._driver, src=pose_tracker.ROOT, dst=id(self.config.gantry_calibration), axis_mapping={'z': 'Z'}), 'plunger': Mover(driver=self._driver, src=pose_tracker.ROOT, dst='volume-calibration-left', axis_mapping={'x': 'B'})}, 'right': {'carriage': Mover(driver=self._driver, src=pose_tracker.ROOT, dst=id(self.config.gantry_calibration), axis_mapping={'z': 'A'}), 'plunger': Mover(driver=self._driver, src=pose_tracker.ROOT, dst='volume-calibration-right', axis_mapping={'x': 'C'})}} self.clear_tips() self.poses = pose_tracker.init() self._runtime_warnings = [] self._deck = containers.Deck() self._fixed_trash = None self.setup_deck() self.setup_gantry() self._instruments = {} self._use_safest_height = False self._previous_instrument = None self._prev_container = None # TODO: Move homing info to driver self.axis_homed = {'x': False, 'y': False, 'z': False, 'a': False, 'b': False} self.clear_commands() # update the position of each Mover self._driver.update_position() for mount in self._actuators.values(): for mover in mount.values(): self.poses = mover.update_pose_from_driver(self.poses) # depends on [control=['for'], data=['mover']] # depends on [control=['for'], data=['mount']] self.cache_instrument_models() return self
def update_metadata(self, entity_type, entity_id, metadata): '''Update the metadata of an entity. Existing non-modified metadata will not be affected. Args: entity_type (str): Type of the entity. Admitted values: 'project', 'folder', 'file'. entity_id (str): The UUID of the entity to be modified. metadata (dict): A dictionary of key/value pairs to be written as metadata. Returns: A dictionary of the updated object metadata:: { u'bar': u'200', u'foo': u'100' } Raises: StorageArgumentException: Invalid arguments StorageForbiddenException: Server response code 403 StorageNotFoundException: Server response code 404 StorageException: other 400-600 error codes ''' if not is_valid_uuid(entity_id): raise StorageArgumentException( 'Invalid UUID for entity_id: {0}'.format(entity_id)) if not isinstance(metadata, dict): raise StorageArgumentException('The metadata was not provided as a ' 'dictionary') return self._authenticated_request \ .to_endpoint('{}/{}/metadata/'.format(entity_type, entity_id)) \ .with_json_body(metadata) \ .return_body() \ .put()
def function[update_metadata, parameter[self, entity_type, entity_id, metadata]]: constant[Update the metadata of an entity. Existing non-modified metadata will not be affected. Args: entity_type (str): Type of the entity. Admitted values: 'project', 'folder', 'file'. entity_id (str): The UUID of the entity to be modified. metadata (dict): A dictionary of key/value pairs to be written as metadata. Returns: A dictionary of the updated object metadata:: { u'bar': u'200', u'foo': u'100' } Raises: StorageArgumentException: Invalid arguments StorageForbiddenException: Server response code 403 StorageNotFoundException: Server response code 404 StorageException: other 400-600 error codes ] if <ast.UnaryOp object at 0x7da18eb56200> begin[:] <ast.Raise object at 0x7da18eb564a0> if <ast.UnaryOp object at 0x7da18eb56a40> begin[:] <ast.Raise object at 0x7da18eb542b0> return[call[call[call[call[name[self]._authenticated_request.to_endpoint, parameter[call[constant[{}/{}/metadata/].format, parameter[name[entity_type], name[entity_id]]]]].with_json_body, parameter[name[metadata]]].return_body, parameter[]].put, parameter[]]]
keyword[def] identifier[update_metadata] ( identifier[self] , identifier[entity_type] , identifier[entity_id] , identifier[metadata] ): literal[string] keyword[if] keyword[not] identifier[is_valid_uuid] ( identifier[entity_id] ): keyword[raise] identifier[StorageArgumentException] ( literal[string] . identifier[format] ( identifier[entity_id] )) keyword[if] keyword[not] identifier[isinstance] ( identifier[metadata] , identifier[dict] ): keyword[raise] identifier[StorageArgumentException] ( literal[string] literal[string] ) keyword[return] identifier[self] . identifier[_authenticated_request] . identifier[to_endpoint] ( literal[string] . identifier[format] ( identifier[entity_type] , identifier[entity_id] )). identifier[with_json_body] ( identifier[metadata] ). identifier[return_body] (). identifier[put] ()
def update_metadata(self, entity_type, entity_id, metadata): """Update the metadata of an entity. Existing non-modified metadata will not be affected. Args: entity_type (str): Type of the entity. Admitted values: 'project', 'folder', 'file'. entity_id (str): The UUID of the entity to be modified. metadata (dict): A dictionary of key/value pairs to be written as metadata. Returns: A dictionary of the updated object metadata:: { u'bar': u'200', u'foo': u'100' } Raises: StorageArgumentException: Invalid arguments StorageForbiddenException: Server response code 403 StorageNotFoundException: Server response code 404 StorageException: other 400-600 error codes """ if not is_valid_uuid(entity_id): raise StorageArgumentException('Invalid UUID for entity_id: {0}'.format(entity_id)) # depends on [control=['if'], data=[]] if not isinstance(metadata, dict): raise StorageArgumentException('The metadata was not provided as a dictionary') # depends on [control=['if'], data=[]] return self._authenticated_request.to_endpoint('{}/{}/metadata/'.format(entity_type, entity_id)).with_json_body(metadata).return_body().put()
def setup_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files, stat_files, background_file, veto_file, veto_name, out_dir, tags=None): """ This function sets up exact match coincidence and background estimation using a folded interval technique. """ if tags is None: tags = [] make_analysis_dir(out_dir) logging.info('Setting up coincidence for injection') if len(hdfbank) > 1: raise ValueError('This coincidence method only supports a ' 'pregenerated template bank') hdfbank = hdfbank[0] if len(workflow.ifos) > 2: raise ValueError('This coincidence method only supports two-ifo searches') # Wall time knob and memory knob factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags)) ffiles = {} ifiles = {} for ifo, ffi in zip(*full_data_trig_files.categorize_by_attr('ifo')): ffiles[ifo] = ffi[0] ifos, files = inj_trig_files.categorize_by_attr('ifo') # ifos list is used later for ifo, ifi in zip(ifos, files): ifiles[ifo] = ifi[0] ifo0, ifo1 = ifos[0], ifos[1] combo = [(FileList([ifiles[ifo0], ifiles[ifo1]]), "injinj"), (FileList([ifiles[ifo0], ffiles[ifo1]]), "injfull"), (FileList([ifiles[ifo1], ffiles[ifo0]]), "fullinj"), ] bg_files = {'injinj':[], 'injfull':[], 'fullinj':[]} for trig_files, ctag in combo: findcoinc_exe = PyCBCFindCoincExecutable(workflow.cp, 'coinc', ifos=workflow.ifos, tags=tags + [ctag], out_dir=out_dir) for i in range(factor): group_str = '%s/%s' % (i, factor) coinc_node = findcoinc_exe.create_node(trig_files, hdfbank, stat_files, veto_file, veto_name, group_str, tags=[str(i)]) bg_files[ctag] += coinc_node.output_files workflow.add_node(coinc_node) return setup_statmap_inj(workflow, bg_files, background_file, hdfbank, out_dir, tags=tags)
def function[setup_interval_coinc_inj, parameter[workflow, hdfbank, full_data_trig_files, inj_trig_files, stat_files, background_file, veto_file, veto_name, out_dir, tags]]: constant[ This function sets up exact match coincidence and background estimation using a folded interval technique. ] if compare[name[tags] is constant[None]] begin[:] variable[tags] assign[=] list[[]] call[name[make_analysis_dir], parameter[name[out_dir]]] call[name[logging].info, parameter[constant[Setting up coincidence for injection]]] if compare[call[name[len], parameter[name[hdfbank]]] greater[>] constant[1]] begin[:] <ast.Raise object at 0x7da18dc07580> variable[hdfbank] assign[=] call[name[hdfbank]][constant[0]] if compare[call[name[len], parameter[name[workflow].ifos]] greater[>] constant[2]] begin[:] <ast.Raise object at 0x7da18dc046a0> variable[factor] assign[=] call[name[int], parameter[call[name[workflow].cp.get_opt_tags, parameter[constant[workflow-coincidence], constant[parallelization-factor], name[tags]]]]] variable[ffiles] assign[=] dictionary[[], []] variable[ifiles] assign[=] dictionary[[], []] for taget[tuple[[<ast.Name object at 0x7da18dc05ae0>, <ast.Name object at 0x7da18dc06c20>]]] in starred[call[name[zip], parameter[<ast.Starred object at 0x7da18f810220>]]] begin[:] call[name[ffiles]][name[ifo]] assign[=] call[name[ffi]][constant[0]] <ast.Tuple object at 0x7da18f811e10> assign[=] call[name[inj_trig_files].categorize_by_attr, parameter[constant[ifo]]] for taget[tuple[[<ast.Name object at 0x7da18f813fa0>, <ast.Name object at 0x7da18f812290>]]] in starred[call[name[zip], parameter[name[ifos], name[files]]]] begin[:] call[name[ifiles]][name[ifo]] assign[=] call[name[ifi]][constant[0]] <ast.Tuple object at 0x7da20e74b820> assign[=] tuple[[<ast.Subscript object at 0x7da20e74be50>, <ast.Subscript object at 0x7da20e74bca0>]] variable[combo] assign[=] list[[<ast.Tuple object at 0x7da18dc05f30>, <ast.Tuple object at 0x7da18dc05510>, <ast.Tuple object at 0x7da18dc07b80>]] variable[bg_files] assign[=] dictionary[[<ast.Constant object at 0x7da18dc05600>, <ast.Constant object at 0x7da18dc049a0>, <ast.Constant object at 0x7da18dc05810>], [<ast.List object at 0x7da18dc05fc0>, <ast.List object at 0x7da18dc055a0>, <ast.List object at 0x7da18dc07c40>]] for taget[tuple[[<ast.Name object at 0x7da18dc06920>, <ast.Name object at 0x7da18dc073a0>]]] in starred[name[combo]] begin[:] variable[findcoinc_exe] assign[=] call[name[PyCBCFindCoincExecutable], parameter[name[workflow].cp, constant[coinc]]] for taget[name[i]] in starred[call[name[range], parameter[name[factor]]]] begin[:] variable[group_str] assign[=] binary_operation[constant[%s/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18dc07eb0>, <ast.Name object at 0x7da18dc061d0>]]] variable[coinc_node] assign[=] call[name[findcoinc_exe].create_node, parameter[name[trig_files], name[hdfbank], name[stat_files], name[veto_file], name[veto_name], name[group_str]]] <ast.AugAssign object at 0x7da18dc06c50> call[name[workflow].add_node, parameter[name[coinc_node]]] return[call[name[setup_statmap_inj], parameter[name[workflow], name[bg_files], name[background_file], name[hdfbank], name[out_dir]]]]
keyword[def] identifier[setup_interval_coinc_inj] ( identifier[workflow] , identifier[hdfbank] , identifier[full_data_trig_files] , identifier[inj_trig_files] , identifier[stat_files] , identifier[background_file] , identifier[veto_file] , identifier[veto_name] , identifier[out_dir] , identifier[tags] = keyword[None] ): literal[string] keyword[if] identifier[tags] keyword[is] keyword[None] : identifier[tags] =[] identifier[make_analysis_dir] ( identifier[out_dir] ) identifier[logging] . identifier[info] ( literal[string] ) keyword[if] identifier[len] ( identifier[hdfbank] )> literal[int] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) identifier[hdfbank] = identifier[hdfbank] [ literal[int] ] keyword[if] identifier[len] ( identifier[workflow] . identifier[ifos] )> literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[factor] = identifier[int] ( identifier[workflow] . identifier[cp] . identifier[get_opt_tags] ( literal[string] , literal[string] , identifier[tags] )) identifier[ffiles] ={} identifier[ifiles] ={} keyword[for] identifier[ifo] , identifier[ffi] keyword[in] identifier[zip] (* identifier[full_data_trig_files] . identifier[categorize_by_attr] ( literal[string] )): identifier[ffiles] [ identifier[ifo] ]= identifier[ffi] [ literal[int] ] identifier[ifos] , identifier[files] = identifier[inj_trig_files] . identifier[categorize_by_attr] ( literal[string] ) keyword[for] identifier[ifo] , identifier[ifi] keyword[in] identifier[zip] ( identifier[ifos] , identifier[files] ): identifier[ifiles] [ identifier[ifo] ]= identifier[ifi] [ literal[int] ] identifier[ifo0] , identifier[ifo1] = identifier[ifos] [ literal[int] ], identifier[ifos] [ literal[int] ] identifier[combo] =[( identifier[FileList] ([ identifier[ifiles] [ identifier[ifo0] ], identifier[ifiles] [ identifier[ifo1] ]]), literal[string] ), ( identifier[FileList] ([ identifier[ifiles] [ identifier[ifo0] ], identifier[ffiles] [ identifier[ifo1] ]]), literal[string] ), ( identifier[FileList] ([ identifier[ifiles] [ identifier[ifo1] ], identifier[ffiles] [ identifier[ifo0] ]]), literal[string] ), ] identifier[bg_files] ={ literal[string] :[], literal[string] :[], literal[string] :[]} keyword[for] identifier[trig_files] , identifier[ctag] keyword[in] identifier[combo] : identifier[findcoinc_exe] = identifier[PyCBCFindCoincExecutable] ( identifier[workflow] . identifier[cp] , literal[string] , identifier[ifos] = identifier[workflow] . identifier[ifos] , identifier[tags] = identifier[tags] +[ identifier[ctag] ], identifier[out_dir] = identifier[out_dir] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[factor] ): identifier[group_str] = literal[string] %( identifier[i] , identifier[factor] ) identifier[coinc_node] = identifier[findcoinc_exe] . identifier[create_node] ( identifier[trig_files] , identifier[hdfbank] , identifier[stat_files] , identifier[veto_file] , identifier[veto_name] , identifier[group_str] , identifier[tags] =[ identifier[str] ( identifier[i] )]) identifier[bg_files] [ identifier[ctag] ]+= identifier[coinc_node] . identifier[output_files] identifier[workflow] . identifier[add_node] ( identifier[coinc_node] ) keyword[return] identifier[setup_statmap_inj] ( identifier[workflow] , identifier[bg_files] , identifier[background_file] , identifier[hdfbank] , identifier[out_dir] , identifier[tags] = identifier[tags] )
def setup_interval_coinc_inj(workflow, hdfbank, full_data_trig_files, inj_trig_files, stat_files, background_file, veto_file, veto_name, out_dir, tags=None): """ This function sets up exact match coincidence and background estimation using a folded interval technique. """ if tags is None: tags = [] # depends on [control=['if'], data=['tags']] make_analysis_dir(out_dir) logging.info('Setting up coincidence for injection') if len(hdfbank) > 1: raise ValueError('This coincidence method only supports a pregenerated template bank') # depends on [control=['if'], data=[]] hdfbank = hdfbank[0] if len(workflow.ifos) > 2: raise ValueError('This coincidence method only supports two-ifo searches') # depends on [control=['if'], data=[]] # Wall time knob and memory knob factor = int(workflow.cp.get_opt_tags('workflow-coincidence', 'parallelization-factor', tags)) ffiles = {} ifiles = {} for (ifo, ffi) in zip(*full_data_trig_files.categorize_by_attr('ifo')): ffiles[ifo] = ffi[0] # depends on [control=['for'], data=[]] (ifos, files) = inj_trig_files.categorize_by_attr('ifo') # ifos list is used later for (ifo, ifi) in zip(ifos, files): ifiles[ifo] = ifi[0] # depends on [control=['for'], data=[]] (ifo0, ifo1) = (ifos[0], ifos[1]) combo = [(FileList([ifiles[ifo0], ifiles[ifo1]]), 'injinj'), (FileList([ifiles[ifo0], ffiles[ifo1]]), 'injfull'), (FileList([ifiles[ifo1], ffiles[ifo0]]), 'fullinj')] bg_files = {'injinj': [], 'injfull': [], 'fullinj': []} for (trig_files, ctag) in combo: findcoinc_exe = PyCBCFindCoincExecutable(workflow.cp, 'coinc', ifos=workflow.ifos, tags=tags + [ctag], out_dir=out_dir) for i in range(factor): group_str = '%s/%s' % (i, factor) coinc_node = findcoinc_exe.create_node(trig_files, hdfbank, stat_files, veto_file, veto_name, group_str, tags=[str(i)]) bg_files[ctag] += coinc_node.output_files workflow.add_node(coinc_node) # depends on [control=['for'], data=['i']] # depends on [control=['for'], data=[]] return setup_statmap_inj(workflow, bg_files, background_file, hdfbank, out_dir, tags=tags)
def get_mapped_permissions_for(brain_or_object): """Get the mapped permissions for the given object A mapped permission is one that is used in the object. Each permission string, e.g. "senaite.core: Field: Edit Analysis Remarks" is translated by the function `AccessControl.Permission.pname` to a valid attribute name: >>> from bika.lims.permissions import FieldEditAnalysisResult >>> AccessControl.Permission import pname >>> pname(FieldEditAnalysisResult) _Field__Edit_Result_Permission This attribute is looked up in the object by `getPermissionMapping`: >>> from AccessControl.PermissionMapping import getPermissionMapping >>> getPermissionMapping(FieldEditAnalysisResult, wrapper) ("Manager", "Sampler") Therefore, only those permissions which have roles mapped on the object or by objects within the acquisition chain are considered. Code extracted from `IRoleManager.manage_getUserRolesAndPermissions` :param brain_or_object: Catalog brain or object :returns: List of permissions """ obj = api.get_object(brain_or_object) mapping = obj.manage_getPermissionMapping() return map(lambda item: item["permission_name"], mapping)
def function[get_mapped_permissions_for, parameter[brain_or_object]]: constant[Get the mapped permissions for the given object A mapped permission is one that is used in the object. Each permission string, e.g. "senaite.core: Field: Edit Analysis Remarks" is translated by the function `AccessControl.Permission.pname` to a valid attribute name: >>> from bika.lims.permissions import FieldEditAnalysisResult >>> AccessControl.Permission import pname >>> pname(FieldEditAnalysisResult) _Field__Edit_Result_Permission This attribute is looked up in the object by `getPermissionMapping`: >>> from AccessControl.PermissionMapping import getPermissionMapping >>> getPermissionMapping(FieldEditAnalysisResult, wrapper) ("Manager", "Sampler") Therefore, only those permissions which have roles mapped on the object or by objects within the acquisition chain are considered. Code extracted from `IRoleManager.manage_getUserRolesAndPermissions` :param brain_or_object: Catalog brain or object :returns: List of permissions ] variable[obj] assign[=] call[name[api].get_object, parameter[name[brain_or_object]]] variable[mapping] assign[=] call[name[obj].manage_getPermissionMapping, parameter[]] return[call[name[map], parameter[<ast.Lambda object at 0x7da1b1d65060>, name[mapping]]]]
keyword[def] identifier[get_mapped_permissions_for] ( identifier[brain_or_object] ): literal[string] identifier[obj] = identifier[api] . identifier[get_object] ( identifier[brain_or_object] ) identifier[mapping] = identifier[obj] . identifier[manage_getPermissionMapping] () keyword[return] identifier[map] ( keyword[lambda] identifier[item] : identifier[item] [ literal[string] ], identifier[mapping] )
def get_mapped_permissions_for(brain_or_object): """Get the mapped permissions for the given object A mapped permission is one that is used in the object. Each permission string, e.g. "senaite.core: Field: Edit Analysis Remarks" is translated by the function `AccessControl.Permission.pname` to a valid attribute name: >>> from bika.lims.permissions import FieldEditAnalysisResult >>> AccessControl.Permission import pname >>> pname(FieldEditAnalysisResult) _Field__Edit_Result_Permission This attribute is looked up in the object by `getPermissionMapping`: >>> from AccessControl.PermissionMapping import getPermissionMapping >>> getPermissionMapping(FieldEditAnalysisResult, wrapper) ("Manager", "Sampler") Therefore, only those permissions which have roles mapped on the object or by objects within the acquisition chain are considered. Code extracted from `IRoleManager.manage_getUserRolesAndPermissions` :param brain_or_object: Catalog brain or object :returns: List of permissions """ obj = api.get_object(brain_or_object) mapping = obj.manage_getPermissionMapping() return map(lambda item: item['permission_name'], mapping)
def _coerce_to_supported_type(cls, value): """ Since we let users populate the context with whatever they want, this ensures the resolved value is something which the expression engine understands. :param value: the resolved value :return: the value converted to a supported data type """ if value is None: return "" # empty string rather than none elif isinstance(value, dict): if '*' in value: return value['*'] elif '__default__' in value: return value['__default__'] else: return json.dumps(value, separators=(',', ':')) # return serialized JSON if no default elif isinstance(value, bool): return value elif isinstance(value, float) or isinstance(value, int): return Decimal(value) else: return value
def function[_coerce_to_supported_type, parameter[cls, value]]: constant[ Since we let users populate the context with whatever they want, this ensures the resolved value is something which the expression engine understands. :param value: the resolved value :return: the value converted to a supported data type ] if compare[name[value] is constant[None]] begin[:] return[constant[]]
keyword[def] identifier[_coerce_to_supported_type] ( identifier[cls] , identifier[value] ): literal[string] keyword[if] identifier[value] keyword[is] keyword[None] : keyword[return] literal[string] keyword[elif] identifier[isinstance] ( identifier[value] , identifier[dict] ): keyword[if] literal[string] keyword[in] identifier[value] : keyword[return] identifier[value] [ literal[string] ] keyword[elif] literal[string] keyword[in] identifier[value] : keyword[return] identifier[value] [ literal[string] ] keyword[else] : keyword[return] identifier[json] . identifier[dumps] ( identifier[value] , identifier[separators] =( literal[string] , literal[string] )) keyword[elif] identifier[isinstance] ( identifier[value] , identifier[bool] ): keyword[return] identifier[value] keyword[elif] identifier[isinstance] ( identifier[value] , identifier[float] ) keyword[or] identifier[isinstance] ( identifier[value] , identifier[int] ): keyword[return] identifier[Decimal] ( identifier[value] ) keyword[else] : keyword[return] identifier[value]
def _coerce_to_supported_type(cls, value): """ Since we let users populate the context with whatever they want, this ensures the resolved value is something which the expression engine understands. :param value: the resolved value :return: the value converted to a supported data type """ if value is None: return '' # empty string rather than none # depends on [control=['if'], data=[]] elif isinstance(value, dict): if '*' in value: return value['*'] # depends on [control=['if'], data=['value']] elif '__default__' in value: return value['__default__'] # depends on [control=['if'], data=['value']] else: return json.dumps(value, separators=(',', ':')) # return serialized JSON if no default # depends on [control=['if'], data=[]] elif isinstance(value, bool): return value # depends on [control=['if'], data=[]] elif isinstance(value, float) or isinstance(value, int): return Decimal(value) # depends on [control=['if'], data=[]] else: return value
def replace_in_file(filename: str, text_from: str, text_to: str) -> None: """ Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text """ log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: outfile.write(contents)
def function[replace_in_file, parameter[filename, text_from, text_to]]: constant[ Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text ] call[name[log].info, parameter[constant[Amending {}: {} -> {}], name[filename], call[name[repr], parameter[name[text_from]]], call[name[repr], parameter[name[text_to]]]]] with call[name[open], parameter[name[filename]]] begin[:] variable[contents] assign[=] call[name[infile].read, parameter[]] variable[contents] assign[=] call[name[contents].replace, parameter[name[text_from], name[text_to]]] with call[name[open], parameter[name[filename], constant[w]]] begin[:] call[name[outfile].write, parameter[name[contents]]]
keyword[def] identifier[replace_in_file] ( identifier[filename] : identifier[str] , identifier[text_from] : identifier[str] , identifier[text_to] : identifier[str] )-> keyword[None] : literal[string] identifier[log] . identifier[info] ( literal[string] , identifier[filename] , identifier[repr] ( identifier[text_from] ), identifier[repr] ( identifier[text_to] )) keyword[with] identifier[open] ( identifier[filename] ) keyword[as] identifier[infile] : identifier[contents] = identifier[infile] . identifier[read] () identifier[contents] = identifier[contents] . identifier[replace] ( identifier[text_from] , identifier[text_to] ) keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[outfile] : identifier[outfile] . identifier[write] ( identifier[contents] )
def replace_in_file(filename: str, text_from: str, text_to: str) -> None: """ Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text """ log.info('Amending {}: {} -> {}', filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() # depends on [control=['with'], data=['infile']] contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: outfile.write(contents) # depends on [control=['with'], data=['outfile']]
def log(self, msg): '''Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ''' if self.logfile: fd = self.logfile.fileno() else: fd = sys.stdout.fileno() os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8'))
def function[log, parameter[self, msg]]: constant[Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ] if name[self].logfile begin[:] variable[fd] assign[=] call[name[self].logfile.fileno, parameter[]] call[name[os].write, parameter[name[fd], call[binary_operation[constant[%.3f %s ] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b0efeaa0>, <ast.Name object at 0x7da1b0efead0>]]].encode, parameter[constant[UTF-8]]]]]
keyword[def] identifier[log] ( identifier[self] , identifier[msg] ): literal[string] keyword[if] identifier[self] . identifier[logfile] : identifier[fd] = identifier[self] . identifier[logfile] . identifier[fileno] () keyword[else] : identifier[fd] = identifier[sys] . identifier[stdout] . identifier[fileno] () identifier[os] . identifier[write] ( identifier[fd] ,( literal[string] %( identifier[time] . identifier[time] (), identifier[msg] )). identifier[encode] ( literal[string] ))
def log(self, msg): """Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. """ if self.logfile: fd = self.logfile.fileno() # depends on [control=['if'], data=[]] else: fd = sys.stdout.fileno() os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8'))
def _Operation(self,operation): """Execute specified operations task against one or more servers. Returns a clc.v2.Requests object. If error due to server(s) already being in the requested state this is not raised as an error at this level. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Pause() <clc.APIv2.queue.Requests object at 0x105fea7d0> >>> _.WaitUntilComplete() 0 """ try: return(clc.v2.Requests(clc.v2.API.Call('POST','operations/%s/servers/%s' % (self.alias,operation), json.dumps(self.servers_lst), session=self.session), alias=self.alias,session=self.session)) except clc.APIFailedResponse as e: # Most likely a queue add error presented as a 400. Let Requests parse this return(clc.v2.Requests(e.response_json,alias=self.alias,session=self.session))
def function[_Operation, parameter[self, operation]]: constant[Execute specified operations task against one or more servers. Returns a clc.v2.Requests object. If error due to server(s) already being in the requested state this is not raised as an error at this level. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Pause() <clc.APIv2.queue.Requests object at 0x105fea7d0> >>> _.WaitUntilComplete() 0 ] <ast.Try object at 0x7da1b23c2dd0>
keyword[def] identifier[_Operation] ( identifier[self] , identifier[operation] ): literal[string] keyword[try] : keyword[return] ( identifier[clc] . identifier[v2] . identifier[Requests] ( identifier[clc] . identifier[v2] . identifier[API] . identifier[Call] ( literal[string] , literal[string] %( identifier[self] . identifier[alias] , identifier[operation] ), identifier[json] . identifier[dumps] ( identifier[self] . identifier[servers_lst] ), identifier[session] = identifier[self] . identifier[session] ), identifier[alias] = identifier[self] . identifier[alias] , identifier[session] = identifier[self] . identifier[session] )) keyword[except] identifier[clc] . identifier[APIFailedResponse] keyword[as] identifier[e] : keyword[return] ( identifier[clc] . identifier[v2] . identifier[Requests] ( identifier[e] . identifier[response_json] , identifier[alias] = identifier[self] . identifier[alias] , identifier[session] = identifier[self] . identifier[session] ))
def _Operation(self, operation): """Execute specified operations task against one or more servers. Returns a clc.v2.Requests object. If error due to server(s) already being in the requested state this is not raised as an error at this level. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Pause() <clc.APIv2.queue.Requests object at 0x105fea7d0> >>> _.WaitUntilComplete() 0 """ try: return clc.v2.Requests(clc.v2.API.Call('POST', 'operations/%s/servers/%s' % (self.alias, operation), json.dumps(self.servers_lst), session=self.session), alias=self.alias, session=self.session) # depends on [control=['try'], data=[]] except clc.APIFailedResponse as e: # Most likely a queue add error presented as a 400. Let Requests parse this return clc.v2.Requests(e.response_json, alias=self.alias, session=self.session) # depends on [control=['except'], data=['e']]
def _getPrototypes(indices, overlaps, topNumber=1): """ Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (numpy.ndarray) Condensed array of overlaps of the form returned by _computeOverlaps(). @param topNumber (int) The number of prototypes to return. Optional, defaults to 1. @returns (numpy.ndarray) Array of indices of prototypes """ # find the number of data points based on the length of the overlap array # solves for n: len(overlaps) = n(n-1)/2 n = numpy.roots([1, -1, -2 * len(overlaps)]).max() k = len(indices) indices = numpy.array(indices, dtype=int) rowIdxs = numpy.ndarray((k, k-1), dtype=int) colIdxs = numpy.ndarray((k, k-1), dtype=int) for i in xrange(k): rowIdxs[i, :] = indices[i] colIdxs[i, :i] = indices[:i] colIdxs[i, i:] = indices[i+1:] idx = HierarchicalClustering._condensedIndex(rowIdxs, colIdxs, n) subsampledOverlaps = overlaps[idx] meanSubsampledOverlaps = subsampledOverlaps.mean(1) biggestOverlapSubsetIdxs = numpy.argsort( -meanSubsampledOverlaps)[:topNumber] return indices[biggestOverlapSubsetIdxs]
def function[_getPrototypes, parameter[indices, overlaps, topNumber]]: constant[ Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (numpy.ndarray) Condensed array of overlaps of the form returned by _computeOverlaps(). @param topNumber (int) The number of prototypes to return. Optional, defaults to 1. @returns (numpy.ndarray) Array of indices of prototypes ] variable[n] assign[=] call[call[name[numpy].roots, parameter[list[[<ast.Constant object at 0x7da204347160>, <ast.UnaryOp object at 0x7da204344ee0>, <ast.BinOp object at 0x7da2043455a0>]]]].max, parameter[]] variable[k] assign[=] call[name[len], parameter[name[indices]]] variable[indices] assign[=] call[name[numpy].array, parameter[name[indices]]] variable[rowIdxs] assign[=] call[name[numpy].ndarray, parameter[tuple[[<ast.Name object at 0x7da204346710>, <ast.BinOp object at 0x7da2043444c0>]]]] variable[colIdxs] assign[=] call[name[numpy].ndarray, parameter[tuple[[<ast.Name object at 0x7da204346ec0>, <ast.BinOp object at 0x7da204347670>]]]] for taget[name[i]] in starred[call[name[xrange], parameter[name[k]]]] begin[:] call[name[rowIdxs]][tuple[[<ast.Name object at 0x7da1b0844850>, <ast.Slice object at 0x7da1b0847ca0>]]] assign[=] call[name[indices]][name[i]] call[name[colIdxs]][tuple[[<ast.Name object at 0x7da1b08446a0>, <ast.Slice object at 0x7da1b0846e60>]]] assign[=] call[name[indices]][<ast.Slice object at 0x7da1b0846c20>] call[name[colIdxs]][tuple[[<ast.Name object at 0x7da1b0845ff0>, <ast.Slice object at 0x7da1b0844100>]]] assign[=] call[name[indices]][<ast.Slice object at 0x7da1b0846ec0>] variable[idx] assign[=] call[name[HierarchicalClustering]._condensedIndex, parameter[name[rowIdxs], name[colIdxs], name[n]]] variable[subsampledOverlaps] assign[=] call[name[overlaps]][name[idx]] variable[meanSubsampledOverlaps] assign[=] call[name[subsampledOverlaps].mean, parameter[constant[1]]] variable[biggestOverlapSubsetIdxs] assign[=] call[call[name[numpy].argsort, parameter[<ast.UnaryOp object at 0x7da1b0847070>]]][<ast.Slice object at 0x7da1b0847d60>] return[call[name[indices]][name[biggestOverlapSubsetIdxs]]]
keyword[def] identifier[_getPrototypes] ( identifier[indices] , identifier[overlaps] , identifier[topNumber] = literal[int] ): literal[string] identifier[n] = identifier[numpy] . identifier[roots] ([ literal[int] ,- literal[int] ,- literal[int] * identifier[len] ( identifier[overlaps] )]). identifier[max] () identifier[k] = identifier[len] ( identifier[indices] ) identifier[indices] = identifier[numpy] . identifier[array] ( identifier[indices] , identifier[dtype] = identifier[int] ) identifier[rowIdxs] = identifier[numpy] . identifier[ndarray] (( identifier[k] , identifier[k] - literal[int] ), identifier[dtype] = identifier[int] ) identifier[colIdxs] = identifier[numpy] . identifier[ndarray] (( identifier[k] , identifier[k] - literal[int] ), identifier[dtype] = identifier[int] ) keyword[for] identifier[i] keyword[in] identifier[xrange] ( identifier[k] ): identifier[rowIdxs] [ identifier[i] ,:]= identifier[indices] [ identifier[i] ] identifier[colIdxs] [ identifier[i] ,: identifier[i] ]= identifier[indices] [: identifier[i] ] identifier[colIdxs] [ identifier[i] , identifier[i] :]= identifier[indices] [ identifier[i] + literal[int] :] identifier[idx] = identifier[HierarchicalClustering] . identifier[_condensedIndex] ( identifier[rowIdxs] , identifier[colIdxs] , identifier[n] ) identifier[subsampledOverlaps] = identifier[overlaps] [ identifier[idx] ] identifier[meanSubsampledOverlaps] = identifier[subsampledOverlaps] . identifier[mean] ( literal[int] ) identifier[biggestOverlapSubsetIdxs] = identifier[numpy] . identifier[argsort] ( - identifier[meanSubsampledOverlaps] )[: identifier[topNumber] ] keyword[return] identifier[indices] [ identifier[biggestOverlapSubsetIdxs] ]
def _getPrototypes(indices, overlaps, topNumber=1): """ Given a compressed overlap array and a set of indices specifying a subset of those in that array, return the set of topNumber indices of vectors that have maximum average overlap with other vectors in `indices`. @param indices (arraylike) Array of indices for which to get prototypes. @param overlaps (numpy.ndarray) Condensed array of overlaps of the form returned by _computeOverlaps(). @param topNumber (int) The number of prototypes to return. Optional, defaults to 1. @returns (numpy.ndarray) Array of indices of prototypes """ # find the number of data points based on the length of the overlap array # solves for n: len(overlaps) = n(n-1)/2 n = numpy.roots([1, -1, -2 * len(overlaps)]).max() k = len(indices) indices = numpy.array(indices, dtype=int) rowIdxs = numpy.ndarray((k, k - 1), dtype=int) colIdxs = numpy.ndarray((k, k - 1), dtype=int) for i in xrange(k): rowIdxs[i, :] = indices[i] colIdxs[i, :i] = indices[:i] colIdxs[i, i:] = indices[i + 1:] # depends on [control=['for'], data=['i']] idx = HierarchicalClustering._condensedIndex(rowIdxs, colIdxs, n) subsampledOverlaps = overlaps[idx] meanSubsampledOverlaps = subsampledOverlaps.mean(1) biggestOverlapSubsetIdxs = numpy.argsort(-meanSubsampledOverlaps)[:topNumber] return indices[biggestOverlapSubsetIdxs]
def visan(name=None): """ Creates the grammar for a V-ISAN code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'V-ISAN Field' field = pp.Regex('[0-9]{25}') field.setName(name) return field.setResultsName('visan')
def function[visan, parameter[name]]: constant[ Creates the grammar for a V-ISAN code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field ] if compare[name[name] is constant[None]] begin[:] variable[name] assign[=] constant[V-ISAN Field] variable[field] assign[=] call[name[pp].Regex, parameter[constant[[0-9]{25}]]] call[name[field].setName, parameter[name[name]]] return[call[name[field].setResultsName, parameter[constant[visan]]]]
keyword[def] identifier[visan] ( identifier[name] = keyword[None] ): literal[string] keyword[if] identifier[name] keyword[is] keyword[None] : identifier[name] = literal[string] identifier[field] = identifier[pp] . identifier[Regex] ( literal[string] ) identifier[field] . identifier[setName] ( identifier[name] ) keyword[return] identifier[field] . identifier[setResultsName] ( literal[string] )
def visan(name=None): """ Creates the grammar for a V-ISAN code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'V-ISAN Field' # depends on [control=['if'], data=['name']] field = pp.Regex('[0-9]{25}') field.setName(name) return field.setResultsName('visan')
def mosaic(logger, itemlist, fov_deg=None): """ Parameters ---------- logger : logger object a logger object passed to created AstroImage instances itemlist : sequence like a sequence of either filenames or AstroImage instances """ if isinstance(itemlist[0], AstroImage.AstroImage): image0 = itemlist[0] name = image0.get('name', 'image0') else: # Assume it is a file and load it filepath = itemlist[0] logger.info("Reading file '%s' ..." % (filepath)) image0 = AstroImage.AstroImage(logger=logger) image0.load_file(filepath) name = filepath ra_deg, dec_deg = image0.get_keywords_list('CRVAL1', 'CRVAL2') header = image0.get_header() (rot_deg, cdelt1, cdelt2) = wcs.get_rotation_and_scale(header) logger.debug("image0 rot=%f cdelt1=%f cdelt2=%f" % (rot_deg, cdelt1, cdelt2)) px_scale = math.fabs(cdelt1) expand = False if fov_deg is None: # TODO: calculate fov? expand = True cdbase = [np.sign(cdelt1), np.sign(cdelt2)] img_mosaic = dp.create_blank_image(ra_deg, dec_deg, fov_deg, px_scale, rot_deg, cdbase=cdbase, logger=logger) header = img_mosaic.get_header() (rot, cdelt1, cdelt2) = wcs.get_rotation_and_scale(header) logger.debug("mosaic rot=%f cdelt1=%f cdelt2=%f" % (rot, cdelt1, cdelt2)) logger.debug("Processing '%s' ..." % (name)) tup = img_mosaic.mosaic_inline([image0], allow_expand=expand) logger.debug("placement %s" % (str(tup))) count = 1 for item in itemlist[1:]: if isinstance(item, AstroImage.AstroImage): image = item name = image.get('name', 'image%d' % (count)) else: # Create and load the image filepath = item logger.info("Reading file '%s' ..." % (filepath)) image = AstroImage.AstroImage(logger=logger) image.load_file(filepath) logger.debug("Inlining '%s' ..." % (name)) tup = img_mosaic.mosaic_inline([image]) logger.debug("placement %s" % (str(tup))) count += 1 logger.info("Done.") return img_mosaic
def function[mosaic, parameter[logger, itemlist, fov_deg]]: constant[ Parameters ---------- logger : logger object a logger object passed to created AstroImage instances itemlist : sequence like a sequence of either filenames or AstroImage instances ] if call[name[isinstance], parameter[call[name[itemlist]][constant[0]], name[AstroImage].AstroImage]] begin[:] variable[image0] assign[=] call[name[itemlist]][constant[0]] variable[name] assign[=] call[name[image0].get, parameter[constant[name], constant[image0]]] <ast.Tuple object at 0x7da1b0efb460> assign[=] call[name[image0].get_keywords_list, parameter[constant[CRVAL1], constant[CRVAL2]]] variable[header] assign[=] call[name[image0].get_header, parameter[]] <ast.Tuple object at 0x7da1b0efb1c0> assign[=] call[name[wcs].get_rotation_and_scale, parameter[name[header]]] call[name[logger].debug, parameter[binary_operation[constant[image0 rot=%f cdelt1=%f cdelt2=%f] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b0efaef0>, <ast.Name object at 0x7da1b0efaec0>, <ast.Name object at 0x7da1b0efae90>]]]]] variable[px_scale] assign[=] call[name[math].fabs, parameter[name[cdelt1]]] variable[expand] assign[=] constant[False] if compare[name[fov_deg] is constant[None]] begin[:] variable[expand] assign[=] constant[True] variable[cdbase] assign[=] list[[<ast.Call object at 0x7da1b0efaaa0>, <ast.Call object at 0x7da1b0efa9e0>]] variable[img_mosaic] assign[=] call[name[dp].create_blank_image, parameter[name[ra_deg], name[dec_deg], name[fov_deg], name[px_scale], name[rot_deg]]] variable[header] assign[=] call[name[img_mosaic].get_header, parameter[]] <ast.Tuple object at 0x7da1b0efa530> assign[=] call[name[wcs].get_rotation_and_scale, parameter[name[header]]] call[name[logger].debug, parameter[binary_operation[constant[mosaic rot=%f cdelt1=%f cdelt2=%f] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b0efa260>, <ast.Name object at 0x7da1b0efa230>, <ast.Name object at 0x7da1b0efa200>]]]]] call[name[logger].debug, parameter[binary_operation[constant[Processing '%s' ...] <ast.Mod object at 0x7da2590d6920> name[name]]]] variable[tup] assign[=] call[name[img_mosaic].mosaic_inline, parameter[list[[<ast.Name object at 0x7da1b0ef9f00>]]]] call[name[logger].debug, parameter[binary_operation[constant[placement %s] <ast.Mod object at 0x7da2590d6920> call[name[str], parameter[name[tup]]]]]] variable[count] assign[=] constant[1] for taget[name[item]] in starred[call[name[itemlist]][<ast.Slice object at 0x7da1b0ef9b40>]] begin[:] if call[name[isinstance], parameter[name[item], name[AstroImage].AstroImage]] begin[:] variable[image] assign[=] name[item] variable[name] assign[=] call[name[image].get, parameter[constant[name], binary_operation[constant[image%d] <ast.Mod object at 0x7da2590d6920> name[count]]]] call[name[logger].debug, parameter[binary_operation[constant[Inlining '%s' ...] <ast.Mod object at 0x7da2590d6920> name[name]]]] variable[tup] assign[=] call[name[img_mosaic].mosaic_inline, parameter[list[[<ast.Name object at 0x7da1b0ef86a0>]]]] call[name[logger].debug, parameter[binary_operation[constant[placement %s] <ast.Mod object at 0x7da2590d6920> call[name[str], parameter[name[tup]]]]]] <ast.AugAssign object at 0x7da1b0ef8490> call[name[logger].info, parameter[constant[Done.]]] return[name[img_mosaic]]
keyword[def] identifier[mosaic] ( identifier[logger] , identifier[itemlist] , identifier[fov_deg] = keyword[None] ): literal[string] keyword[if] identifier[isinstance] ( identifier[itemlist] [ literal[int] ], identifier[AstroImage] . identifier[AstroImage] ): identifier[image0] = identifier[itemlist] [ literal[int] ] identifier[name] = identifier[image0] . identifier[get] ( literal[string] , literal[string] ) keyword[else] : identifier[filepath] = identifier[itemlist] [ literal[int] ] identifier[logger] . identifier[info] ( literal[string] %( identifier[filepath] )) identifier[image0] = identifier[AstroImage] . identifier[AstroImage] ( identifier[logger] = identifier[logger] ) identifier[image0] . identifier[load_file] ( identifier[filepath] ) identifier[name] = identifier[filepath] identifier[ra_deg] , identifier[dec_deg] = identifier[image0] . identifier[get_keywords_list] ( literal[string] , literal[string] ) identifier[header] = identifier[image0] . identifier[get_header] () ( identifier[rot_deg] , identifier[cdelt1] , identifier[cdelt2] )= identifier[wcs] . identifier[get_rotation_and_scale] ( identifier[header] ) identifier[logger] . identifier[debug] ( literal[string] %( identifier[rot_deg] , identifier[cdelt1] , identifier[cdelt2] )) identifier[px_scale] = identifier[math] . identifier[fabs] ( identifier[cdelt1] ) identifier[expand] = keyword[False] keyword[if] identifier[fov_deg] keyword[is] keyword[None] : identifier[expand] = keyword[True] identifier[cdbase] =[ identifier[np] . identifier[sign] ( identifier[cdelt1] ), identifier[np] . identifier[sign] ( identifier[cdelt2] )] identifier[img_mosaic] = identifier[dp] . identifier[create_blank_image] ( identifier[ra_deg] , identifier[dec_deg] , identifier[fov_deg] , identifier[px_scale] , identifier[rot_deg] , identifier[cdbase] = identifier[cdbase] , identifier[logger] = identifier[logger] ) identifier[header] = identifier[img_mosaic] . identifier[get_header] () ( identifier[rot] , identifier[cdelt1] , identifier[cdelt2] )= identifier[wcs] . identifier[get_rotation_and_scale] ( identifier[header] ) identifier[logger] . identifier[debug] ( literal[string] %( identifier[rot] , identifier[cdelt1] , identifier[cdelt2] )) identifier[logger] . identifier[debug] ( literal[string] %( identifier[name] )) identifier[tup] = identifier[img_mosaic] . identifier[mosaic_inline] ([ identifier[image0] ], identifier[allow_expand] = identifier[expand] ) identifier[logger] . identifier[debug] ( literal[string] %( identifier[str] ( identifier[tup] ))) identifier[count] = literal[int] keyword[for] identifier[item] keyword[in] identifier[itemlist] [ literal[int] :]: keyword[if] identifier[isinstance] ( identifier[item] , identifier[AstroImage] . identifier[AstroImage] ): identifier[image] = identifier[item] identifier[name] = identifier[image] . identifier[get] ( literal[string] , literal[string] %( identifier[count] )) keyword[else] : identifier[filepath] = identifier[item] identifier[logger] . identifier[info] ( literal[string] %( identifier[filepath] )) identifier[image] = identifier[AstroImage] . identifier[AstroImage] ( identifier[logger] = identifier[logger] ) identifier[image] . identifier[load_file] ( identifier[filepath] ) identifier[logger] . identifier[debug] ( literal[string] %( identifier[name] )) identifier[tup] = identifier[img_mosaic] . identifier[mosaic_inline] ([ identifier[image] ]) identifier[logger] . identifier[debug] ( literal[string] %( identifier[str] ( identifier[tup] ))) identifier[count] += literal[int] identifier[logger] . identifier[info] ( literal[string] ) keyword[return] identifier[img_mosaic]
def mosaic(logger, itemlist, fov_deg=None): """ Parameters ---------- logger : logger object a logger object passed to created AstroImage instances itemlist : sequence like a sequence of either filenames or AstroImage instances """ if isinstance(itemlist[0], AstroImage.AstroImage): image0 = itemlist[0] name = image0.get('name', 'image0') # depends on [control=['if'], data=[]] else: # Assume it is a file and load it filepath = itemlist[0] logger.info("Reading file '%s' ..." % filepath) image0 = AstroImage.AstroImage(logger=logger) image0.load_file(filepath) name = filepath (ra_deg, dec_deg) = image0.get_keywords_list('CRVAL1', 'CRVAL2') header = image0.get_header() (rot_deg, cdelt1, cdelt2) = wcs.get_rotation_and_scale(header) logger.debug('image0 rot=%f cdelt1=%f cdelt2=%f' % (rot_deg, cdelt1, cdelt2)) px_scale = math.fabs(cdelt1) expand = False if fov_deg is None: # TODO: calculate fov? expand = True # depends on [control=['if'], data=[]] cdbase = [np.sign(cdelt1), np.sign(cdelt2)] img_mosaic = dp.create_blank_image(ra_deg, dec_deg, fov_deg, px_scale, rot_deg, cdbase=cdbase, logger=logger) header = img_mosaic.get_header() (rot, cdelt1, cdelt2) = wcs.get_rotation_and_scale(header) logger.debug('mosaic rot=%f cdelt1=%f cdelt2=%f' % (rot, cdelt1, cdelt2)) logger.debug("Processing '%s' ..." % name) tup = img_mosaic.mosaic_inline([image0], allow_expand=expand) logger.debug('placement %s' % str(tup)) count = 1 for item in itemlist[1:]: if isinstance(item, AstroImage.AstroImage): image = item name = image.get('name', 'image%d' % count) # depends on [control=['if'], data=[]] else: # Create and load the image filepath = item logger.info("Reading file '%s' ..." % filepath) image = AstroImage.AstroImage(logger=logger) image.load_file(filepath) logger.debug("Inlining '%s' ..." % name) tup = img_mosaic.mosaic_inline([image]) logger.debug('placement %s' % str(tup)) count += 1 # depends on [control=['for'], data=['item']] logger.info('Done.') return img_mosaic
def add(symbol: str, date, value, currency: str): """ Add individual price """ symbol = symbol.upper() currency = currency.upper() app = PriceDbApplication() price = PriceModel() # security = SecuritySymbol("", "") price.symbol.parse(symbol) # price.symbol.mnemonic = price.symbol.mnemonic.upper() # date_str = f"{date}" # date_format = "%Y-%m-%d" # if time: # date_str = f"{date_str}T{time}" # date_format += "T%H:%M:%S" # datum.from_iso_date_string(date) # price.datetime = datetime.strptime(date_str, date_format) price.datum.from_iso_date_string(date) price.value = Decimal(value) price.currency = currency app.add_price(price) app.save() click.echo("Price added.")
def function[add, parameter[symbol, date, value, currency]]: constant[ Add individual price ] variable[symbol] assign[=] call[name[symbol].upper, parameter[]] variable[currency] assign[=] call[name[currency].upper, parameter[]] variable[app] assign[=] call[name[PriceDbApplication], parameter[]] variable[price] assign[=] call[name[PriceModel], parameter[]] call[name[price].symbol.parse, parameter[name[symbol]]] call[name[price].datum.from_iso_date_string, parameter[name[date]]] name[price].value assign[=] call[name[Decimal], parameter[name[value]]] name[price].currency assign[=] name[currency] call[name[app].add_price, parameter[name[price]]] call[name[app].save, parameter[]] call[name[click].echo, parameter[constant[Price added.]]]
keyword[def] identifier[add] ( identifier[symbol] : identifier[str] , identifier[date] , identifier[value] , identifier[currency] : identifier[str] ): literal[string] identifier[symbol] = identifier[symbol] . identifier[upper] () identifier[currency] = identifier[currency] . identifier[upper] () identifier[app] = identifier[PriceDbApplication] () identifier[price] = identifier[PriceModel] () identifier[price] . identifier[symbol] . identifier[parse] ( identifier[symbol] ) identifier[price] . identifier[datum] . identifier[from_iso_date_string] ( identifier[date] ) identifier[price] . identifier[value] = identifier[Decimal] ( identifier[value] ) identifier[price] . identifier[currency] = identifier[currency] identifier[app] . identifier[add_price] ( identifier[price] ) identifier[app] . identifier[save] () identifier[click] . identifier[echo] ( literal[string] )
def add(symbol: str, date, value, currency: str): """ Add individual price """ symbol = symbol.upper() currency = currency.upper() app = PriceDbApplication() price = PriceModel() # security = SecuritySymbol("", "") price.symbol.parse(symbol) # price.symbol.mnemonic = price.symbol.mnemonic.upper() # date_str = f"{date}" # date_format = "%Y-%m-%d" # if time: # date_str = f"{date_str}T{time}" # date_format += "T%H:%M:%S" # datum.from_iso_date_string(date) # price.datetime = datetime.strptime(date_str, date_format) price.datum.from_iso_date_string(date) price.value = Decimal(value) price.currency = currency app.add_price(price) app.save() click.echo('Price added.')
def merge_scans(workdir, fileroot, scans, snrmin=0, snrmax=999): """ Merge cands/noise files over all scans """ pkllist = [ff for ff in [os.path.join(workdir, 'cands_{0}_sc{1}.pkl'.format(fileroot, scan)) for scan in scans] if os.path.exists(ff)] merge_cands(pkllist, outroot=fileroot, snrmin=snrmin, snrmax=snrmax) pkllist = [ff for ff in [os.path.join(workdir, 'noise_{0}_sc{1}.pkl'.format(fileroot, scan)) for scan in scans] if os.path.exists(ff)] merge_noises(pkllist, fileroot)
def function[merge_scans, parameter[workdir, fileroot, scans, snrmin, snrmax]]: constant[ Merge cands/noise files over all scans ] variable[pkllist] assign[=] <ast.ListComp object at 0x7da1b26f50c0> call[name[merge_cands], parameter[name[pkllist]]] variable[pkllist] assign[=] <ast.ListComp object at 0x7da1b26f47f0> call[name[merge_noises], parameter[name[pkllist], name[fileroot]]]
keyword[def] identifier[merge_scans] ( identifier[workdir] , identifier[fileroot] , identifier[scans] , identifier[snrmin] = literal[int] , identifier[snrmax] = literal[int] ): literal[string] identifier[pkllist] =[ identifier[ff] keyword[for] identifier[ff] keyword[in] [ identifier[os] . identifier[path] . identifier[join] ( identifier[workdir] , literal[string] . identifier[format] ( identifier[fileroot] , identifier[scan] )) keyword[for] identifier[scan] keyword[in] identifier[scans] ] keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[ff] )] identifier[merge_cands] ( identifier[pkllist] , identifier[outroot] = identifier[fileroot] , identifier[snrmin] = identifier[snrmin] , identifier[snrmax] = identifier[snrmax] ) identifier[pkllist] =[ identifier[ff] keyword[for] identifier[ff] keyword[in] [ identifier[os] . identifier[path] . identifier[join] ( identifier[workdir] , literal[string] . identifier[format] ( identifier[fileroot] , identifier[scan] )) keyword[for] identifier[scan] keyword[in] identifier[scans] ] keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[ff] )] identifier[merge_noises] ( identifier[pkllist] , identifier[fileroot] )
def merge_scans(workdir, fileroot, scans, snrmin=0, snrmax=999): """ Merge cands/noise files over all scans """ pkllist = [ff for ff in [os.path.join(workdir, 'cands_{0}_sc{1}.pkl'.format(fileroot, scan)) for scan in scans] if os.path.exists(ff)] merge_cands(pkllist, outroot=fileroot, snrmin=snrmin, snrmax=snrmax) pkllist = [ff for ff in [os.path.join(workdir, 'noise_{0}_sc{1}.pkl'.format(fileroot, scan)) for scan in scans] if os.path.exists(ff)] merge_noises(pkllist, fileroot)
def has_datastore(self): # type: () -> bool """Check if the resource has a datastore. Returns: bool: Whether the resource has a datastore or not """ success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id', self.actions()['datastore_search']) if not success: logger.debug(result) else: if result: return True return False
def function[has_datastore, parameter[self]]: constant[Check if the resource has a datastore. Returns: bool: Whether the resource has a datastore or not ] <ast.Tuple object at 0x7da1b0e33070> assign[=] call[name[self]._read_from_hdx, parameter[constant[datastore], call[name[self].data][constant[id]], constant[resource_id], call[call[name[self].actions, parameter[]]][constant[datastore_search]]]] if <ast.UnaryOp object at 0x7da1b0e30820> begin[:] call[name[logger].debug, parameter[name[result]]] return[constant[False]]
keyword[def] identifier[has_datastore] ( identifier[self] ): literal[string] identifier[success] , identifier[result] = identifier[self] . identifier[_read_from_hdx] ( literal[string] , identifier[self] . identifier[data] [ literal[string] ], literal[string] , identifier[self] . identifier[actions] ()[ literal[string] ]) keyword[if] keyword[not] identifier[success] : identifier[logger] . identifier[debug] ( identifier[result] ) keyword[else] : keyword[if] identifier[result] : keyword[return] keyword[True] keyword[return] keyword[False]
def has_datastore(self): # type: () -> bool 'Check if the resource has a datastore.\n\n Returns:\n bool: Whether the resource has a datastore or not\n ' (success, result) = self._read_from_hdx('datastore', self.data['id'], 'resource_id', self.actions()['datastore_search']) if not success: logger.debug(result) # depends on [control=['if'], data=[]] elif result: return True # depends on [control=['if'], data=[]] return False
def generate_to(self, worksheet, row): '''Generate row report. Generates a row report of the item represented by this instance and inserts it into a given worksheet at a specified row number. :param worksheet: Reference to a worksheet in which to insert row report. :param row: Row number. ''' super(ItemImage, self).generate_to(worksheet, row) embedded = False fmt = self.generator.formats worksheet.write(row, 3, "image", fmt['type_image']) worksheet.write_url(row, 5, self.data[0], fmt['link']) try: if self.data: image = self.resize_image(StringIO(self.data[1])) worksheet.insert_image(row, 4, 'image', {'image_data': image}) embedded = True except: # We probably wrongly ignoring the exception. Should really at # least log it somewhere. pass # Attempt to retrieve image data from the image URL if image data not # present already above or something failed whilst recreating image # from base64 encoding. if not embedded: url = self.data[0] if url: image = self.resize_image(BytesIO(urlopen(url).read())) worksheet.insert_image(row, 4, url, {'image_data': image}) embedded = True else: worksheet.write(row, 4, '<unavailable>') if embedded: worksheet.set_row(row, 40)
def function[generate_to, parameter[self, worksheet, row]]: constant[Generate row report. Generates a row report of the item represented by this instance and inserts it into a given worksheet at a specified row number. :param worksheet: Reference to a worksheet in which to insert row report. :param row: Row number. ] call[call[name[super], parameter[name[ItemImage], name[self]]].generate_to, parameter[name[worksheet], name[row]]] variable[embedded] assign[=] constant[False] variable[fmt] assign[=] name[self].generator.formats call[name[worksheet].write, parameter[name[row], constant[3], constant[image], call[name[fmt]][constant[type_image]]]] call[name[worksheet].write_url, parameter[name[row], constant[5], call[name[self].data][constant[0]], call[name[fmt]][constant[link]]]] <ast.Try object at 0x7da1b13009a0> if <ast.UnaryOp object at 0x7da1b13021a0> begin[:] variable[url] assign[=] call[name[self].data][constant[0]] if name[url] begin[:] variable[image] assign[=] call[name[self].resize_image, parameter[call[name[BytesIO], parameter[call[call[name[urlopen], parameter[name[url]]].read, parameter[]]]]]] call[name[worksheet].insert_image, parameter[name[row], constant[4], name[url], dictionary[[<ast.Constant object at 0x7da1b13021d0>], [<ast.Name object at 0x7da1b13017b0>]]]] variable[embedded] assign[=] constant[True] if name[embedded] begin[:] call[name[worksheet].set_row, parameter[name[row], constant[40]]]
keyword[def] identifier[generate_to] ( identifier[self] , identifier[worksheet] , identifier[row] ): literal[string] identifier[super] ( identifier[ItemImage] , identifier[self] ). identifier[generate_to] ( identifier[worksheet] , identifier[row] ) identifier[embedded] = keyword[False] identifier[fmt] = identifier[self] . identifier[generator] . identifier[formats] identifier[worksheet] . identifier[write] ( identifier[row] , literal[int] , literal[string] , identifier[fmt] [ literal[string] ]) identifier[worksheet] . identifier[write_url] ( identifier[row] , literal[int] , identifier[self] . identifier[data] [ literal[int] ], identifier[fmt] [ literal[string] ]) keyword[try] : keyword[if] identifier[self] . identifier[data] : identifier[image] = identifier[self] . identifier[resize_image] ( identifier[StringIO] ( identifier[self] . identifier[data] [ literal[int] ])) identifier[worksheet] . identifier[insert_image] ( identifier[row] , literal[int] , literal[string] , { literal[string] : identifier[image] }) identifier[embedded] = keyword[True] keyword[except] : keyword[pass] keyword[if] keyword[not] identifier[embedded] : identifier[url] = identifier[self] . identifier[data] [ literal[int] ] keyword[if] identifier[url] : identifier[image] = identifier[self] . identifier[resize_image] ( identifier[BytesIO] ( identifier[urlopen] ( identifier[url] ). identifier[read] ())) identifier[worksheet] . identifier[insert_image] ( identifier[row] , literal[int] , identifier[url] ,{ literal[string] : identifier[image] }) identifier[embedded] = keyword[True] keyword[else] : identifier[worksheet] . identifier[write] ( identifier[row] , literal[int] , literal[string] ) keyword[if] identifier[embedded] : identifier[worksheet] . identifier[set_row] ( identifier[row] , literal[int] )
def generate_to(self, worksheet, row): """Generate row report. Generates a row report of the item represented by this instance and inserts it into a given worksheet at a specified row number. :param worksheet: Reference to a worksheet in which to insert row report. :param row: Row number. """ super(ItemImage, self).generate_to(worksheet, row) embedded = False fmt = self.generator.formats worksheet.write(row, 3, 'image', fmt['type_image']) worksheet.write_url(row, 5, self.data[0], fmt['link']) try: if self.data: image = self.resize_image(StringIO(self.data[1])) worksheet.insert_image(row, 4, 'image', {'image_data': image}) embedded = True # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except: # We probably wrongly ignoring the exception. Should really at # least log it somewhere. pass # depends on [control=['except'], data=[]] # Attempt to retrieve image data from the image URL if image data not # present already above or something failed whilst recreating image # from base64 encoding. if not embedded: url = self.data[0] if url: image = self.resize_image(BytesIO(urlopen(url).read())) worksheet.insert_image(row, 4, url, {'image_data': image}) embedded = True # depends on [control=['if'], data=[]] else: worksheet.write(row, 4, '<unavailable>') # depends on [control=['if'], data=[]] if embedded: worksheet.set_row(row, 40) # depends on [control=['if'], data=[]]
def setFilterData(self, key, value): """ Sets the filtering information for the given key to the inputed value. :param key | <str> value | <str> """ self._filterData[nativestring(key)] = nativestring(value)
def function[setFilterData, parameter[self, key, value]]: constant[ Sets the filtering information for the given key to the inputed value. :param key | <str> value | <str> ] call[name[self]._filterData][call[name[nativestring], parameter[name[key]]]] assign[=] call[name[nativestring], parameter[name[value]]]
keyword[def] identifier[setFilterData] ( identifier[self] , identifier[key] , identifier[value] ): literal[string] identifier[self] . identifier[_filterData] [ identifier[nativestring] ( identifier[key] )]= identifier[nativestring] ( identifier[value] )
def setFilterData(self, key, value): """ Sets the filtering information for the given key to the inputed value. :param key | <str> value | <str> """ self._filterData[nativestring(key)] = nativestring(value)
def rank_from_shape(shape_tensor_fn, tensorshape=None): """Computes `rank` given a `Tensor`'s `shape`.""" if tensorshape is None: shape_tensor = (shape_tensor_fn() if callable(shape_tensor_fn) else shape_tensor_fn) if (hasattr(shape_tensor, 'shape') and hasattr(shape_tensor.shape, 'num_elements')): ndims_ = tensorshape_util.num_elements(shape_tensor.shape) else: ndims_ = len(shape_tensor) ndims_fn = lambda: tf.size(input=shape_tensor) else: ndims_ = tensorshape_util.rank(tensorshape) ndims_fn = lambda: tf.size(input=shape_tensor_fn() # pylint: disable=g-long-lambda if callable(shape_tensor_fn) else shape_tensor_fn) return ndims_fn() if ndims_ is None else ndims_
def function[rank_from_shape, parameter[shape_tensor_fn, tensorshape]]: constant[Computes `rank` given a `Tensor`'s `shape`.] if compare[name[tensorshape] is constant[None]] begin[:] variable[shape_tensor] assign[=] <ast.IfExp object at 0x7da1b0211a80> if <ast.BoolOp object at 0x7da1b0212800> begin[:] variable[ndims_] assign[=] call[name[tensorshape_util].num_elements, parameter[name[shape_tensor].shape]] variable[ndims_fn] assign[=] <ast.Lambda object at 0x7da1b03229e0> return[<ast.IfExp object at 0x7da1b03238b0>]
keyword[def] identifier[rank_from_shape] ( identifier[shape_tensor_fn] , identifier[tensorshape] = keyword[None] ): literal[string] keyword[if] identifier[tensorshape] keyword[is] keyword[None] : identifier[shape_tensor] =( identifier[shape_tensor_fn] () keyword[if] identifier[callable] ( identifier[shape_tensor_fn] ) keyword[else] identifier[shape_tensor_fn] ) keyword[if] ( identifier[hasattr] ( identifier[shape_tensor] , literal[string] ) keyword[and] identifier[hasattr] ( identifier[shape_tensor] . identifier[shape] , literal[string] )): identifier[ndims_] = identifier[tensorshape_util] . identifier[num_elements] ( identifier[shape_tensor] . identifier[shape] ) keyword[else] : identifier[ndims_] = identifier[len] ( identifier[shape_tensor] ) identifier[ndims_fn] = keyword[lambda] : identifier[tf] . identifier[size] ( identifier[input] = identifier[shape_tensor] ) keyword[else] : identifier[ndims_] = identifier[tensorshape_util] . identifier[rank] ( identifier[tensorshape] ) identifier[ndims_fn] = keyword[lambda] : identifier[tf] . identifier[size] ( identifier[input] = identifier[shape_tensor_fn] () keyword[if] identifier[callable] ( identifier[shape_tensor_fn] ) keyword[else] identifier[shape_tensor_fn] ) keyword[return] identifier[ndims_fn] () keyword[if] identifier[ndims_] keyword[is] keyword[None] keyword[else] identifier[ndims_]
def rank_from_shape(shape_tensor_fn, tensorshape=None): """Computes `rank` given a `Tensor`'s `shape`.""" if tensorshape is None: shape_tensor = shape_tensor_fn() if callable(shape_tensor_fn) else shape_tensor_fn if hasattr(shape_tensor, 'shape') and hasattr(shape_tensor.shape, 'num_elements'): ndims_ = tensorshape_util.num_elements(shape_tensor.shape) # depends on [control=['if'], data=[]] else: ndims_ = len(shape_tensor) ndims_fn = lambda : tf.size(input=shape_tensor) # depends on [control=['if'], data=[]] else: ndims_ = tensorshape_util.rank(tensorshape) # pylint: disable=g-long-lambda ndims_fn = lambda : tf.size(input=shape_tensor_fn() if callable(shape_tensor_fn) else shape_tensor_fn) return ndims_fn() if ndims_ is None else ndims_
def jens_transformation_beta(graph: BELGraph) -> DiGraph: """Apply Jens' Transformation (Type 2) to the graph. 1. Induce a sub-graph over causal and correlative relations 2. Transform edges with the following rules: - increases => backwards decreases - decreases => decreases - positive correlation => delete - negative correlation => two way decreases The resulting graph can be used to search for 3-cycles, which now symbolize stable triples where ``A -> B``, ``A -| C`` and ``B negativeCorrelation C``. """ result = DiGraph() for u, v, d in graph.edges(data=True): relation = d[RELATION] if relation == NEGATIVE_CORRELATION: result.add_edge(u, v) result.add_edge(v, u) elif relation in CAUSAL_INCREASE_RELATIONS: result.add_edge(v, u) elif relation in CAUSAL_DECREASE_RELATIONS: result.add_edge(u, v) return result
def function[jens_transformation_beta, parameter[graph]]: constant[Apply Jens' Transformation (Type 2) to the graph. 1. Induce a sub-graph over causal and correlative relations 2. Transform edges with the following rules: - increases => backwards decreases - decreases => decreases - positive correlation => delete - negative correlation => two way decreases The resulting graph can be used to search for 3-cycles, which now symbolize stable triples where ``A -> B``, ``A -| C`` and ``B negativeCorrelation C``. ] variable[result] assign[=] call[name[DiGraph], parameter[]] for taget[tuple[[<ast.Name object at 0x7da1afe51cc0>, <ast.Name object at 0x7da1afe53fa0>, <ast.Name object at 0x7da1afe511e0>]]] in starred[call[name[graph].edges, parameter[]]] begin[:] variable[relation] assign[=] call[name[d]][name[RELATION]] if compare[name[relation] equal[==] name[NEGATIVE_CORRELATION]] begin[:] call[name[result].add_edge, parameter[name[u], name[v]]] call[name[result].add_edge, parameter[name[v], name[u]]] return[name[result]]
keyword[def] identifier[jens_transformation_beta] ( identifier[graph] : identifier[BELGraph] )-> identifier[DiGraph] : literal[string] identifier[result] = identifier[DiGraph] () keyword[for] identifier[u] , identifier[v] , identifier[d] keyword[in] identifier[graph] . identifier[edges] ( identifier[data] = keyword[True] ): identifier[relation] = identifier[d] [ identifier[RELATION] ] keyword[if] identifier[relation] == identifier[NEGATIVE_CORRELATION] : identifier[result] . identifier[add_edge] ( identifier[u] , identifier[v] ) identifier[result] . identifier[add_edge] ( identifier[v] , identifier[u] ) keyword[elif] identifier[relation] keyword[in] identifier[CAUSAL_INCREASE_RELATIONS] : identifier[result] . identifier[add_edge] ( identifier[v] , identifier[u] ) keyword[elif] identifier[relation] keyword[in] identifier[CAUSAL_DECREASE_RELATIONS] : identifier[result] . identifier[add_edge] ( identifier[u] , identifier[v] ) keyword[return] identifier[result]
def jens_transformation_beta(graph: BELGraph) -> DiGraph: """Apply Jens' Transformation (Type 2) to the graph. 1. Induce a sub-graph over causal and correlative relations 2. Transform edges with the following rules: - increases => backwards decreases - decreases => decreases - positive correlation => delete - negative correlation => two way decreases The resulting graph can be used to search for 3-cycles, which now symbolize stable triples where ``A -> B``, ``A -| C`` and ``B negativeCorrelation C``. """ result = DiGraph() for (u, v, d) in graph.edges(data=True): relation = d[RELATION] if relation == NEGATIVE_CORRELATION: result.add_edge(u, v) result.add_edge(v, u) # depends on [control=['if'], data=[]] elif relation in CAUSAL_INCREASE_RELATIONS: result.add_edge(v, u) # depends on [control=['if'], data=[]] elif relation in CAUSAL_DECREASE_RELATIONS: result.add_edge(u, v) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] return result
def setup_logging(self): """Set up self.logger This function is called after load_configuration() and after changing to new user/group IDs (if configured). Logging to syslog using the root logger is configured by default, you can override this method if you want something else. """ self.logger = logging.getLogger() if os.path.exists('/dev/log'): handler = SysLogHandler('/dev/log') else: handler = SysLogHandler() self.logger.addHandler(handler)
def function[setup_logging, parameter[self]]: constant[Set up self.logger This function is called after load_configuration() and after changing to new user/group IDs (if configured). Logging to syslog using the root logger is configured by default, you can override this method if you want something else. ] name[self].logger assign[=] call[name[logging].getLogger, parameter[]] if call[name[os].path.exists, parameter[constant[/dev/log]]] begin[:] variable[handler] assign[=] call[name[SysLogHandler], parameter[constant[/dev/log]]] call[name[self].logger.addHandler, parameter[name[handler]]]
keyword[def] identifier[setup_logging] ( identifier[self] ): literal[string] identifier[self] . identifier[logger] = identifier[logging] . identifier[getLogger] () keyword[if] identifier[os] . identifier[path] . identifier[exists] ( literal[string] ): identifier[handler] = identifier[SysLogHandler] ( literal[string] ) keyword[else] : identifier[handler] = identifier[SysLogHandler] () identifier[self] . identifier[logger] . identifier[addHandler] ( identifier[handler] )
def setup_logging(self): """Set up self.logger This function is called after load_configuration() and after changing to new user/group IDs (if configured). Logging to syslog using the root logger is configured by default, you can override this method if you want something else. """ self.logger = logging.getLogger() if os.path.exists('/dev/log'): handler = SysLogHandler('/dev/log') # depends on [control=['if'], data=[]] else: handler = SysLogHandler() self.logger.addHandler(handler)
def get_unique_schema_name(components, name, counter=0): """Function to generate a unique name based on the provided name and names already in the spec. Will append a number to the name to make it unique if the name is already in the spec. :param Components components: instance of the components of the spec :param string name: the name to use as a basis for the unique name :param int counter: the counter of the number of recursions :return: the unique name """ if name not in components._schemas: return name if not counter: # first time through recursion warnings.warn( "Multiple schemas resolved to the name {}. The name has been modified. " "Either manually add each of the schemas with a different name or " "provide a custom schema_name_resolver.".format(name), UserWarning, ) else: # subsequent recursions name = name[: -len(str(counter))] counter += 1 return get_unique_schema_name(components, name + str(counter), counter)
def function[get_unique_schema_name, parameter[components, name, counter]]: constant[Function to generate a unique name based on the provided name and names already in the spec. Will append a number to the name to make it unique if the name is already in the spec. :param Components components: instance of the components of the spec :param string name: the name to use as a basis for the unique name :param int counter: the counter of the number of recursions :return: the unique name ] if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[components]._schemas] begin[:] return[name[name]] if <ast.UnaryOp object at 0x7da1b18e5a50> begin[:] call[name[warnings].warn, parameter[call[constant[Multiple schemas resolved to the name {}. The name has been modified. Either manually add each of the schemas with a different name or provide a custom schema_name_resolver.].format, parameter[name[name]]], name[UserWarning]]] <ast.AugAssign object at 0x7da1b18e57b0> return[call[name[get_unique_schema_name], parameter[name[components], binary_operation[name[name] + call[name[str], parameter[name[counter]]]], name[counter]]]]
keyword[def] identifier[get_unique_schema_name] ( identifier[components] , identifier[name] , identifier[counter] = literal[int] ): literal[string] keyword[if] identifier[name] keyword[not] keyword[in] identifier[components] . identifier[_schemas] : keyword[return] identifier[name] keyword[if] keyword[not] identifier[counter] : identifier[warnings] . identifier[warn] ( literal[string] literal[string] literal[string] . identifier[format] ( identifier[name] ), identifier[UserWarning] , ) keyword[else] : identifier[name] = identifier[name] [:- identifier[len] ( identifier[str] ( identifier[counter] ))] identifier[counter] += literal[int] keyword[return] identifier[get_unique_schema_name] ( identifier[components] , identifier[name] + identifier[str] ( identifier[counter] ), identifier[counter] )
def get_unique_schema_name(components, name, counter=0): """Function to generate a unique name based on the provided name and names already in the spec. Will append a number to the name to make it unique if the name is already in the spec. :param Components components: instance of the components of the spec :param string name: the name to use as a basis for the unique name :param int counter: the counter of the number of recursions :return: the unique name """ if name not in components._schemas: return name # depends on [control=['if'], data=['name']] if not counter: # first time through recursion warnings.warn('Multiple schemas resolved to the name {}. The name has been modified. Either manually add each of the schemas with a different name or provide a custom schema_name_resolver.'.format(name), UserWarning) # depends on [control=['if'], data=[]] else: # subsequent recursions name = name[:-len(str(counter))] counter += 1 return get_unique_schema_name(components, name + str(counter), counter)