code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def _deserialize(self, value, attr, data): """Deserialize string value.""" value = super(TrimmedString, self)._deserialize(value, attr, data) return value.strip()
def function[_deserialize, parameter[self, value, attr, data]]: constant[Deserialize string value.] variable[value] assign[=] call[call[name[super], parameter[name[TrimmedString], name[self]]]._deserialize, parameter[name[value], name[attr], name[data]]] return[call[name[value].strip, parameter[]]]
keyword[def] identifier[_deserialize] ( identifier[self] , identifier[value] , identifier[attr] , identifier[data] ): literal[string] identifier[value] = identifier[super] ( identifier[TrimmedString] , identifier[self] ). identifier[_deserialize] ( identifier[value] , identifier[attr] , identifier[data] ) keyword[return] identifier[value] . identifier[strip] ()
def _deserialize(self, value, attr, data): """Deserialize string value.""" value = super(TrimmedString, self)._deserialize(value, attr, data) return value.strip()
def next_request(self): ''' Logic to handle getting a new url request, from a bunch of different queues ''' t = time.time() # update the redis queues every so often if t - self.update_time > self.update_interval: self.update_time = t self.create_queues() self.expire_queues() # update the ip address every so often if t - self.update_ip_time > self.ip_update_interval: self.update_ip_time = t self.update_ipaddress() self.report_self() item = self.find_item() if item: self.logger.debug("Found url to crawl {url}" \ .format(url=item['url'])) try: req = Request(item['url']) except ValueError: # need absolute url # need better url validation here req = Request('http://' + item['url']) try: if 'callback' in item and item['callback'] is not None: req.callback = getattr(self.spider, item['callback']) except AttributeError: self.logger.warn("Unable to find callback method") try: if 'errback' in item and item['errback'] is not None: req.errback = getattr(self.spider, item['errback']) except AttributeError: self.logger.warn("Unable to find errback method") if 'meta' in item: item = item['meta'] # defaults not in schema if 'curdepth' not in item: item['curdepth'] = 0 if "retry_times" not in item: item['retry_times'] = 0 for key in list(item.keys()): req.meta[key] = item[key] # extra check to add items to request if 'useragent' in item and item['useragent'] is not None: req.headers['User-Agent'] = item['useragent'] if 'cookie' in item and item['cookie'] is not None: if isinstance(item['cookie'], dict): req.cookies = item['cookie'] elif isinstance(item['cookie'], basestring): req.cookies = self.parse_cookie(item['cookie']) return req return None
def function[next_request, parameter[self]]: constant[ Logic to handle getting a new url request, from a bunch of different queues ] variable[t] assign[=] call[name[time].time, parameter[]] if compare[binary_operation[name[t] - name[self].update_time] greater[>] name[self].update_interval] begin[:] name[self].update_time assign[=] name[t] call[name[self].create_queues, parameter[]] call[name[self].expire_queues, parameter[]] if compare[binary_operation[name[t] - name[self].update_ip_time] greater[>] name[self].ip_update_interval] begin[:] name[self].update_ip_time assign[=] name[t] call[name[self].update_ipaddress, parameter[]] call[name[self].report_self, parameter[]] variable[item] assign[=] call[name[self].find_item, parameter[]] if name[item] begin[:] call[name[self].logger.debug, parameter[call[constant[Found url to crawl {url}].format, parameter[]]]] <ast.Try object at 0x7da18ede4d00> <ast.Try object at 0x7da18ede7340> <ast.Try object at 0x7da18ede71c0> if compare[constant[meta] in name[item]] begin[:] variable[item] assign[=] call[name[item]][constant[meta]] if compare[constant[curdepth] <ast.NotIn object at 0x7da2590d7190> name[item]] begin[:] call[name[item]][constant[curdepth]] assign[=] constant[0] if compare[constant[retry_times] <ast.NotIn object at 0x7da2590d7190> name[item]] begin[:] call[name[item]][constant[retry_times]] assign[=] constant[0] for taget[name[key]] in starred[call[name[list], parameter[call[name[item].keys, parameter[]]]]] begin[:] call[name[req].meta][name[key]] assign[=] call[name[item]][name[key]] if <ast.BoolOp object at 0x7da1b19da2c0> begin[:] call[name[req].headers][constant[User-Agent]] assign[=] call[name[item]][constant[useragent]] if <ast.BoolOp object at 0x7da1b19d9c00> begin[:] if call[name[isinstance], parameter[call[name[item]][constant[cookie]], name[dict]]] begin[:] name[req].cookies assign[=] call[name[item]][constant[cookie]] return[name[req]] return[constant[None]]
keyword[def] identifier[next_request] ( identifier[self] ): literal[string] identifier[t] = identifier[time] . identifier[time] () keyword[if] identifier[t] - identifier[self] . identifier[update_time] > identifier[self] . identifier[update_interval] : identifier[self] . identifier[update_time] = identifier[t] identifier[self] . identifier[create_queues] () identifier[self] . identifier[expire_queues] () keyword[if] identifier[t] - identifier[self] . identifier[update_ip_time] > identifier[self] . identifier[ip_update_interval] : identifier[self] . identifier[update_ip_time] = identifier[t] identifier[self] . identifier[update_ipaddress] () identifier[self] . identifier[report_self] () identifier[item] = identifier[self] . identifier[find_item] () keyword[if] identifier[item] : identifier[self] . identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[url] = identifier[item] [ literal[string] ])) keyword[try] : identifier[req] = identifier[Request] ( identifier[item] [ literal[string] ]) keyword[except] identifier[ValueError] : identifier[req] = identifier[Request] ( literal[string] + identifier[item] [ literal[string] ]) keyword[try] : keyword[if] literal[string] keyword[in] identifier[item] keyword[and] identifier[item] [ literal[string] ] keyword[is] keyword[not] keyword[None] : identifier[req] . identifier[callback] = identifier[getattr] ( identifier[self] . identifier[spider] , identifier[item] [ literal[string] ]) keyword[except] identifier[AttributeError] : identifier[self] . identifier[logger] . identifier[warn] ( literal[string] ) keyword[try] : keyword[if] literal[string] keyword[in] identifier[item] keyword[and] identifier[item] [ literal[string] ] keyword[is] keyword[not] keyword[None] : identifier[req] . identifier[errback] = identifier[getattr] ( identifier[self] . identifier[spider] , identifier[item] [ literal[string] ]) keyword[except] identifier[AttributeError] : identifier[self] . identifier[logger] . identifier[warn] ( literal[string] ) keyword[if] literal[string] keyword[in] identifier[item] : identifier[item] = identifier[item] [ literal[string] ] keyword[if] literal[string] keyword[not] keyword[in] identifier[item] : identifier[item] [ literal[string] ]= literal[int] keyword[if] literal[string] keyword[not] keyword[in] identifier[item] : identifier[item] [ literal[string] ]= literal[int] keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[item] . identifier[keys] ()): identifier[req] . identifier[meta] [ identifier[key] ]= identifier[item] [ identifier[key] ] keyword[if] literal[string] keyword[in] identifier[item] keyword[and] identifier[item] [ literal[string] ] keyword[is] keyword[not] keyword[None] : identifier[req] . identifier[headers] [ literal[string] ]= identifier[item] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[item] keyword[and] identifier[item] [ literal[string] ] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[isinstance] ( identifier[item] [ literal[string] ], identifier[dict] ): identifier[req] . identifier[cookies] = identifier[item] [ literal[string] ] keyword[elif] identifier[isinstance] ( identifier[item] [ literal[string] ], identifier[basestring] ): identifier[req] . identifier[cookies] = identifier[self] . identifier[parse_cookie] ( identifier[item] [ literal[string] ]) keyword[return] identifier[req] keyword[return] keyword[None]
def next_request(self): """ Logic to handle getting a new url request, from a bunch of different queues """ t = time.time() # update the redis queues every so often if t - self.update_time > self.update_interval: self.update_time = t self.create_queues() self.expire_queues() # depends on [control=['if'], data=[]] # update the ip address every so often if t - self.update_ip_time > self.ip_update_interval: self.update_ip_time = t self.update_ipaddress() self.report_self() # depends on [control=['if'], data=[]] item = self.find_item() if item: self.logger.debug('Found url to crawl {url}'.format(url=item['url'])) try: req = Request(item['url']) # depends on [control=['try'], data=[]] except ValueError: # need absolute url # need better url validation here req = Request('http://' + item['url']) # depends on [control=['except'], data=[]] try: if 'callback' in item and item['callback'] is not None: req.callback = getattr(self.spider, item['callback']) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except AttributeError: self.logger.warn('Unable to find callback method') # depends on [control=['except'], data=[]] try: if 'errback' in item and item['errback'] is not None: req.errback = getattr(self.spider, item['errback']) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except AttributeError: self.logger.warn('Unable to find errback method') # depends on [control=['except'], data=[]] if 'meta' in item: item = item['meta'] # depends on [control=['if'], data=['item']] # defaults not in schema if 'curdepth' not in item: item['curdepth'] = 0 # depends on [control=['if'], data=['item']] if 'retry_times' not in item: item['retry_times'] = 0 # depends on [control=['if'], data=['item']] for key in list(item.keys()): req.meta[key] = item[key] # depends on [control=['for'], data=['key']] # extra check to add items to request if 'useragent' in item and item['useragent'] is not None: req.headers['User-Agent'] = item['useragent'] # depends on [control=['if'], data=[]] if 'cookie' in item and item['cookie'] is not None: if isinstance(item['cookie'], dict): req.cookies = item['cookie'] # depends on [control=['if'], data=[]] elif isinstance(item['cookie'], basestring): req.cookies = self.parse_cookie(item['cookie']) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return req # depends on [control=['if'], data=[]] return None
def shutdown(self, cancel=False, cancel_msg=''): """Shutdown the TransferManager It will wait till all transfers complete before it completely shuts down. :type cancel: boolean :param cancel: If True, calls TransferFuture.cancel() for all in-progress in transfers. This is useful if you want the shutdown to happen quicker. :type cancel_msg: str :param cancel_msg: The message to specify if canceling all in-progress transfers. """ self._shutdown(cancel, cancel, cancel_msg)
def function[shutdown, parameter[self, cancel, cancel_msg]]: constant[Shutdown the TransferManager It will wait till all transfers complete before it completely shuts down. :type cancel: boolean :param cancel: If True, calls TransferFuture.cancel() for all in-progress in transfers. This is useful if you want the shutdown to happen quicker. :type cancel_msg: str :param cancel_msg: The message to specify if canceling all in-progress transfers. ] call[name[self]._shutdown, parameter[name[cancel], name[cancel], name[cancel_msg]]]
keyword[def] identifier[shutdown] ( identifier[self] , identifier[cancel] = keyword[False] , identifier[cancel_msg] = literal[string] ): literal[string] identifier[self] . identifier[_shutdown] ( identifier[cancel] , identifier[cancel] , identifier[cancel_msg] )
def shutdown(self, cancel=False, cancel_msg=''): """Shutdown the TransferManager It will wait till all transfers complete before it completely shuts down. :type cancel: boolean :param cancel: If True, calls TransferFuture.cancel() for all in-progress in transfers. This is useful if you want the shutdown to happen quicker. :type cancel_msg: str :param cancel_msg: The message to specify if canceling all in-progress transfers. """ self._shutdown(cancel, cancel, cancel_msg)
def validate_model_specification_file(file_path: str) -> str: """Ensures the provided file is a yaml file""" if not os.path.isfile(file_path): raise ConfigurationError('If you provide a model specification file, it must be a file. ' f'You provided {file_path}') extension = file_path.split('.')[-1] if extension not in ['yaml', 'yml']: raise ConfigurationError(f'Model specification files must be in a yaml format. You provided {extension}') # Attempt to load yaml.full_load(file_path) return file_path
def function[validate_model_specification_file, parameter[file_path]]: constant[Ensures the provided file is a yaml file] if <ast.UnaryOp object at 0x7da20c6abbb0> begin[:] <ast.Raise object at 0x7da20c6a8af0> variable[extension] assign[=] call[call[name[file_path].split, parameter[constant[.]]]][<ast.UnaryOp object at 0x7da20c6a9de0>] if compare[name[extension] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object at 0x7da20c6abb20>, <ast.Constant object at 0x7da20c6aa8f0>]]] begin[:] <ast.Raise object at 0x7da20c6aa920> call[name[yaml].full_load, parameter[name[file_path]]] return[name[file_path]]
keyword[def] identifier[validate_model_specification_file] ( identifier[file_path] : identifier[str] )-> identifier[str] : literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[file_path] ): keyword[raise] identifier[ConfigurationError] ( literal[string] literal[string] ) identifier[extension] = identifier[file_path] . identifier[split] ( literal[string] )[- literal[int] ] keyword[if] identifier[extension] keyword[not] keyword[in] [ literal[string] , literal[string] ]: keyword[raise] identifier[ConfigurationError] ( literal[string] ) identifier[yaml] . identifier[full_load] ( identifier[file_path] ) keyword[return] identifier[file_path]
def validate_model_specification_file(file_path: str) -> str: """Ensures the provided file is a yaml file""" if not os.path.isfile(file_path): raise ConfigurationError(f'If you provide a model specification file, it must be a file. You provided {file_path}') # depends on [control=['if'], data=[]] extension = file_path.split('.')[-1] if extension not in ['yaml', 'yml']: raise ConfigurationError(f'Model specification files must be in a yaml format. You provided {extension}') # depends on [control=['if'], data=['extension']] # Attempt to load yaml.full_load(file_path) return file_path
def write_to_file(self, filename, do_compress=None): """ Writes the las data into a file Parameters ---------- filename : str The file where the data should be written. do_compress: bool, optional, default None if None the extension of the filename will be used to determine if the data should be compressed otherwise the do_compress flag indicate if the data should be compressed """ is_ext_laz = filename.split(".")[-1] == "laz" if is_ext_laz and do_compress is None: do_compress = True with open(filename, mode="wb") as out: self.write_to(out, do_compress=do_compress)
def function[write_to_file, parameter[self, filename, do_compress]]: constant[ Writes the las data into a file Parameters ---------- filename : str The file where the data should be written. do_compress: bool, optional, default None if None the extension of the filename will be used to determine if the data should be compressed otherwise the do_compress flag indicate if the data should be compressed ] variable[is_ext_laz] assign[=] compare[call[call[name[filename].split, parameter[constant[.]]]][<ast.UnaryOp object at 0x7da1b025cee0>] equal[==] constant[laz]] if <ast.BoolOp object at 0x7da1b025cd30> begin[:] variable[do_compress] assign[=] constant[True] with call[name[open], parameter[name[filename]]] begin[:] call[name[self].write_to, parameter[name[out]]]
keyword[def] identifier[write_to_file] ( identifier[self] , identifier[filename] , identifier[do_compress] = keyword[None] ): literal[string] identifier[is_ext_laz] = identifier[filename] . identifier[split] ( literal[string] )[- literal[int] ]== literal[string] keyword[if] identifier[is_ext_laz] keyword[and] identifier[do_compress] keyword[is] keyword[None] : identifier[do_compress] = keyword[True] keyword[with] identifier[open] ( identifier[filename] , identifier[mode] = literal[string] ) keyword[as] identifier[out] : identifier[self] . identifier[write_to] ( identifier[out] , identifier[do_compress] = identifier[do_compress] )
def write_to_file(self, filename, do_compress=None): """ Writes the las data into a file Parameters ---------- filename : str The file where the data should be written. do_compress: bool, optional, default None if None the extension of the filename will be used to determine if the data should be compressed otherwise the do_compress flag indicate if the data should be compressed """ is_ext_laz = filename.split('.')[-1] == 'laz' if is_ext_laz and do_compress is None: do_compress = True # depends on [control=['if'], data=[]] with open(filename, mode='wb') as out: self.write_to(out, do_compress=do_compress) # depends on [control=['with'], data=['out']]
def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
def function[category, parameter[]]: constant[Get a category.] if compare[constant[series] in name[kwargs]] begin[:] call[name[kwargs].pop, parameter[constant[series]]] variable[path] assign[=] constant[series] return[call[call[name[Fred], parameter[]].category, parameter[name[path]]]]
keyword[def] identifier[category] (** identifier[kwargs] ): literal[string] keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[path] = literal[string] keyword[else] : identifier[path] = keyword[None] keyword[return] identifier[Fred] (). identifier[category] ( identifier[path] ,** identifier[kwargs] )
def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' # depends on [control=['if'], data=['kwargs']] else: path = None return Fred().category(path, **kwargs)
def get_protein_feather_paths(protgroup, memornot, protgroup_dict, protein_feathers_dir, core_only_genes=None): """ protgroup example: ('subsystem', 'cog_primary', 'H') memornot example: ('vizrecon', 'membrane') protgroup_dict example: {'databases': {'redoxdb': {'experimental_sensitive_cys': ['b2518','b3352','b2195','b4016'], ...}}} """ prots_memornot = protgroup_dict['localization'][memornot[0]][memornot[1]] if protgroup[0] == 'localization': if protgroup[2] != 'all': if memornot[1] in ['membrane', 'inner_membrane', 'outer_membrane'] and protgroup[2] not in ['membrane', 'inner_membrane', 'outer_membrane']: return [] if memornot[1] not in ['membrane', 'inner_membrane', 'outer_membrane'] and protgroup[2] in ['membrane', 'inner_membrane', 'outer_membrane']: return [] prots_group = protgroup_dict[protgroup[0]][protgroup[1]][protgroup[2]] prots_filtered = list(set(prots_group).intersection(prots_memornot)) if core_only_genes: prots_filtered = list(set(prots_filtered).intersection(core_only_genes)) return [op.join(protein_feathers_dir, '{}_protein_strain_properties.fthr'.format(x)) for x in prots_filtered if op.exists(op.join(protein_feathers_dir, '{}_protein_strain_properties.fthr'.format(x)))]
def function[get_protein_feather_paths, parameter[protgroup, memornot, protgroup_dict, protein_feathers_dir, core_only_genes]]: constant[ protgroup example: ('subsystem', 'cog_primary', 'H') memornot example: ('vizrecon', 'membrane') protgroup_dict example: {'databases': {'redoxdb': {'experimental_sensitive_cys': ['b2518','b3352','b2195','b4016'], ...}}} ] variable[prots_memornot] assign[=] call[call[call[name[protgroup_dict]][constant[localization]]][call[name[memornot]][constant[0]]]][call[name[memornot]][constant[1]]] if compare[call[name[protgroup]][constant[0]] equal[==] constant[localization]] begin[:] if compare[call[name[protgroup]][constant[2]] not_equal[!=] constant[all]] begin[:] if <ast.BoolOp object at 0x7da20c76da50> begin[:] return[list[[]]] if <ast.BoolOp object at 0x7da20c76c880> begin[:] return[list[[]]] variable[prots_group] assign[=] call[call[call[name[protgroup_dict]][call[name[protgroup]][constant[0]]]][call[name[protgroup]][constant[1]]]][call[name[protgroup]][constant[2]]] variable[prots_filtered] assign[=] call[name[list], parameter[call[call[name[set], parameter[name[prots_group]]].intersection, parameter[name[prots_memornot]]]]] if name[core_only_genes] begin[:] variable[prots_filtered] assign[=] call[name[list], parameter[call[call[name[set], parameter[name[prots_filtered]]].intersection, parameter[name[core_only_genes]]]]] return[<ast.ListComp object at 0x7da18c4ccf70>]
keyword[def] identifier[get_protein_feather_paths] ( identifier[protgroup] , identifier[memornot] , identifier[protgroup_dict] , identifier[protein_feathers_dir] , identifier[core_only_genes] = keyword[None] ): literal[string] identifier[prots_memornot] = identifier[protgroup_dict] [ literal[string] ][ identifier[memornot] [ literal[int] ]][ identifier[memornot] [ literal[int] ]] keyword[if] identifier[protgroup] [ literal[int] ]== literal[string] : keyword[if] identifier[protgroup] [ literal[int] ]!= literal[string] : keyword[if] identifier[memornot] [ literal[int] ] keyword[in] [ literal[string] , literal[string] , literal[string] ] keyword[and] identifier[protgroup] [ literal[int] ] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] ]: keyword[return] [] keyword[if] identifier[memornot] [ literal[int] ] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] ] keyword[and] identifier[protgroup] [ literal[int] ] keyword[in] [ literal[string] , literal[string] , literal[string] ]: keyword[return] [] identifier[prots_group] = identifier[protgroup_dict] [ identifier[protgroup] [ literal[int] ]][ identifier[protgroup] [ literal[int] ]][ identifier[protgroup] [ literal[int] ]] identifier[prots_filtered] = identifier[list] ( identifier[set] ( identifier[prots_group] ). identifier[intersection] ( identifier[prots_memornot] )) keyword[if] identifier[core_only_genes] : identifier[prots_filtered] = identifier[list] ( identifier[set] ( identifier[prots_filtered] ). identifier[intersection] ( identifier[core_only_genes] )) keyword[return] [ identifier[op] . identifier[join] ( identifier[protein_feathers_dir] , literal[string] . identifier[format] ( identifier[x] )) keyword[for] identifier[x] keyword[in] identifier[prots_filtered] keyword[if] identifier[op] . identifier[exists] ( identifier[op] . identifier[join] ( identifier[protein_feathers_dir] , literal[string] . identifier[format] ( identifier[x] )))]
def get_protein_feather_paths(protgroup, memornot, protgroup_dict, protein_feathers_dir, core_only_genes=None): """ protgroup example: ('subsystem', 'cog_primary', 'H') memornot example: ('vizrecon', 'membrane') protgroup_dict example: {'databases': {'redoxdb': {'experimental_sensitive_cys': ['b2518','b3352','b2195','b4016'], ...}}} """ prots_memornot = protgroup_dict['localization'][memornot[0]][memornot[1]] if protgroup[0] == 'localization': if protgroup[2] != 'all': if memornot[1] in ['membrane', 'inner_membrane', 'outer_membrane'] and protgroup[2] not in ['membrane', 'inner_membrane', 'outer_membrane']: return [] # depends on [control=['if'], data=[]] if memornot[1] not in ['membrane', 'inner_membrane', 'outer_membrane'] and protgroup[2] in ['membrane', 'inner_membrane', 'outer_membrane']: return [] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] prots_group = protgroup_dict[protgroup[0]][protgroup[1]][protgroup[2]] prots_filtered = list(set(prots_group).intersection(prots_memornot)) if core_only_genes: prots_filtered = list(set(prots_filtered).intersection(core_only_genes)) # depends on [control=['if'], data=[]] return [op.join(protein_feathers_dir, '{}_protein_strain_properties.fthr'.format(x)) for x in prots_filtered if op.exists(op.join(protein_feathers_dir, '{}_protein_strain_properties.fthr'.format(x)))]
def p_expr_BOR_expr(p): """ expr : expr BOR expr """ p[0] = make_binary(p.lineno(2), 'BOR', p[1], p[3], lambda x, y: x | y)
def function[p_expr_BOR_expr, parameter[p]]: constant[ expr : expr BOR expr ] call[name[p]][constant[0]] assign[=] call[name[make_binary], parameter[call[name[p].lineno, parameter[constant[2]]], constant[BOR], call[name[p]][constant[1]], call[name[p]][constant[3]], <ast.Lambda object at 0x7da204960610>]]
keyword[def] identifier[p_expr_BOR_expr] ( identifier[p] ): literal[string] identifier[p] [ literal[int] ]= identifier[make_binary] ( identifier[p] . identifier[lineno] ( literal[int] ), literal[string] , identifier[p] [ literal[int] ], identifier[p] [ literal[int] ], keyword[lambda] identifier[x] , identifier[y] : identifier[x] | identifier[y] )
def p_expr_BOR_expr(p): """ expr : expr BOR expr """ p[0] = make_binary(p.lineno(2), 'BOR', p[1], p[3], lambda x, y: x | y)
def symlink_list(self, load): ''' Return a dict of all symlinks based on a given path in the repo ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if not salt.utils.stringutils.is_hex(load['saltenv']) \ and load['saltenv'] not in self.envs(): return {} if 'prefix' in load: prefix = load['prefix'].strip('/') else: prefix = '' symlinks = self._file_lists(load, 'symlinks') return dict([(key, val) for key, val in six.iteritems(symlinks) if key.startswith(prefix)])
def function[symlink_list, parameter[self, load]]: constant[ Return a dict of all symlinks based on a given path in the repo ] if compare[constant[env] in name[load]] begin[:] call[name[load].pop, parameter[constant[env]]] if <ast.BoolOp object at 0x7da1b1f74a00> begin[:] return[dictionary[[], []]] if compare[constant[prefix] in name[load]] begin[:] variable[prefix] assign[=] call[call[name[load]][constant[prefix]].strip, parameter[constant[/]]] variable[symlinks] assign[=] call[name[self]._file_lists, parameter[name[load], constant[symlinks]]] return[call[name[dict], parameter[<ast.ListComp object at 0x7da1b1f74670>]]]
keyword[def] identifier[symlink_list] ( identifier[self] , identifier[load] ): literal[string] keyword[if] literal[string] keyword[in] identifier[load] : identifier[load] . identifier[pop] ( literal[string] ) keyword[if] keyword[not] identifier[salt] . identifier[utils] . identifier[stringutils] . identifier[is_hex] ( identifier[load] [ literal[string] ]) keyword[and] identifier[load] [ literal[string] ] keyword[not] keyword[in] identifier[self] . identifier[envs] (): keyword[return] {} keyword[if] literal[string] keyword[in] identifier[load] : identifier[prefix] = identifier[load] [ literal[string] ]. identifier[strip] ( literal[string] ) keyword[else] : identifier[prefix] = literal[string] identifier[symlinks] = identifier[self] . identifier[_file_lists] ( identifier[load] , literal[string] ) keyword[return] identifier[dict] ([( identifier[key] , identifier[val] ) keyword[for] identifier[key] , identifier[val] keyword[in] identifier[six] . identifier[iteritems] ( identifier[symlinks] ) keyword[if] identifier[key] . identifier[startswith] ( identifier[prefix] )])
def symlink_list(self, load): """ Return a dict of all symlinks based on a given path in the repo """ if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') # depends on [control=['if'], data=['load']] if not salt.utils.stringutils.is_hex(load['saltenv']) and load['saltenv'] not in self.envs(): return {} # depends on [control=['if'], data=[]] if 'prefix' in load: prefix = load['prefix'].strip('/') # depends on [control=['if'], data=['load']] else: prefix = '' symlinks = self._file_lists(load, 'symlinks') return dict([(key, val) for (key, val) in six.iteritems(symlinks) if key.startswith(prefix)])
def get_files_changed(repository, review_id): """ Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory. """ repository.git.fetch([next(iter(repository.remotes)), review_id]) files_changed = repository.git.diff_tree(["--no-commit-id", "--name-only", "-r", "FETCH_HEAD"]).splitlines() print("Found {} files changed".format(len(files_changed))) return files_changed
def function[get_files_changed, parameter[repository, review_id]]: constant[ Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory. ] call[name[repository].git.fetch, parameter[list[[<ast.Call object at 0x7da1b24fc3a0>, <ast.Name object at 0x7da1b24fc5b0>]]]] variable[files_changed] assign[=] call[call[name[repository].git.diff_tree, parameter[list[[<ast.Constant object at 0x7da1b24fc4f0>, <ast.Constant object at 0x7da1b24fdc00>, <ast.Constant object at 0x7da1b24fc460>, <ast.Constant object at 0x7da1b24febf0>]]]].splitlines, parameter[]] call[name[print], parameter[call[constant[Found {} files changed].format, parameter[call[name[len], parameter[name[files_changed]]]]]]] return[name[files_changed]]
keyword[def] identifier[get_files_changed] ( identifier[repository] , identifier[review_id] ): literal[string] identifier[repository] . identifier[git] . identifier[fetch] ([ identifier[next] ( identifier[iter] ( identifier[repository] . identifier[remotes] )), identifier[review_id] ]) identifier[files_changed] = identifier[repository] . identifier[git] . identifier[diff_tree] ([ literal[string] , literal[string] , literal[string] , literal[string] ]). identifier[splitlines] () identifier[print] ( literal[string] . identifier[format] ( identifier[len] ( identifier[files_changed] ))) keyword[return] identifier[files_changed]
def get_files_changed(repository, review_id): """ Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory. """ repository.git.fetch([next(iter(repository.remotes)), review_id]) files_changed = repository.git.diff_tree(['--no-commit-id', '--name-only', '-r', 'FETCH_HEAD']).splitlines() print('Found {} files changed'.format(len(files_changed))) return files_changed
def _def_lookup(self, live_defs, variable): """ This is a backward lookup in the previous defs. :param addr_list: a list of normalized addresses. Note that, as we are using VSA, it is possible that @a is affected by several definitions. :returns: a dict {stmt:labels} where label is the number of individual addresses of addr_list (or the actual set of addresses depending on the keep_addrs flag) that are definted by stmt. """ prevdefs = { } if variable in live_defs: code_loc_set = live_defs[variable] for code_loc in code_loc_set: # Label edges with cardinality or actual sets of addresses if isinstance(variable, SimMemoryVariable): type_ = 'mem' elif isinstance(variable, SimRegisterVariable): type_ = 'reg' else: raise AngrDDGError('Unknown variable type %s' % type(variable)) if self.keep_data is True: data = variable prevdefs[code_loc] = { 'type': type_, 'data': data } else: if code_loc in prevdefs: count = prevdefs[code_loc]['count'] + 1 else: count = 0 prevdefs[code_loc] = { 'type': type_, 'count': count } return prevdefs
def function[_def_lookup, parameter[self, live_defs, variable]]: constant[ This is a backward lookup in the previous defs. :param addr_list: a list of normalized addresses. Note that, as we are using VSA, it is possible that @a is affected by several definitions. :returns: a dict {stmt:labels} where label is the number of individual addresses of addr_list (or the actual set of addresses depending on the keep_addrs flag) that are definted by stmt. ] variable[prevdefs] assign[=] dictionary[[], []] if compare[name[variable] in name[live_defs]] begin[:] variable[code_loc_set] assign[=] call[name[live_defs]][name[variable]] for taget[name[code_loc]] in starred[name[code_loc_set]] begin[:] if call[name[isinstance], parameter[name[variable], name[SimMemoryVariable]]] begin[:] variable[type_] assign[=] constant[mem] if compare[name[self].keep_data is constant[True]] begin[:] variable[data] assign[=] name[variable] call[name[prevdefs]][name[code_loc]] assign[=] dictionary[[<ast.Constant object at 0x7da20c6aa9b0>, <ast.Constant object at 0x7da20c6aada0>], [<ast.Name object at 0x7da20c6aaec0>, <ast.Name object at 0x7da1b21e3790>]] return[name[prevdefs]]
keyword[def] identifier[_def_lookup] ( identifier[self] , identifier[live_defs] , identifier[variable] ): literal[string] identifier[prevdefs] ={} keyword[if] identifier[variable] keyword[in] identifier[live_defs] : identifier[code_loc_set] = identifier[live_defs] [ identifier[variable] ] keyword[for] identifier[code_loc] keyword[in] identifier[code_loc_set] : keyword[if] identifier[isinstance] ( identifier[variable] , identifier[SimMemoryVariable] ): identifier[type_] = literal[string] keyword[elif] identifier[isinstance] ( identifier[variable] , identifier[SimRegisterVariable] ): identifier[type_] = literal[string] keyword[else] : keyword[raise] identifier[AngrDDGError] ( literal[string] % identifier[type] ( identifier[variable] )) keyword[if] identifier[self] . identifier[keep_data] keyword[is] keyword[True] : identifier[data] = identifier[variable] identifier[prevdefs] [ identifier[code_loc] ]={ literal[string] : identifier[type_] , literal[string] : identifier[data] } keyword[else] : keyword[if] identifier[code_loc] keyword[in] identifier[prevdefs] : identifier[count] = identifier[prevdefs] [ identifier[code_loc] ][ literal[string] ]+ literal[int] keyword[else] : identifier[count] = literal[int] identifier[prevdefs] [ identifier[code_loc] ]={ literal[string] : identifier[type_] , literal[string] : identifier[count] } keyword[return] identifier[prevdefs]
def _def_lookup(self, live_defs, variable): """ This is a backward lookup in the previous defs. :param addr_list: a list of normalized addresses. Note that, as we are using VSA, it is possible that @a is affected by several definitions. :returns: a dict {stmt:labels} where label is the number of individual addresses of addr_list (or the actual set of addresses depending on the keep_addrs flag) that are definted by stmt. """ prevdefs = {} if variable in live_defs: code_loc_set = live_defs[variable] for code_loc in code_loc_set: # Label edges with cardinality or actual sets of addresses if isinstance(variable, SimMemoryVariable): type_ = 'mem' # depends on [control=['if'], data=[]] elif isinstance(variable, SimRegisterVariable): type_ = 'reg' # depends on [control=['if'], data=[]] else: raise AngrDDGError('Unknown variable type %s' % type(variable)) if self.keep_data is True: data = variable prevdefs[code_loc] = {'type': type_, 'data': data} # depends on [control=['if'], data=[]] else: if code_loc in prevdefs: count = prevdefs[code_loc]['count'] + 1 # depends on [control=['if'], data=['code_loc', 'prevdefs']] else: count = 0 prevdefs[code_loc] = {'type': type_, 'count': count} # depends on [control=['for'], data=['code_loc']] # depends on [control=['if'], data=['variable', 'live_defs']] return prevdefs
def index_open(index, allow_no_indices=True, expand_wildcards='closed', ignore_unavailable=True, hosts=None, profile=None): ''' .. versionadded:: 2017.7.0 Open specified index. index Index to be opened allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes _all string or when no indices have been specified) expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both., default ‘closed’, valid choices are: ‘open’, ‘closed’, ‘none’, ‘all’ ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) CLI example:: salt myminion elasticsearch.index_open testindex ''' es = _get_instance(hosts, profile) try: result = es.indices.open(index=index, allow_no_indices=allow_no_indices, expand_wildcards=expand_wildcards, ignore_unavailable=ignore_unavailable) return result.get('acknowledged', False) except elasticsearch.TransportError as e: raise CommandExecutionError("Cannot open index {0}, server returned code {1} with message {2}".format(index, e.status_code, e.error))
def function[index_open, parameter[index, allow_no_indices, expand_wildcards, ignore_unavailable, hosts, profile]]: constant[ .. versionadded:: 2017.7.0 Open specified index. index Index to be opened allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes _all string or when no indices have been specified) expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both., default ‘closed’, valid choices are: ‘open’, ‘closed’, ‘none’, ‘all’ ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) CLI example:: salt myminion elasticsearch.index_open testindex ] variable[es] assign[=] call[name[_get_instance], parameter[name[hosts], name[profile]]] <ast.Try object at 0x7da18f811a50>
keyword[def] identifier[index_open] ( identifier[index] , identifier[allow_no_indices] = keyword[True] , identifier[expand_wildcards] = literal[string] , identifier[ignore_unavailable] = keyword[True] , identifier[hosts] = keyword[None] , identifier[profile] = keyword[None] ): literal[string] identifier[es] = identifier[_get_instance] ( identifier[hosts] , identifier[profile] ) keyword[try] : identifier[result] = identifier[es] . identifier[indices] . identifier[open] ( identifier[index] = identifier[index] , identifier[allow_no_indices] = identifier[allow_no_indices] , identifier[expand_wildcards] = identifier[expand_wildcards] , identifier[ignore_unavailable] = identifier[ignore_unavailable] ) keyword[return] identifier[result] . identifier[get] ( literal[string] , keyword[False] ) keyword[except] identifier[elasticsearch] . identifier[TransportError] keyword[as] identifier[e] : keyword[raise] identifier[CommandExecutionError] ( literal[string] . identifier[format] ( identifier[index] , identifier[e] . identifier[status_code] , identifier[e] . identifier[error] ))
def index_open(index, allow_no_indices=True, expand_wildcards='closed', ignore_unavailable=True, hosts=None, profile=None): """ .. versionadded:: 2017.7.0 Open specified index. index Index to be opened allow_no_indices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes _all string or when no indices have been specified) expand_wildcards Whether to expand wildcard expression to concrete indices that are open, closed or both., default ‘closed’, valid choices are: ‘open’, ‘closed’, ‘none’, ‘all’ ignore_unavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) CLI example:: salt myminion elasticsearch.index_open testindex """ es = _get_instance(hosts, profile) try: result = es.indices.open(index=index, allow_no_indices=allow_no_indices, expand_wildcards=expand_wildcards, ignore_unavailable=ignore_unavailable) return result.get('acknowledged', False) # depends on [control=['try'], data=[]] except elasticsearch.TransportError as e: raise CommandExecutionError('Cannot open index {0}, server returned code {1} with message {2}'.format(index, e.status_code, e.error)) # depends on [control=['except'], data=['e']]
def trace2array(self, sl): """Return an array with the trace of all stochastics, sliced by sl.""" chain = [] for stochastic in self.stochastics: tr = stochastic.trace.gettrace(slicing=sl) if tr is None: raise AttributeError chain.append(tr) return np.hstack(chain)
def function[trace2array, parameter[self, sl]]: constant[Return an array with the trace of all stochastics, sliced by sl.] variable[chain] assign[=] list[[]] for taget[name[stochastic]] in starred[name[self].stochastics] begin[:] variable[tr] assign[=] call[name[stochastic].trace.gettrace, parameter[]] if compare[name[tr] is constant[None]] begin[:] <ast.Raise object at 0x7da20c7c8a30> call[name[chain].append, parameter[name[tr]]] return[call[name[np].hstack, parameter[name[chain]]]]
keyword[def] identifier[trace2array] ( identifier[self] , identifier[sl] ): literal[string] identifier[chain] =[] keyword[for] identifier[stochastic] keyword[in] identifier[self] . identifier[stochastics] : identifier[tr] = identifier[stochastic] . identifier[trace] . identifier[gettrace] ( identifier[slicing] = identifier[sl] ) keyword[if] identifier[tr] keyword[is] keyword[None] : keyword[raise] identifier[AttributeError] identifier[chain] . identifier[append] ( identifier[tr] ) keyword[return] identifier[np] . identifier[hstack] ( identifier[chain] )
def trace2array(self, sl): """Return an array with the trace of all stochastics, sliced by sl.""" chain = [] for stochastic in self.stochastics: tr = stochastic.trace.gettrace(slicing=sl) if tr is None: raise AttributeError # depends on [control=['if'], data=[]] chain.append(tr) # depends on [control=['for'], data=['stochastic']] return np.hstack(chain)
def reverse_mapping(mapping): """ For every key, value pair, return the mapping for the equivalent value, key pair >>> reverse_mapping({'a': 'b'}) == {'b': 'a'} True """ keys, values = zip(*mapping.items()) return dict(zip(values, keys))
def function[reverse_mapping, parameter[mapping]]: constant[ For every key, value pair, return the mapping for the equivalent value, key pair >>> reverse_mapping({'a': 'b'}) == {'b': 'a'} True ] <ast.Tuple object at 0x7da1b0214eb0> assign[=] call[name[zip], parameter[<ast.Starred object at 0x7da1b0216d10>]] return[call[name[dict], parameter[call[name[zip], parameter[name[values], name[keys]]]]]]
keyword[def] identifier[reverse_mapping] ( identifier[mapping] ): literal[string] identifier[keys] , identifier[values] = identifier[zip] (* identifier[mapping] . identifier[items] ()) keyword[return] identifier[dict] ( identifier[zip] ( identifier[values] , identifier[keys] ))
def reverse_mapping(mapping): """ For every key, value pair, return the mapping for the equivalent value, key pair >>> reverse_mapping({'a': 'b'}) == {'b': 'a'} True """ (keys, values) = zip(*mapping.items()) return dict(zip(values, keys))
def click_and_hold(self, on_element=None): """ Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) if self._driver.w3c: self.w3c_actions.pointer_action.click_and_hold() self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute( Command.MOUSE_DOWN, {})) return self
def function[click_and_hold, parameter[self, on_element]]: constant[ Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position. ] if name[on_element] begin[:] call[name[self].move_to_element, parameter[name[on_element]]] if name[self]._driver.w3c begin[:] call[name[self].w3c_actions.pointer_action.click_and_hold, parameter[]] call[name[self].w3c_actions.key_action.pause, parameter[]] return[name[self]]
keyword[def] identifier[click_and_hold] ( identifier[self] , identifier[on_element] = keyword[None] ): literal[string] keyword[if] identifier[on_element] : identifier[self] . identifier[move_to_element] ( identifier[on_element] ) keyword[if] identifier[self] . identifier[_driver] . identifier[w3c] : identifier[self] . identifier[w3c_actions] . identifier[pointer_action] . identifier[click_and_hold] () identifier[self] . identifier[w3c_actions] . identifier[key_action] . identifier[pause] () keyword[else] : identifier[self] . identifier[_actions] . identifier[append] ( keyword[lambda] : identifier[self] . identifier[_driver] . identifier[execute] ( identifier[Command] . identifier[MOUSE_DOWN] ,{})) keyword[return] identifier[self]
def click_and_hold(self, on_element=None): """ Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) # depends on [control=['if'], data=[]] if self._driver.w3c: self.w3c_actions.pointer_action.click_and_hold() self.w3c_actions.key_action.pause() # depends on [control=['if'], data=[]] else: self._actions.append(lambda : self._driver.execute(Command.MOUSE_DOWN, {})) return self
def groupByNodes(requestContext, seriesList, callback, *nodes): """ Takes a serieslist and maps a callback to subgroups within as defined by multiple nodes. Example:: &target=groupByNodes(ganglia.server*.*.cpu.load*,"sumSeries",1,4) Would return multiple series which are each the result of applying the "sumSeries" function to groups joined on the nodes' list (0 indexed) resulting in a list of targets like:: sumSeries(ganglia.server1.*.cpu.load5), sumSeries(ganglia.server1.*.cpu.load10), sumSeries(ganglia.server1.*.cpu.load15), sumSeries(ganglia.server2.*.cpu.load5), sumSeries(ganglia.server2.*.cpu.load10), sumSeries(ganglia.server2.*.cpu.load15), ... """ from .app import app metaSeries = {} keys = [] if isinstance(nodes, int): nodes = [nodes] for series in seriesList: key = '.'.join(series.name.split(".")[n] for n in nodes) if key not in metaSeries: metaSeries[key] = [series] keys.append(key) else: metaSeries[key].append(series) for key in metaSeries: metaSeries[key] = app.functions[callback](requestContext, metaSeries[key])[0] metaSeries[key].name = key return [metaSeries[key] for key in keys]
def function[groupByNodes, parameter[requestContext, seriesList, callback]]: constant[ Takes a serieslist and maps a callback to subgroups within as defined by multiple nodes. Example:: &target=groupByNodes(ganglia.server*.*.cpu.load*,"sumSeries",1,4) Would return multiple series which are each the result of applying the "sumSeries" function to groups joined on the nodes' list (0 indexed) resulting in a list of targets like:: sumSeries(ganglia.server1.*.cpu.load5), sumSeries(ganglia.server1.*.cpu.load10), sumSeries(ganglia.server1.*.cpu.load15), sumSeries(ganglia.server2.*.cpu.load5), sumSeries(ganglia.server2.*.cpu.load10), sumSeries(ganglia.server2.*.cpu.load15), ... ] from relative_module[app] import module[app] variable[metaSeries] assign[=] dictionary[[], []] variable[keys] assign[=] list[[]] if call[name[isinstance], parameter[name[nodes], name[int]]] begin[:] variable[nodes] assign[=] list[[<ast.Name object at 0x7da18c4cd720>]] for taget[name[series]] in starred[name[seriesList]] begin[:] variable[key] assign[=] call[constant[.].join, parameter[<ast.GeneratorExp object at 0x7da18c4cd3f0>]] if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[metaSeries]] begin[:] call[name[metaSeries]][name[key]] assign[=] list[[<ast.Name object at 0x7da18c4cead0>]] call[name[keys].append, parameter[name[key]]] for taget[name[key]] in starred[name[metaSeries]] begin[:] call[name[metaSeries]][name[key]] assign[=] call[call[call[name[app].functions][name[callback]], parameter[name[requestContext], call[name[metaSeries]][name[key]]]]][constant[0]] call[name[metaSeries]][name[key]].name assign[=] name[key] return[<ast.ListComp object at 0x7da18c4cec80>]
keyword[def] identifier[groupByNodes] ( identifier[requestContext] , identifier[seriesList] , identifier[callback] ,* identifier[nodes] ): literal[string] keyword[from] . identifier[app] keyword[import] identifier[app] identifier[metaSeries] ={} identifier[keys] =[] keyword[if] identifier[isinstance] ( identifier[nodes] , identifier[int] ): identifier[nodes] =[ identifier[nodes] ] keyword[for] identifier[series] keyword[in] identifier[seriesList] : identifier[key] = literal[string] . identifier[join] ( identifier[series] . identifier[name] . identifier[split] ( literal[string] )[ identifier[n] ] keyword[for] identifier[n] keyword[in] identifier[nodes] ) keyword[if] identifier[key] keyword[not] keyword[in] identifier[metaSeries] : identifier[metaSeries] [ identifier[key] ]=[ identifier[series] ] identifier[keys] . identifier[append] ( identifier[key] ) keyword[else] : identifier[metaSeries] [ identifier[key] ]. identifier[append] ( identifier[series] ) keyword[for] identifier[key] keyword[in] identifier[metaSeries] : identifier[metaSeries] [ identifier[key] ]= identifier[app] . identifier[functions] [ identifier[callback] ]( identifier[requestContext] , identifier[metaSeries] [ identifier[key] ])[ literal[int] ] identifier[metaSeries] [ identifier[key] ]. identifier[name] = identifier[key] keyword[return] [ identifier[metaSeries] [ identifier[key] ] keyword[for] identifier[key] keyword[in] identifier[keys] ]
def groupByNodes(requestContext, seriesList, callback, *nodes): """ Takes a serieslist and maps a callback to subgroups within as defined by multiple nodes. Example:: &target=groupByNodes(ganglia.server*.*.cpu.load*,"sumSeries",1,4) Would return multiple series which are each the result of applying the "sumSeries" function to groups joined on the nodes' list (0 indexed) resulting in a list of targets like:: sumSeries(ganglia.server1.*.cpu.load5), sumSeries(ganglia.server1.*.cpu.load10), sumSeries(ganglia.server1.*.cpu.load15), sumSeries(ganglia.server2.*.cpu.load5), sumSeries(ganglia.server2.*.cpu.load10), sumSeries(ganglia.server2.*.cpu.load15), ... """ from .app import app metaSeries = {} keys = [] if isinstance(nodes, int): nodes = [nodes] # depends on [control=['if'], data=[]] for series in seriesList: key = '.'.join((series.name.split('.')[n] for n in nodes)) if key not in metaSeries: metaSeries[key] = [series] keys.append(key) # depends on [control=['if'], data=['key', 'metaSeries']] else: metaSeries[key].append(series) # depends on [control=['for'], data=['series']] for key in metaSeries: metaSeries[key] = app.functions[callback](requestContext, metaSeries[key])[0] metaSeries[key].name = key # depends on [control=['for'], data=['key']] return [metaSeries[key] for key in keys]
def add_response(self, req, resp): """Adds the response from sending to `req` to this instance's cache. Args: req (`ServicecontrolServicesCheckRequest`): the request resp (CheckResponse): the response from sending the request """ if self._cache is None: return signature = sign(req.checkRequest) with self._cache as c: now = self._timer() quota_scale = 0 # WIP item = c.get(signature) if item is None: c[signature] = CachedItem( resp, self.service_name, now, quota_scale) else: # Update the cached item to reflect that it is updated item.last_check_time = now item.response = resp item.quota_scale = quota_scale item.is_flushing = False c[signature] = item
def function[add_response, parameter[self, req, resp]]: constant[Adds the response from sending to `req` to this instance's cache. Args: req (`ServicecontrolServicesCheckRequest`): the request resp (CheckResponse): the response from sending the request ] if compare[name[self]._cache is constant[None]] begin[:] return[None] variable[signature] assign[=] call[name[sign], parameter[name[req].checkRequest]] with name[self]._cache begin[:] variable[now] assign[=] call[name[self]._timer, parameter[]] variable[quota_scale] assign[=] constant[0] variable[item] assign[=] call[name[c].get, parameter[name[signature]]] if compare[name[item] is constant[None]] begin[:] call[name[c]][name[signature]] assign[=] call[name[CachedItem], parameter[name[resp], name[self].service_name, name[now], name[quota_scale]]]
keyword[def] identifier[add_response] ( identifier[self] , identifier[req] , identifier[resp] ): literal[string] keyword[if] identifier[self] . identifier[_cache] keyword[is] keyword[None] : keyword[return] identifier[signature] = identifier[sign] ( identifier[req] . identifier[checkRequest] ) keyword[with] identifier[self] . identifier[_cache] keyword[as] identifier[c] : identifier[now] = identifier[self] . identifier[_timer] () identifier[quota_scale] = literal[int] identifier[item] = identifier[c] . identifier[get] ( identifier[signature] ) keyword[if] identifier[item] keyword[is] keyword[None] : identifier[c] [ identifier[signature] ]= identifier[CachedItem] ( identifier[resp] , identifier[self] . identifier[service_name] , identifier[now] , identifier[quota_scale] ) keyword[else] : identifier[item] . identifier[last_check_time] = identifier[now] identifier[item] . identifier[response] = identifier[resp] identifier[item] . identifier[quota_scale] = identifier[quota_scale] identifier[item] . identifier[is_flushing] = keyword[False] identifier[c] [ identifier[signature] ]= identifier[item]
def add_response(self, req, resp): """Adds the response from sending to `req` to this instance's cache. Args: req (`ServicecontrolServicesCheckRequest`): the request resp (CheckResponse): the response from sending the request """ if self._cache is None: return # depends on [control=['if'], data=[]] signature = sign(req.checkRequest) with self._cache as c: now = self._timer() quota_scale = 0 # WIP item = c.get(signature) if item is None: c[signature] = CachedItem(resp, self.service_name, now, quota_scale) # depends on [control=['if'], data=[]] else: # Update the cached item to reflect that it is updated item.last_check_time = now item.response = resp item.quota_scale = quota_scale item.is_flushing = False c[signature] = item # depends on [control=['with'], data=['c']]
def filter_genes(data, min_counts=None, min_cells=None, max_counts=None, max_cells=None, min_counts_u=None, min_cells_u=None, max_counts_u=None, max_cells_u=None, min_shared_counts=None, min_shared_cells=None, copy=False): """Filter genes based on number of cells or counts. Keep genes that have at least `min_counts` counts or are expressed in at least `min_cells` cells or have at most `max_counts` counts or are expressed in at most `max_cells` cells. Only provide one of the optional parameters `min_counts`, `min_cells`, `max_counts`, `max_cells` per call. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.spmatrix` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. min_counts : `int`, optional (default: `None`) Minimum number of counts required for a gene to pass filtering. min_cells : `int`, optional (default: `None`) Minimum number of cells expressed required for a gene to pass filtering. max_counts : `int`, optional (default: `None`) Maximum number of counts required for a gene to pass filtering. max_cells : `int`, optional (default: `None`) Maximum number of cells expressed required for a gene to pass filtering. min_counts_u : `int`, optional (default: `None`) Minimum number of unspliced counts required for a gene to pass filtering. min_cells_u : `int`, optional (default: `None`) Minimum number of unspliced cells expressed required for a gene to pass filtering. max_counts_u : `int`, optional (default: `None`) Maximum number of unspliced counts required for a gene to pass filtering. max_cells_u : `int`, optional (default: `None`) Maximum number of unspliced cells expressed required for a gene to pass filtering. min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. copy : `bool`, optional (default: `False`) Determines whether a copy is returned. Returns ------- Filters the object and adds `n_counts` to `adata.var`. """ adata = data.copy() if copy else data # set initial cell sizes before filtering set_initial_size(adata) layers = [layer for layer in ['spliced', 'unspliced'] if layer in adata.layers.keys()] if min_shared_counts is not None or min_shared_cells is not None: layers.extend(['shared']) for layer in layers: if layer is 'spliced': _min_counts, _min_cells, _max_counts, _max_cells = min_counts, min_cells, max_counts, max_cells elif layer is 'unspliced': _min_counts, _min_cells, _max_counts, _max_cells = min_counts_u, min_cells_u, max_counts_u, max_cells_u else: # shared counts/cells _min_counts, _min_cells, _max_counts, _max_cells = min_shared_counts, min_shared_cells, None, None if layer in adata.layers.keys(): X = adata.layers[layer] else: # shared counts/cells Xs, Xu = adata.layers['spliced'], adata.layers['unspliced'] nonzeros = (Xs > 0).multiply(Xu > 0) if issparse(Xs) else (Xs > 0) * (Xu > 0) X = nonzeros.multiply(Xs) + nonzeros.multiply(Xu) if issparse(nonzeros) else nonzeros * (Xs + Xu) gene_subset = np.ones(adata.n_vars, dtype=bool) if _min_counts is not None or _max_counts is not None: gene_subset, _ = filter(X, min_counts=_min_counts, max_counts=_max_counts) adata._inplace_subset_var(gene_subset) if _min_cells is not None or _max_cells is not None: gene_subset, _ = filter(X, min_cells=_min_cells, max_cells=_max_cells) adata._inplace_subset_var(gene_subset) s = np.sum(~gene_subset) if s > 0: logg.info('Filtered out {} genes that are detected'.format(s), end=' ') if _min_cells is not None or _min_counts is not None: logg.info('in less than', str(_min_cells) + ' cells (' + str(layer) + ').' if _min_counts is None else str(_min_counts) + ' counts (' + str(layer) + ').', no_indent=True) if max_cells is not None or max_counts is not None: logg.info('in more than ', str(_max_cells) + ' cells(' + str(layer) + ').' if _max_counts is None else str(_max_counts) + ' counts (' + str(layer) + ').', no_indent=True) return adata if copy else None
def function[filter_genes, parameter[data, min_counts, min_cells, max_counts, max_cells, min_counts_u, min_cells_u, max_counts_u, max_cells_u, min_shared_counts, min_shared_cells, copy]]: constant[Filter genes based on number of cells or counts. Keep genes that have at least `min_counts` counts or are expressed in at least `min_cells` cells or have at most `max_counts` counts or are expressed in at most `max_cells` cells. Only provide one of the optional parameters `min_counts`, `min_cells`, `max_counts`, `max_cells` per call. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.spmatrix` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. min_counts : `int`, optional (default: `None`) Minimum number of counts required for a gene to pass filtering. min_cells : `int`, optional (default: `None`) Minimum number of cells expressed required for a gene to pass filtering. max_counts : `int`, optional (default: `None`) Maximum number of counts required for a gene to pass filtering. max_cells : `int`, optional (default: `None`) Maximum number of cells expressed required for a gene to pass filtering. min_counts_u : `int`, optional (default: `None`) Minimum number of unspliced counts required for a gene to pass filtering. min_cells_u : `int`, optional (default: `None`) Minimum number of unspliced cells expressed required for a gene to pass filtering. max_counts_u : `int`, optional (default: `None`) Maximum number of unspliced counts required for a gene to pass filtering. max_cells_u : `int`, optional (default: `None`) Maximum number of unspliced cells expressed required for a gene to pass filtering. min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. copy : `bool`, optional (default: `False`) Determines whether a copy is returned. Returns ------- Filters the object and adds `n_counts` to `adata.var`. ] variable[adata] assign[=] <ast.IfExp object at 0x7da18c4cd4e0> call[name[set_initial_size], parameter[name[adata]]] variable[layers] assign[=] <ast.ListComp object at 0x7da18c4cc7c0> if <ast.BoolOp object at 0x7da18c4cf100> begin[:] call[name[layers].extend, parameter[list[[<ast.Constant object at 0x7da18c4ccca0>]]]] for taget[name[layer]] in starred[name[layers]] begin[:] if compare[name[layer] is constant[spliced]] begin[:] <ast.Tuple object at 0x7da18c4ce770> assign[=] tuple[[<ast.Name object at 0x7da18c4cd180>, <ast.Name object at 0x7da18c4cef80>, <ast.Name object at 0x7da18c4cd240>, <ast.Name object at 0x7da18c4cf2e0>]] if compare[name[layer] in call[name[adata].layers.keys, parameter[]]] begin[:] variable[X] assign[=] call[name[adata].layers][name[layer]] variable[gene_subset] assign[=] call[name[np].ones, parameter[name[adata].n_vars]] if <ast.BoolOp object at 0x7da18c4ceb90> begin[:] <ast.Tuple object at 0x7da18c4ccc10> assign[=] call[name[filter], parameter[name[X]]] call[name[adata]._inplace_subset_var, parameter[name[gene_subset]]] if <ast.BoolOp object at 0x7da18c4ce440> begin[:] <ast.Tuple object at 0x7da18c4cfc70> assign[=] call[name[filter], parameter[name[X]]] call[name[adata]._inplace_subset_var, parameter[name[gene_subset]]] variable[s] assign[=] call[name[np].sum, parameter[<ast.UnaryOp object at 0x7da18c4ccd60>]] if compare[name[s] greater[>] constant[0]] begin[:] call[name[logg].info, parameter[call[constant[Filtered out {} genes that are detected].format, parameter[name[s]]]]] if <ast.BoolOp object at 0x7da18c4cdfc0> begin[:] call[name[logg].info, parameter[constant[in less than], <ast.IfExp object at 0x7da18c4cdd50>]] if <ast.BoolOp object at 0x7da18dc04e20> begin[:] call[name[logg].info, parameter[constant[in more than ], <ast.IfExp object at 0x7da18dc06050>]] return[<ast.IfExp object at 0x7da18dc06b90>]
keyword[def] identifier[filter_genes] ( identifier[data] , identifier[min_counts] = keyword[None] , identifier[min_cells] = keyword[None] , identifier[max_counts] = keyword[None] , identifier[max_cells] = keyword[None] , identifier[min_counts_u] = keyword[None] , identifier[min_cells_u] = keyword[None] , identifier[max_counts_u] = keyword[None] , identifier[max_cells_u] = keyword[None] , identifier[min_shared_counts] = keyword[None] , identifier[min_shared_cells] = keyword[None] , identifier[copy] = keyword[False] ): literal[string] identifier[adata] = identifier[data] . identifier[copy] () keyword[if] identifier[copy] keyword[else] identifier[data] identifier[set_initial_size] ( identifier[adata] ) identifier[layers] =[ identifier[layer] keyword[for] identifier[layer] keyword[in] [ literal[string] , literal[string] ] keyword[if] identifier[layer] keyword[in] identifier[adata] . identifier[layers] . identifier[keys] ()] keyword[if] identifier[min_shared_counts] keyword[is] keyword[not] keyword[None] keyword[or] identifier[min_shared_cells] keyword[is] keyword[not] keyword[None] : identifier[layers] . identifier[extend] ([ literal[string] ]) keyword[for] identifier[layer] keyword[in] identifier[layers] : keyword[if] identifier[layer] keyword[is] literal[string] : identifier[_min_counts] , identifier[_min_cells] , identifier[_max_counts] , identifier[_max_cells] = identifier[min_counts] , identifier[min_cells] , identifier[max_counts] , identifier[max_cells] keyword[elif] identifier[layer] keyword[is] literal[string] : identifier[_min_counts] , identifier[_min_cells] , identifier[_max_counts] , identifier[_max_cells] = identifier[min_counts_u] , identifier[min_cells_u] , identifier[max_counts_u] , identifier[max_cells_u] keyword[else] : identifier[_min_counts] , identifier[_min_cells] , identifier[_max_counts] , identifier[_max_cells] = identifier[min_shared_counts] , identifier[min_shared_cells] , keyword[None] , keyword[None] keyword[if] identifier[layer] keyword[in] identifier[adata] . identifier[layers] . identifier[keys] (): identifier[X] = identifier[adata] . identifier[layers] [ identifier[layer] ] keyword[else] : identifier[Xs] , identifier[Xu] = identifier[adata] . identifier[layers] [ literal[string] ], identifier[adata] . identifier[layers] [ literal[string] ] identifier[nonzeros] =( identifier[Xs] > literal[int] ). identifier[multiply] ( identifier[Xu] > literal[int] ) keyword[if] identifier[issparse] ( identifier[Xs] ) keyword[else] ( identifier[Xs] > literal[int] )*( identifier[Xu] > literal[int] ) identifier[X] = identifier[nonzeros] . identifier[multiply] ( identifier[Xs] )+ identifier[nonzeros] . identifier[multiply] ( identifier[Xu] ) keyword[if] identifier[issparse] ( identifier[nonzeros] ) keyword[else] identifier[nonzeros] *( identifier[Xs] + identifier[Xu] ) identifier[gene_subset] = identifier[np] . identifier[ones] ( identifier[adata] . identifier[n_vars] , identifier[dtype] = identifier[bool] ) keyword[if] identifier[_min_counts] keyword[is] keyword[not] keyword[None] keyword[or] identifier[_max_counts] keyword[is] keyword[not] keyword[None] : identifier[gene_subset] , identifier[_] = identifier[filter] ( identifier[X] , identifier[min_counts] = identifier[_min_counts] , identifier[max_counts] = identifier[_max_counts] ) identifier[adata] . identifier[_inplace_subset_var] ( identifier[gene_subset] ) keyword[if] identifier[_min_cells] keyword[is] keyword[not] keyword[None] keyword[or] identifier[_max_cells] keyword[is] keyword[not] keyword[None] : identifier[gene_subset] , identifier[_] = identifier[filter] ( identifier[X] , identifier[min_cells] = identifier[_min_cells] , identifier[max_cells] = identifier[_max_cells] ) identifier[adata] . identifier[_inplace_subset_var] ( identifier[gene_subset] ) identifier[s] = identifier[np] . identifier[sum] (~ identifier[gene_subset] ) keyword[if] identifier[s] > literal[int] : identifier[logg] . identifier[info] ( literal[string] . identifier[format] ( identifier[s] ), identifier[end] = literal[string] ) keyword[if] identifier[_min_cells] keyword[is] keyword[not] keyword[None] keyword[or] identifier[_min_counts] keyword[is] keyword[not] keyword[None] : identifier[logg] . identifier[info] ( literal[string] , identifier[str] ( identifier[_min_cells] )+ literal[string] + identifier[str] ( identifier[layer] )+ literal[string] keyword[if] identifier[_min_counts] keyword[is] keyword[None] keyword[else] identifier[str] ( identifier[_min_counts] )+ literal[string] + identifier[str] ( identifier[layer] )+ literal[string] , identifier[no_indent] = keyword[True] ) keyword[if] identifier[max_cells] keyword[is] keyword[not] keyword[None] keyword[or] identifier[max_counts] keyword[is] keyword[not] keyword[None] : identifier[logg] . identifier[info] ( literal[string] , identifier[str] ( identifier[_max_cells] )+ literal[string] + identifier[str] ( identifier[layer] )+ literal[string] keyword[if] identifier[_max_counts] keyword[is] keyword[None] keyword[else] identifier[str] ( identifier[_max_counts] )+ literal[string] + identifier[str] ( identifier[layer] )+ literal[string] , identifier[no_indent] = keyword[True] ) keyword[return] identifier[adata] keyword[if] identifier[copy] keyword[else] keyword[None]
def filter_genes(data, min_counts=None, min_cells=None, max_counts=None, max_cells=None, min_counts_u=None, min_cells_u=None, max_counts_u=None, max_cells_u=None, min_shared_counts=None, min_shared_cells=None, copy=False): """Filter genes based on number of cells or counts. Keep genes that have at least `min_counts` counts or are expressed in at least `min_cells` cells or have at most `max_counts` counts or are expressed in at most `max_cells` cells. Only provide one of the optional parameters `min_counts`, `min_cells`, `max_counts`, `max_cells` per call. Parameters ---------- data : :class:`~anndata.AnnData`, `np.ndarray`, `sp.spmatrix` The (annotated) data matrix of shape `n_obs` × `n_vars`. Rows correspond to cells and columns to genes. min_counts : `int`, optional (default: `None`) Minimum number of counts required for a gene to pass filtering. min_cells : `int`, optional (default: `None`) Minimum number of cells expressed required for a gene to pass filtering. max_counts : `int`, optional (default: `None`) Maximum number of counts required for a gene to pass filtering. max_cells : `int`, optional (default: `None`) Maximum number of cells expressed required for a gene to pass filtering. min_counts_u : `int`, optional (default: `None`) Minimum number of unspliced counts required for a gene to pass filtering. min_cells_u : `int`, optional (default: `None`) Minimum number of unspliced cells expressed required for a gene to pass filtering. max_counts_u : `int`, optional (default: `None`) Maximum number of unspliced counts required for a gene to pass filtering. max_cells_u : `int`, optional (default: `None`) Maximum number of unspliced cells expressed required for a gene to pass filtering. min_shared_counts: `int`, optional (default: `None`) Minimum number of counts (in cells expressed simultaneously in unspliced and spliced) required for a gene. min_shared_cells: `int`, optional (default: `None`) Minimum number of cells required for a gene to be expressed simultaneously in unspliced and spliced. copy : `bool`, optional (default: `False`) Determines whether a copy is returned. Returns ------- Filters the object and adds `n_counts` to `adata.var`. """ adata = data.copy() if copy else data # set initial cell sizes before filtering set_initial_size(adata) layers = [layer for layer in ['spliced', 'unspliced'] if layer in adata.layers.keys()] if min_shared_counts is not None or min_shared_cells is not None: layers.extend(['shared']) # depends on [control=['if'], data=[]] for layer in layers: if layer is 'spliced': (_min_counts, _min_cells, _max_counts, _max_cells) = (min_counts, min_cells, max_counts, max_cells) # depends on [control=['if'], data=[]] elif layer is 'unspliced': (_min_counts, _min_cells, _max_counts, _max_cells) = (min_counts_u, min_cells_u, max_counts_u, max_cells_u) # depends on [control=['if'], data=[]] else: # shared counts/cells (_min_counts, _min_cells, _max_counts, _max_cells) = (min_shared_counts, min_shared_cells, None, None) if layer in adata.layers.keys(): X = adata.layers[layer] # depends on [control=['if'], data=['layer']] else: # shared counts/cells (Xs, Xu) = (adata.layers['spliced'], adata.layers['unspliced']) nonzeros = (Xs > 0).multiply(Xu > 0) if issparse(Xs) else (Xs > 0) * (Xu > 0) X = nonzeros.multiply(Xs) + nonzeros.multiply(Xu) if issparse(nonzeros) else nonzeros * (Xs + Xu) gene_subset = np.ones(adata.n_vars, dtype=bool) if _min_counts is not None or _max_counts is not None: (gene_subset, _) = filter(X, min_counts=_min_counts, max_counts=_max_counts) adata._inplace_subset_var(gene_subset) # depends on [control=['if'], data=[]] if _min_cells is not None or _max_cells is not None: (gene_subset, _) = filter(X, min_cells=_min_cells, max_cells=_max_cells) adata._inplace_subset_var(gene_subset) # depends on [control=['if'], data=[]] s = np.sum(~gene_subset) if s > 0: logg.info('Filtered out {} genes that are detected'.format(s), end=' ') if _min_cells is not None or _min_counts is not None: logg.info('in less than', str(_min_cells) + ' cells (' + str(layer) + ').' if _min_counts is None else str(_min_counts) + ' counts (' + str(layer) + ').', no_indent=True) # depends on [control=['if'], data=[]] if max_cells is not None or max_counts is not None: logg.info('in more than ', str(_max_cells) + ' cells(' + str(layer) + ').' if _max_counts is None else str(_max_counts) + ' counts (' + str(layer) + ').', no_indent=True) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['s']] # depends on [control=['for'], data=['layer']] return adata if copy else None
def get_allowed(allow, disallow): """ Normalize the given string attributes as a list of all allowed vClasses.""" if allow is None and disallow is None: return SUMO_VEHICLE_CLASSES elif disallow is None: return allow.split() else: disallow = disallow.split() return tuple([c for c in SUMO_VEHICLE_CLASSES if c not in disallow])
def function[get_allowed, parameter[allow, disallow]]: constant[ Normalize the given string attributes as a list of all allowed vClasses.] if <ast.BoolOp object at 0x7da1b0852860> begin[:] return[name[SUMO_VEHICLE_CLASSES]]
keyword[def] identifier[get_allowed] ( identifier[allow] , identifier[disallow] ): literal[string] keyword[if] identifier[allow] keyword[is] keyword[None] keyword[and] identifier[disallow] keyword[is] keyword[None] : keyword[return] identifier[SUMO_VEHICLE_CLASSES] keyword[elif] identifier[disallow] keyword[is] keyword[None] : keyword[return] identifier[allow] . identifier[split] () keyword[else] : identifier[disallow] = identifier[disallow] . identifier[split] () keyword[return] identifier[tuple] ([ identifier[c] keyword[for] identifier[c] keyword[in] identifier[SUMO_VEHICLE_CLASSES] keyword[if] identifier[c] keyword[not] keyword[in] identifier[disallow] ])
def get_allowed(allow, disallow): """ Normalize the given string attributes as a list of all allowed vClasses.""" if allow is None and disallow is None: return SUMO_VEHICLE_CLASSES # depends on [control=['if'], data=[]] elif disallow is None: return allow.split() # depends on [control=['if'], data=[]] else: disallow = disallow.split() return tuple([c for c in SUMO_VEHICLE_CLASSES if c not in disallow])
def updateGeometry(self): """Move widget to point under cursor """ WIDGET_BORDER_MARGIN = 5 SCROLLBAR_WIDTH = 30 # just a guess sizeHint = self.sizeHint() width = sizeHint.width() height = sizeHint.height() cursorRect = self._qpart.cursorRect() parentSize = self.parentWidget().size() spaceBelow = parentSize.height() - cursorRect.bottom() - WIDGET_BORDER_MARGIN spaceAbove = cursorRect.top() - WIDGET_BORDER_MARGIN if height <= spaceBelow or \ spaceBelow > spaceAbove: yPos = cursorRect.bottom() if height > spaceBelow and \ spaceBelow > self.minimumHeight(): height = spaceBelow width = width + SCROLLBAR_WIDTH else: if height > spaceAbove and \ spaceAbove > self.minimumHeight(): height = spaceAbove width = width + SCROLLBAR_WIDTH yPos = max(3, cursorRect.top() - height) xPos = cursorRect.right() - self._horizontalShift() if xPos + width + WIDGET_BORDER_MARGIN > parentSize.width(): xPos = max(3, parentSize.width() - WIDGET_BORDER_MARGIN - width) self.setGeometry(xPos, yPos, width, height) self._closeIfNotUpdatedTimer.stop()
def function[updateGeometry, parameter[self]]: constant[Move widget to point under cursor ] variable[WIDGET_BORDER_MARGIN] assign[=] constant[5] variable[SCROLLBAR_WIDTH] assign[=] constant[30] variable[sizeHint] assign[=] call[name[self].sizeHint, parameter[]] variable[width] assign[=] call[name[sizeHint].width, parameter[]] variable[height] assign[=] call[name[sizeHint].height, parameter[]] variable[cursorRect] assign[=] call[name[self]._qpart.cursorRect, parameter[]] variable[parentSize] assign[=] call[call[name[self].parentWidget, parameter[]].size, parameter[]] variable[spaceBelow] assign[=] binary_operation[binary_operation[call[name[parentSize].height, parameter[]] - call[name[cursorRect].bottom, parameter[]]] - name[WIDGET_BORDER_MARGIN]] variable[spaceAbove] assign[=] binary_operation[call[name[cursorRect].top, parameter[]] - name[WIDGET_BORDER_MARGIN]] if <ast.BoolOp object at 0x7da2041d9f30> begin[:] variable[yPos] assign[=] call[name[cursorRect].bottom, parameter[]] if <ast.BoolOp object at 0x7da2041db550> begin[:] variable[height] assign[=] name[spaceBelow] variable[width] assign[=] binary_operation[name[width] + name[SCROLLBAR_WIDTH]] variable[xPos] assign[=] binary_operation[call[name[cursorRect].right, parameter[]] - call[name[self]._horizontalShift, parameter[]]] if compare[binary_operation[binary_operation[name[xPos] + name[width]] + name[WIDGET_BORDER_MARGIN]] greater[>] call[name[parentSize].width, parameter[]]] begin[:] variable[xPos] assign[=] call[name[max], parameter[constant[3], binary_operation[binary_operation[call[name[parentSize].width, parameter[]] - name[WIDGET_BORDER_MARGIN]] - name[width]]]] call[name[self].setGeometry, parameter[name[xPos], name[yPos], name[width], name[height]]] call[name[self]._closeIfNotUpdatedTimer.stop, parameter[]]
keyword[def] identifier[updateGeometry] ( identifier[self] ): literal[string] identifier[WIDGET_BORDER_MARGIN] = literal[int] identifier[SCROLLBAR_WIDTH] = literal[int] identifier[sizeHint] = identifier[self] . identifier[sizeHint] () identifier[width] = identifier[sizeHint] . identifier[width] () identifier[height] = identifier[sizeHint] . identifier[height] () identifier[cursorRect] = identifier[self] . identifier[_qpart] . identifier[cursorRect] () identifier[parentSize] = identifier[self] . identifier[parentWidget] (). identifier[size] () identifier[spaceBelow] = identifier[parentSize] . identifier[height] ()- identifier[cursorRect] . identifier[bottom] ()- identifier[WIDGET_BORDER_MARGIN] identifier[spaceAbove] = identifier[cursorRect] . identifier[top] ()- identifier[WIDGET_BORDER_MARGIN] keyword[if] identifier[height] <= identifier[spaceBelow] keyword[or] identifier[spaceBelow] > identifier[spaceAbove] : identifier[yPos] = identifier[cursorRect] . identifier[bottom] () keyword[if] identifier[height] > identifier[spaceBelow] keyword[and] identifier[spaceBelow] > identifier[self] . identifier[minimumHeight] (): identifier[height] = identifier[spaceBelow] identifier[width] = identifier[width] + identifier[SCROLLBAR_WIDTH] keyword[else] : keyword[if] identifier[height] > identifier[spaceAbove] keyword[and] identifier[spaceAbove] > identifier[self] . identifier[minimumHeight] (): identifier[height] = identifier[spaceAbove] identifier[width] = identifier[width] + identifier[SCROLLBAR_WIDTH] identifier[yPos] = identifier[max] ( literal[int] , identifier[cursorRect] . identifier[top] ()- identifier[height] ) identifier[xPos] = identifier[cursorRect] . identifier[right] ()- identifier[self] . identifier[_horizontalShift] () keyword[if] identifier[xPos] + identifier[width] + identifier[WIDGET_BORDER_MARGIN] > identifier[parentSize] . identifier[width] (): identifier[xPos] = identifier[max] ( literal[int] , identifier[parentSize] . identifier[width] ()- identifier[WIDGET_BORDER_MARGIN] - identifier[width] ) identifier[self] . identifier[setGeometry] ( identifier[xPos] , identifier[yPos] , identifier[width] , identifier[height] ) identifier[self] . identifier[_closeIfNotUpdatedTimer] . identifier[stop] ()
def updateGeometry(self): """Move widget to point under cursor """ WIDGET_BORDER_MARGIN = 5 SCROLLBAR_WIDTH = 30 # just a guess sizeHint = self.sizeHint() width = sizeHint.width() height = sizeHint.height() cursorRect = self._qpart.cursorRect() parentSize = self.parentWidget().size() spaceBelow = parentSize.height() - cursorRect.bottom() - WIDGET_BORDER_MARGIN spaceAbove = cursorRect.top() - WIDGET_BORDER_MARGIN if height <= spaceBelow or spaceBelow > spaceAbove: yPos = cursorRect.bottom() if height > spaceBelow and spaceBelow > self.minimumHeight(): height = spaceBelow width = width + SCROLLBAR_WIDTH # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: if height > spaceAbove and spaceAbove > self.minimumHeight(): height = spaceAbove width = width + SCROLLBAR_WIDTH # depends on [control=['if'], data=[]] yPos = max(3, cursorRect.top() - height) xPos = cursorRect.right() - self._horizontalShift() if xPos + width + WIDGET_BORDER_MARGIN > parentSize.width(): xPos = max(3, parentSize.width() - WIDGET_BORDER_MARGIN - width) # depends on [control=['if'], data=[]] self.setGeometry(xPos, yPos, width, height) self._closeIfNotUpdatedTimer.stop()
def parse_stm_file(stm_file): r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ stm_segments = [] with codecs.open(stm_file, encoding="utf-8") as stm_lines: for stm_line in stm_lines: stmSegment = STMSegment(stm_line) if not "ignore_time_segment_in_scoring" == stmSegment.transcript: stm_segments.append(stmSegment) return stm_segments
def function[parse_stm_file, parameter[stm_file]]: constant[ Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. ] variable[stm_segments] assign[=] list[[]] with call[name[codecs].open, parameter[name[stm_file]]] begin[:] for taget[name[stm_line]] in starred[name[stm_lines]] begin[:] variable[stmSegment] assign[=] call[name[STMSegment], parameter[name[stm_line]]] if <ast.UnaryOp object at 0x7da1b203db10> begin[:] call[name[stm_segments].append, parameter[name[stmSegment]]] return[name[stm_segments]]
keyword[def] identifier[parse_stm_file] ( identifier[stm_file] ): literal[string] identifier[stm_segments] =[] keyword[with] identifier[codecs] . identifier[open] ( identifier[stm_file] , identifier[encoding] = literal[string] ) keyword[as] identifier[stm_lines] : keyword[for] identifier[stm_line] keyword[in] identifier[stm_lines] : identifier[stmSegment] = identifier[STMSegment] ( identifier[stm_line] ) keyword[if] keyword[not] literal[string] == identifier[stmSegment] . identifier[transcript] : identifier[stm_segments] . identifier[append] ( identifier[stmSegment] ) keyword[return] identifier[stm_segments]
def parse_stm_file(stm_file): """ Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ stm_segments = [] with codecs.open(stm_file, encoding='utf-8') as stm_lines: for stm_line in stm_lines: stmSegment = STMSegment(stm_line) if not 'ignore_time_segment_in_scoring' == stmSegment.transcript: stm_segments.append(stmSegment) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['stm_line']] # depends on [control=['with'], data=['stm_lines']] return stm_segments
def tunnel_open(self): ''' Open tunnel ''' if (self.server.is_server_running() == 'no' or self.server.is_server_running() == 'maybe'): print("Error: Sorry, you need to have the server running to open a " "tunnel. Try 'server on' first.") else: self.tunnel.open()
def function[tunnel_open, parameter[self]]: constant[ Open tunnel ] if <ast.BoolOp object at 0x7da20e957b80> begin[:] call[name[print], parameter[constant[Error: Sorry, you need to have the server running to open a tunnel. Try 'server on' first.]]]
keyword[def] identifier[tunnel_open] ( identifier[self] ): literal[string] keyword[if] ( identifier[self] . identifier[server] . identifier[is_server_running] ()== literal[string] keyword[or] identifier[self] . identifier[server] . identifier[is_server_running] ()== literal[string] ): identifier[print] ( literal[string] literal[string] ) keyword[else] : identifier[self] . identifier[tunnel] . identifier[open] ()
def tunnel_open(self): """ Open tunnel """ if self.server.is_server_running() == 'no' or self.server.is_server_running() == 'maybe': print("Error: Sorry, you need to have the server running to open a tunnel. Try 'server on' first.") # depends on [control=['if'], data=[]] else: self.tunnel.open()
def build_post_form_args(self, bucket_name, key, expires_in = 6000, acl = None, success_action_redirect = None, max_content_length = None, http_method = "http", fields=None, conditions=None): """ Taken from the AWS book Python examples and modified for use with boto This only returns the arguments required for the post form, not the actual form. This does not return the file input field which also needs to be added :type bucket_name: string :param bucket_name: Bucket to submit to :type key: string :param key: Key name, optionally add ${filename} to the end to attach the submitted filename :type expires_in: integer :param expires_in: Time (in seconds) before this expires, defaults to 6000 :type acl: :class:`boto.s3.acl.ACL` :param acl: ACL rule to use, if any :type success_action_redirect: string :param success_action_redirect: URL to redirect to on success :type max_content_length: integer :param max_content_length: Maximum size for this file :type http_method: string :param http_method: HTTP Method to use, "http" or "https" :rtype: dict :return: A dictionary containing field names/values as well as a url to POST to .. code-block:: python { "action": action_url_to_post_to, "fields": [ { "name": field_name, "value": field_value }, { "name": field_name2, "value": field_value2 } ] } """ if fields == None: fields = [] if conditions == None: conditions = [] expiration = time.gmtime(int(time.time() + expires_in)) # Generate policy document conditions.append('{"bucket": "%s"}' % bucket_name) if key.endswith("${filename}"): conditions.append('["starts-with", "$key", "%s"]' % key[:-len("${filename}")]) else: conditions.append('{"key": "%s"}' % key) if acl: conditions.append('{"acl": "%s"}' % acl) fields.append({ "name": "acl", "value": acl}) if success_action_redirect: conditions.append('{"success_action_redirect": "%s"}' % success_action_redirect) fields.append({ "name": "success_action_redirect", "value": success_action_redirect}) if max_content_length: conditions.append('["content-length-range", 0, %i]' % max_content_length) fields.append({"name":'content-length-range', "value": "0,%i" % max_content_length}) policy = self.build_post_policy(expiration, conditions) # Add the base64-encoded policy document as the 'policy' field policy_b64 = base64.b64encode(policy) fields.append({"name": "policy", "value": policy_b64}) # Add the AWS access key as the 'AWSAccessKeyId' field fields.append({"name": "AWSAccessKeyId", "value": self.aws_access_key_id}) # Add signature for encoded policy document as the 'AWSAccessKeyId' field signature = self._auth_handler.sign_string(policy_b64) fields.append({"name": "signature", "value": signature}) fields.append({"name": "key", "value": key}) # HTTPS protocol will be used if the secure HTTP option is enabled. url = '%s://%s/' % (http_method, self.calling_format.build_host(self.server_name(), bucket_name)) return {"action": url, "fields": fields}
def function[build_post_form_args, parameter[self, bucket_name, key, expires_in, acl, success_action_redirect, max_content_length, http_method, fields, conditions]]: constant[ Taken from the AWS book Python examples and modified for use with boto This only returns the arguments required for the post form, not the actual form. This does not return the file input field which also needs to be added :type bucket_name: string :param bucket_name: Bucket to submit to :type key: string :param key: Key name, optionally add ${filename} to the end to attach the submitted filename :type expires_in: integer :param expires_in: Time (in seconds) before this expires, defaults to 6000 :type acl: :class:`boto.s3.acl.ACL` :param acl: ACL rule to use, if any :type success_action_redirect: string :param success_action_redirect: URL to redirect to on success :type max_content_length: integer :param max_content_length: Maximum size for this file :type http_method: string :param http_method: HTTP Method to use, "http" or "https" :rtype: dict :return: A dictionary containing field names/values as well as a url to POST to .. code-block:: python { "action": action_url_to_post_to, "fields": [ { "name": field_name, "value": field_value }, { "name": field_name2, "value": field_value2 } ] } ] if compare[name[fields] equal[==] constant[None]] begin[:] variable[fields] assign[=] list[[]] if compare[name[conditions] equal[==] constant[None]] begin[:] variable[conditions] assign[=] list[[]] variable[expiration] assign[=] call[name[time].gmtime, parameter[call[name[int], parameter[binary_operation[call[name[time].time, parameter[]] + name[expires_in]]]]]] call[name[conditions].append, parameter[binary_operation[constant[{"bucket": "%s"}] <ast.Mod object at 0x7da2590d6920> name[bucket_name]]]] if call[name[key].endswith, parameter[constant[${filename}]]] begin[:] call[name[conditions].append, parameter[binary_operation[constant[["starts-with", "$key", "%s"]] <ast.Mod object at 0x7da2590d6920> call[name[key]][<ast.Slice object at 0x7da1b269ca30>]]]] if name[acl] begin[:] call[name[conditions].append, parameter[binary_operation[constant[{"acl": "%s"}] <ast.Mod object at 0x7da2590d6920> name[acl]]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da1b269c970>, <ast.Constant object at 0x7da1b269c910>], [<ast.Constant object at 0x7da1b269d900>, <ast.Name object at 0x7da1b269e590>]]]] if name[success_action_redirect] begin[:] call[name[conditions].append, parameter[binary_operation[constant[{"success_action_redirect": "%s"}] <ast.Mod object at 0x7da2590d6920> name[success_action_redirect]]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da1b269e0e0>, <ast.Constant object at 0x7da1b269dff0>], [<ast.Constant object at 0x7da1b269e110>, <ast.Name object at 0x7da1b269e080>]]]] if name[max_content_length] begin[:] call[name[conditions].append, parameter[binary_operation[constant[["content-length-range", 0, %i]] <ast.Mod object at 0x7da2590d6920> name[max_content_length]]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da1b269f250>, <ast.Constant object at 0x7da20c6a8be0>], [<ast.Constant object at 0x7da20c6ab6d0>, <ast.BinOp object at 0x7da20c6aaef0>]]]] variable[policy] assign[=] call[name[self].build_post_policy, parameter[name[expiration], name[conditions]]] variable[policy_b64] assign[=] call[name[base64].b64encode, parameter[name[policy]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da20c6a8940>, <ast.Constant object at 0x7da20c6a89d0>], [<ast.Constant object at 0x7da20c6aa200>, <ast.Name object at 0x7da20c6a8b20>]]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da20c6a9cc0>, <ast.Constant object at 0x7da20c6aa6b0>], [<ast.Constant object at 0x7da20c6a8340>, <ast.Attribute object at 0x7da20c6a8520>]]]] variable[signature] assign[=] call[name[self]._auth_handler.sign_string, parameter[name[policy_b64]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da1b269f280>, <ast.Constant object at 0x7da1b269dbd0>], [<ast.Constant object at 0x7da1b269d0f0>, <ast.Name object at 0x7da1b269dc00>]]]] call[name[fields].append, parameter[dictionary[[<ast.Constant object at 0x7da1b269f700>, <ast.Constant object at 0x7da1b269f670>], [<ast.Constant object at 0x7da1b269fe50>, <ast.Name object at 0x7da1b269f610>]]]] variable[url] assign[=] binary_operation[constant[%s://%s/] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b269d930>, <ast.Call object at 0x7da1b269db10>]]] return[dictionary[[<ast.Constant object at 0x7da1b269d300>, <ast.Constant object at 0x7da1b269d330>], [<ast.Name object at 0x7da1b269d390>, <ast.Name object at 0x7da1b269d570>]]]
keyword[def] identifier[build_post_form_args] ( identifier[self] , identifier[bucket_name] , identifier[key] , identifier[expires_in] = literal[int] , identifier[acl] = keyword[None] , identifier[success_action_redirect] = keyword[None] , identifier[max_content_length] = keyword[None] , identifier[http_method] = literal[string] , identifier[fields] = keyword[None] , identifier[conditions] = keyword[None] ): literal[string] keyword[if] identifier[fields] == keyword[None] : identifier[fields] =[] keyword[if] identifier[conditions] == keyword[None] : identifier[conditions] =[] identifier[expiration] = identifier[time] . identifier[gmtime] ( identifier[int] ( identifier[time] . identifier[time] ()+ identifier[expires_in] )) identifier[conditions] . identifier[append] ( literal[string] % identifier[bucket_name] ) keyword[if] identifier[key] . identifier[endswith] ( literal[string] ): identifier[conditions] . identifier[append] ( literal[string] % identifier[key] [:- identifier[len] ( literal[string] )]) keyword[else] : identifier[conditions] . identifier[append] ( literal[string] % identifier[key] ) keyword[if] identifier[acl] : identifier[conditions] . identifier[append] ( literal[string] % identifier[acl] ) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[acl] }) keyword[if] identifier[success_action_redirect] : identifier[conditions] . identifier[append] ( literal[string] % identifier[success_action_redirect] ) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[success_action_redirect] }) keyword[if] identifier[max_content_length] : identifier[conditions] . identifier[append] ( literal[string] % identifier[max_content_length] ) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : literal[string] % identifier[max_content_length] }) identifier[policy] = identifier[self] . identifier[build_post_policy] ( identifier[expiration] , identifier[conditions] ) identifier[policy_b64] = identifier[base64] . identifier[b64encode] ( identifier[policy] ) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[policy_b64] }) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[self] . identifier[aws_access_key_id] }) identifier[signature] = identifier[self] . identifier[_auth_handler] . identifier[sign_string] ( identifier[policy_b64] ) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[signature] }) identifier[fields] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[key] }) identifier[url] = literal[string] %( identifier[http_method] , identifier[self] . identifier[calling_format] . identifier[build_host] ( identifier[self] . identifier[server_name] (), identifier[bucket_name] )) keyword[return] { literal[string] : identifier[url] , literal[string] : identifier[fields] }
def build_post_form_args(self, bucket_name, key, expires_in=6000, acl=None, success_action_redirect=None, max_content_length=None, http_method='http', fields=None, conditions=None): """ Taken from the AWS book Python examples and modified for use with boto This only returns the arguments required for the post form, not the actual form. This does not return the file input field which also needs to be added :type bucket_name: string :param bucket_name: Bucket to submit to :type key: string :param key: Key name, optionally add ${filename} to the end to attach the submitted filename :type expires_in: integer :param expires_in: Time (in seconds) before this expires, defaults to 6000 :type acl: :class:`boto.s3.acl.ACL` :param acl: ACL rule to use, if any :type success_action_redirect: string :param success_action_redirect: URL to redirect to on success :type max_content_length: integer :param max_content_length: Maximum size for this file :type http_method: string :param http_method: HTTP Method to use, "http" or "https" :rtype: dict :return: A dictionary containing field names/values as well as a url to POST to .. code-block:: python { "action": action_url_to_post_to, "fields": [ { "name": field_name, "value": field_value }, { "name": field_name2, "value": field_value2 } ] } """ if fields == None: fields = [] # depends on [control=['if'], data=['fields']] if conditions == None: conditions = [] # depends on [control=['if'], data=['conditions']] expiration = time.gmtime(int(time.time() + expires_in)) # Generate policy document conditions.append('{"bucket": "%s"}' % bucket_name) if key.endswith('${filename}'): conditions.append('["starts-with", "$key", "%s"]' % key[:-len('${filename}')]) # depends on [control=['if'], data=[]] else: conditions.append('{"key": "%s"}' % key) if acl: conditions.append('{"acl": "%s"}' % acl) fields.append({'name': 'acl', 'value': acl}) # depends on [control=['if'], data=[]] if success_action_redirect: conditions.append('{"success_action_redirect": "%s"}' % success_action_redirect) fields.append({'name': 'success_action_redirect', 'value': success_action_redirect}) # depends on [control=['if'], data=[]] if max_content_length: conditions.append('["content-length-range", 0, %i]' % max_content_length) fields.append({'name': 'content-length-range', 'value': '0,%i' % max_content_length}) # depends on [control=['if'], data=[]] policy = self.build_post_policy(expiration, conditions) # Add the base64-encoded policy document as the 'policy' field policy_b64 = base64.b64encode(policy) fields.append({'name': 'policy', 'value': policy_b64}) # Add the AWS access key as the 'AWSAccessKeyId' field fields.append({'name': 'AWSAccessKeyId', 'value': self.aws_access_key_id}) # Add signature for encoded policy document as the 'AWSAccessKeyId' field signature = self._auth_handler.sign_string(policy_b64) fields.append({'name': 'signature', 'value': signature}) fields.append({'name': 'key', 'value': key}) # HTTPS protocol will be used if the secure HTTP option is enabled. url = '%s://%s/' % (http_method, self.calling_format.build_host(self.server_name(), bucket_name)) return {'action': url, 'fields': fields}
def NOAC_metric(bpmn_graph): """ Returns the value of the NOAC metric (Number of Activities and control flow elements) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. """ activities_count = all_activities_count(bpmn_graph) control_flow_count = all_control_flow_elements_count(bpmn_graph) return activities_count + control_flow_count
def function[NOAC_metric, parameter[bpmn_graph]]: constant[ Returns the value of the NOAC metric (Number of Activities and control flow elements) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. ] variable[activities_count] assign[=] call[name[all_activities_count], parameter[name[bpmn_graph]]] variable[control_flow_count] assign[=] call[name[all_control_flow_elements_count], parameter[name[bpmn_graph]]] return[binary_operation[name[activities_count] + name[control_flow_count]]]
keyword[def] identifier[NOAC_metric] ( identifier[bpmn_graph] ): literal[string] identifier[activities_count] = identifier[all_activities_count] ( identifier[bpmn_graph] ) identifier[control_flow_count] = identifier[all_control_flow_elements_count] ( identifier[bpmn_graph] ) keyword[return] identifier[activities_count] + identifier[control_flow_count]
def NOAC_metric(bpmn_graph): """ Returns the value of the NOAC metric (Number of Activities and control flow elements) for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. """ activities_count = all_activities_count(bpmn_graph) control_flow_count = all_control_flow_elements_count(bpmn_graph) return activities_count + control_flow_count
def _ipython_key_completions_(self) -> List[str]: """Provide method for the key-autocompletions in IPython. See http://ipython.readthedocs.io/en/stable/config/integrating.html#tab-completion For the details. """ # noqa item_lists = [item for sublist in self._item_sources for item in sublist if isinstance(item, str)] return list(set(item_lists))
def function[_ipython_key_completions_, parameter[self]]: constant[Provide method for the key-autocompletions in IPython. See http://ipython.readthedocs.io/en/stable/config/integrating.html#tab-completion For the details. ] variable[item_lists] assign[=] <ast.ListComp object at 0x7da20c6c7bb0> return[call[name[list], parameter[call[name[set], parameter[name[item_lists]]]]]]
keyword[def] identifier[_ipython_key_completions_] ( identifier[self] )-> identifier[List] [ identifier[str] ]: literal[string] identifier[item_lists] =[ identifier[item] keyword[for] identifier[sublist] keyword[in] identifier[self] . identifier[_item_sources] keyword[for] identifier[item] keyword[in] identifier[sublist] keyword[if] identifier[isinstance] ( identifier[item] , identifier[str] )] keyword[return] identifier[list] ( identifier[set] ( identifier[item_lists] ))
def _ipython_key_completions_(self) -> List[str]: """Provide method for the key-autocompletions in IPython. See http://ipython.readthedocs.io/en/stable/config/integrating.html#tab-completion For the details. """ # noqa item_lists = [item for sublist in self._item_sources for item in sublist if isinstance(item, str)] return list(set(item_lists))
def _guess_content_type(url): ''' Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream' ''' OCTET_STREAM = 'application/octet-stream' n = url.rfind('.') if n == -1: return OCTET_STREAM return mimetypes.types_map.get(url[n:].lower(), OCTET_STREAM)
def function[_guess_content_type, parameter[url]]: constant[ Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream' ] variable[OCTET_STREAM] assign[=] constant[application/octet-stream] variable[n] assign[=] call[name[url].rfind, parameter[constant[.]]] if compare[name[n] equal[==] <ast.UnaryOp object at 0x7da1b22ce2c0>] begin[:] return[name[OCTET_STREAM]] return[call[name[mimetypes].types_map.get, parameter[call[call[name[url]][<ast.Slice object at 0x7da1b22cfbb0>].lower, parameter[]], name[OCTET_STREAM]]]]
keyword[def] identifier[_guess_content_type] ( identifier[url] ): literal[string] identifier[OCTET_STREAM] = literal[string] identifier[n] = identifier[url] . identifier[rfind] ( literal[string] ) keyword[if] identifier[n] ==- literal[int] : keyword[return] identifier[OCTET_STREAM] keyword[return] identifier[mimetypes] . identifier[types_map] . identifier[get] ( identifier[url] [ identifier[n] :]. identifier[lower] (), identifier[OCTET_STREAM] )
def _guess_content_type(url): """ Guess content type by url. >>> _guess_content_type('http://test/A.HTML') 'text/html' >>> _guess_content_type('http://test/a.jpg') 'image/jpeg' >>> _guess_content_type('/path.txt/aaa') 'application/octet-stream' """ OCTET_STREAM = 'application/octet-stream' n = url.rfind('.') if n == -1: return OCTET_STREAM # depends on [control=['if'], data=[]] return mimetypes.types_map.get(url[n:].lower(), OCTET_STREAM)
def unlock(self, unique_id_prefix, case_id, interact): """Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purposes of analytics. interact -- function; handles user interaction during the unlocking phase. """ print(self.setup.strip()) prompt_num = 0 current_prompt = [] try: for line in self.lines: if isinstance(line, str) and line: print(line) current_prompt.append(line) elif isinstance(line, CodeAnswer): prompt_num += 1 if not line.locked: print('\n'.join(line.output)) continue unique_id = self._construct_unique_id(unique_id_prefix, self.lines) line.output = interact(unique_id, case_id + ' > Prompt {}'.format(prompt_num), '\n'.join(current_prompt), line.output, line.choices) line.locked = False current_prompt = [] self.locked = False finally: self._sync_code()
def function[unlock, parameter[self, unique_id_prefix, case_id, interact]]: constant[Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purposes of analytics. interact -- function; handles user interaction during the unlocking phase. ] call[name[print], parameter[call[name[self].setup.strip, parameter[]]]] variable[prompt_num] assign[=] constant[0] variable[current_prompt] assign[=] list[[]] <ast.Try object at 0x7da1b064fd00>
keyword[def] identifier[unlock] ( identifier[self] , identifier[unique_id_prefix] , identifier[case_id] , identifier[interact] ): literal[string] identifier[print] ( identifier[self] . identifier[setup] . identifier[strip] ()) identifier[prompt_num] = literal[int] identifier[current_prompt] =[] keyword[try] : keyword[for] identifier[line] keyword[in] identifier[self] . identifier[lines] : keyword[if] identifier[isinstance] ( identifier[line] , identifier[str] ) keyword[and] identifier[line] : identifier[print] ( identifier[line] ) identifier[current_prompt] . identifier[append] ( identifier[line] ) keyword[elif] identifier[isinstance] ( identifier[line] , identifier[CodeAnswer] ): identifier[prompt_num] += literal[int] keyword[if] keyword[not] identifier[line] . identifier[locked] : identifier[print] ( literal[string] . identifier[join] ( identifier[line] . identifier[output] )) keyword[continue] identifier[unique_id] = identifier[self] . identifier[_construct_unique_id] ( identifier[unique_id_prefix] , identifier[self] . identifier[lines] ) identifier[line] . identifier[output] = identifier[interact] ( identifier[unique_id] , identifier[case_id] + literal[string] . identifier[format] ( identifier[prompt_num] ), literal[string] . identifier[join] ( identifier[current_prompt] ), identifier[line] . identifier[output] , identifier[line] . identifier[choices] ) identifier[line] . identifier[locked] = keyword[False] identifier[current_prompt] =[] identifier[self] . identifier[locked] = keyword[False] keyword[finally] : identifier[self] . identifier[_sync_code] ()
def unlock(self, unique_id_prefix, case_id, interact): """Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purposes of analytics. interact -- function; handles user interaction during the unlocking phase. """ print(self.setup.strip()) prompt_num = 0 current_prompt = [] try: for line in self.lines: if isinstance(line, str) and line: print(line) current_prompt.append(line) # depends on [control=['if'], data=[]] elif isinstance(line, CodeAnswer): prompt_num += 1 if not line.locked: print('\n'.join(line.output)) continue # depends on [control=['if'], data=[]] unique_id = self._construct_unique_id(unique_id_prefix, self.lines) line.output = interact(unique_id, case_id + ' > Prompt {}'.format(prompt_num), '\n'.join(current_prompt), line.output, line.choices) line.locked = False current_prompt = [] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] self.locked = False # depends on [control=['try'], data=[]] finally: self._sync_code()
def clean_descriptor(self, number): """Close file descriptor and remove underlying files.""" self.descriptors[number]['stdout'].close() self.descriptors[number]['stderr'].close() if os.path.exists(self.descriptors[number]['stdout_path']): os.remove(self.descriptors[number]['stdout_path']) if os.path.exists(self.descriptors[number]['stderr_path']): os.remove(self.descriptors[number]['stderr_path'])
def function[clean_descriptor, parameter[self, number]]: constant[Close file descriptor and remove underlying files.] call[call[call[name[self].descriptors][name[number]]][constant[stdout]].close, parameter[]] call[call[call[name[self].descriptors][name[number]]][constant[stderr]].close, parameter[]] if call[name[os].path.exists, parameter[call[call[name[self].descriptors][name[number]]][constant[stdout_path]]]] begin[:] call[name[os].remove, parameter[call[call[name[self].descriptors][name[number]]][constant[stdout_path]]]] if call[name[os].path.exists, parameter[call[call[name[self].descriptors][name[number]]][constant[stderr_path]]]] begin[:] call[name[os].remove, parameter[call[call[name[self].descriptors][name[number]]][constant[stderr_path]]]]
keyword[def] identifier[clean_descriptor] ( identifier[self] , identifier[number] ): literal[string] identifier[self] . identifier[descriptors] [ identifier[number] ][ literal[string] ]. identifier[close] () identifier[self] . identifier[descriptors] [ identifier[number] ][ literal[string] ]. identifier[close] () keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[descriptors] [ identifier[number] ][ literal[string] ]): identifier[os] . identifier[remove] ( identifier[self] . identifier[descriptors] [ identifier[number] ][ literal[string] ]) keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[descriptors] [ identifier[number] ][ literal[string] ]): identifier[os] . identifier[remove] ( identifier[self] . identifier[descriptors] [ identifier[number] ][ literal[string] ])
def clean_descriptor(self, number): """Close file descriptor and remove underlying files.""" self.descriptors[number]['stdout'].close() self.descriptors[number]['stderr'].close() if os.path.exists(self.descriptors[number]['stdout_path']): os.remove(self.descriptors[number]['stdout_path']) # depends on [control=['if'], data=[]] if os.path.exists(self.descriptors[number]['stderr_path']): os.remove(self.descriptors[number]['stderr_path']) # depends on [control=['if'], data=[]]
def turn_left(self): """Make the drone rotate left.""" self.at(ardrone.at.pcmd, True, 0, 0, 0, -self.speed)
def function[turn_left, parameter[self]]: constant[Make the drone rotate left.] call[name[self].at, parameter[name[ardrone].at.pcmd, constant[True], constant[0], constant[0], constant[0], <ast.UnaryOp object at 0x7da1b1042710>]]
keyword[def] identifier[turn_left] ( identifier[self] ): literal[string] identifier[self] . identifier[at] ( identifier[ardrone] . identifier[at] . identifier[pcmd] , keyword[True] , literal[int] , literal[int] , literal[int] ,- identifier[self] . identifier[speed] )
def turn_left(self): """Make the drone rotate left.""" self.at(ardrone.at.pcmd, True, 0, 0, 0, -self.speed)
def handle_page_location_changed(self, timeout=None): ''' If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location. ''' # In general, this is often called after other mechanisms have confirmed # that the tab has already navigated. As such, we want to not wait a while # to discover something went wrong, so use a timeout that basically just # results in checking the available buffer, and nothing else. if not timeout: timeout = 0.1 self.log.debug("We may have redirected. Checking.") messages = self.transport.recv_all_filtered(filter_funcs.capture_loading_events, tab_key=self.tab_id) if not messages: raise ChromeError("Couldn't track redirect! No idea what to do!") last_message = messages[-1] self.log.info("Probably a redirect! New content url: '%s'", last_message['params']['documentURL']) resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(last_message['params']['documentURL'], last_message['params']['frameId']), tab_key=self.tab_id) resp = resp['params'] ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(";")[0] # We assume the last document request was the redirect. # This is /probably/ kind of a poor practice, but what the hell. # I have no idea what this would do if there are non-html documents (or if that can even happen.) return self.get_unpacked_response_body(last_message['params']['requestId'], mimetype=ctype)
def function[handle_page_location_changed, parameter[self, timeout]]: constant[ If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location. ] if <ast.UnaryOp object at 0x7da1b11161d0> begin[:] variable[timeout] assign[=] constant[0.1] call[name[self].log.debug, parameter[constant[We may have redirected. Checking.]]] variable[messages] assign[=] call[name[self].transport.recv_all_filtered, parameter[name[filter_funcs].capture_loading_events]] if <ast.UnaryOp object at 0x7da1b1116b30> begin[:] <ast.Raise object at 0x7da1b11152a0> variable[last_message] assign[=] call[name[messages]][<ast.UnaryOp object at 0x7da1b1115330>] call[name[self].log.info, parameter[constant[Probably a redirect! New content url: '%s'], call[call[name[last_message]][constant[params]]][constant[documentURL]]]] variable[resp] assign[=] call[name[self].transport.recv_filtered, parameter[call[name[filter_funcs].network_response_recieved_for_url, parameter[call[call[name[last_message]][constant[params]]][constant[documentURL]], call[call[name[last_message]][constant[params]]][constant[frameId]]]]]] variable[resp] assign[=] call[name[resp]][constant[params]] variable[ctype] assign[=] constant[application/unknown] variable[resp_response] assign[=] call[name[resp]][constant[response]] if compare[constant[mimeType] in name[resp_response]] begin[:] variable[ctype] assign[=] call[name[resp_response]][constant[mimeType]] if <ast.BoolOp object at 0x7da1b11ea020> begin[:] variable[ctype] assign[=] call[call[call[call[name[resp_response]][constant[headers]]][constant[content-type]].split, parameter[constant[;]]]][constant[0]] return[call[name[self].get_unpacked_response_body, parameter[call[call[name[last_message]][constant[params]]][constant[requestId]]]]]
keyword[def] identifier[handle_page_location_changed] ( identifier[self] , identifier[timeout] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[timeout] : identifier[timeout] = literal[int] identifier[self] . identifier[log] . identifier[debug] ( literal[string] ) identifier[messages] = identifier[self] . identifier[transport] . identifier[recv_all_filtered] ( identifier[filter_funcs] . identifier[capture_loading_events] , identifier[tab_key] = identifier[self] . identifier[tab_id] ) keyword[if] keyword[not] identifier[messages] : keyword[raise] identifier[ChromeError] ( literal[string] ) identifier[last_message] = identifier[messages] [- literal[int] ] identifier[self] . identifier[log] . identifier[info] ( literal[string] , identifier[last_message] [ literal[string] ][ literal[string] ]) identifier[resp] = identifier[self] . identifier[transport] . identifier[recv_filtered] ( identifier[filter_funcs] . identifier[network_response_recieved_for_url] ( identifier[last_message] [ literal[string] ][ literal[string] ], identifier[last_message] [ literal[string] ][ literal[string] ]), identifier[tab_key] = identifier[self] . identifier[tab_id] ) identifier[resp] = identifier[resp] [ literal[string] ] identifier[ctype] = literal[string] identifier[resp_response] = identifier[resp] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[resp_response] : identifier[ctype] = identifier[resp_response] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[resp_response] keyword[and] literal[string] keyword[in] identifier[resp_response] [ literal[string] ]: identifier[ctype] = identifier[resp_response] [ literal[string] ][ literal[string] ]. identifier[split] ( literal[string] )[ literal[int] ] keyword[return] identifier[self] . identifier[get_unpacked_response_body] ( identifier[last_message] [ literal[string] ][ literal[string] ], identifier[mimetype] = identifier[ctype] )
def handle_page_location_changed(self, timeout=None): """ If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location. """ # In general, this is often called after other mechanisms have confirmed # that the tab has already navigated. As such, we want to not wait a while # to discover something went wrong, so use a timeout that basically just # results in checking the available buffer, and nothing else. if not timeout: timeout = 0.1 # depends on [control=['if'], data=[]] self.log.debug('We may have redirected. Checking.') messages = self.transport.recv_all_filtered(filter_funcs.capture_loading_events, tab_key=self.tab_id) if not messages: raise ChromeError("Couldn't track redirect! No idea what to do!") # depends on [control=['if'], data=[]] last_message = messages[-1] self.log.info("Probably a redirect! New content url: '%s'", last_message['params']['documentURL']) resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(last_message['params']['documentURL'], last_message['params']['frameId']), tab_key=self.tab_id) resp = resp['params'] ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] # depends on [control=['if'], data=['resp_response']] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(';')[0] # depends on [control=['if'], data=[]] # We assume the last document request was the redirect. # This is /probably/ kind of a poor practice, but what the hell. # I have no idea what this would do if there are non-html documents (or if that can even happen.) return self.get_unpacked_response_body(last_message['params']['requestId'], mimetype=ctype)
def get_timestamp_column(expression, column_name): """Postgres is unable to identify mixed case column names unless they are quoted.""" if expression: return expression elif column_name.lower() != column_name: return f'"{column_name}"' return column_name
def function[get_timestamp_column, parameter[expression, column_name]]: constant[Postgres is unable to identify mixed case column names unless they are quoted.] if name[expression] begin[:] return[name[expression]] return[name[column_name]]
keyword[def] identifier[get_timestamp_column] ( identifier[expression] , identifier[column_name] ): literal[string] keyword[if] identifier[expression] : keyword[return] identifier[expression] keyword[elif] identifier[column_name] . identifier[lower] ()!= identifier[column_name] : keyword[return] literal[string] keyword[return] identifier[column_name]
def get_timestamp_column(expression, column_name): """Postgres is unable to identify mixed case column names unless they are quoted.""" if expression: return expression # depends on [control=['if'], data=[]] elif column_name.lower() != column_name: return f'"{column_name}"' # depends on [control=['if'], data=['column_name']] return column_name
def download(self, url, post=False, parameters=None, timeout=None): # type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response """Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]): Parameters to pass. Defaults to None. timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout). Returns: requests.Response: Response """ return self.setup(url, stream=False, post=post, parameters=parameters, timeout=timeout)
def function[download, parameter[self, url, post, parameters, timeout]]: constant[Download url Args: url (str): URL to download post (bool): Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]): Parameters to pass. Defaults to None. timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout). Returns: requests.Response: Response ] return[call[name[self].setup, parameter[name[url]]]]
keyword[def] identifier[download] ( identifier[self] , identifier[url] , identifier[post] = keyword[False] , identifier[parameters] = keyword[None] , identifier[timeout] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[setup] ( identifier[url] , identifier[stream] = keyword[False] , identifier[post] = identifier[post] , identifier[parameters] = identifier[parameters] , identifier[timeout] = identifier[timeout] )
def download(self, url, post=False, parameters=None, timeout=None): # type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response 'Download url\n\n Args:\n url (str): URL to download\n post (bool): Whether to use POST instead of GET. Defaults to False.\n parameters (Optional[Dict]): Parameters to pass. Defaults to None.\n timeout (Optional[float]): Timeout for connecting to URL. Defaults to None (no timeout).\n\n Returns:\n requests.Response: Response\n\n ' return self.setup(url, stream=False, post=post, parameters=parameters, timeout=timeout)
def HashBuffer(self, buf): """Updates underlying hashers with a given buffer. Args: buf: A byte buffer (string object) that is going to be fed to the hashers. """ for hasher in itervalues(self._hashers): hasher.update(buf) if self._progress: self._progress() self._bytes_read += len(buf)
def function[HashBuffer, parameter[self, buf]]: constant[Updates underlying hashers with a given buffer. Args: buf: A byte buffer (string object) that is going to be fed to the hashers. ] for taget[name[hasher]] in starred[call[name[itervalues], parameter[name[self]._hashers]]] begin[:] call[name[hasher].update, parameter[name[buf]]] if name[self]._progress begin[:] call[name[self]._progress, parameter[]] <ast.AugAssign object at 0x7da2044c0880>
keyword[def] identifier[HashBuffer] ( identifier[self] , identifier[buf] ): literal[string] keyword[for] identifier[hasher] keyword[in] identifier[itervalues] ( identifier[self] . identifier[_hashers] ): identifier[hasher] . identifier[update] ( identifier[buf] ) keyword[if] identifier[self] . identifier[_progress] : identifier[self] . identifier[_progress] () identifier[self] . identifier[_bytes_read] += identifier[len] ( identifier[buf] )
def HashBuffer(self, buf): """Updates underlying hashers with a given buffer. Args: buf: A byte buffer (string object) that is going to be fed to the hashers. """ for hasher in itervalues(self._hashers): hasher.update(buf) if self._progress: self._progress() # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['hasher']] self._bytes_read += len(buf)
def set_parent(self, new_parent, init=False): "Store the gui/wx object parent for this component" # set init=True if this is called from the constructor self._parent = get(new_parent, init)
def function[set_parent, parameter[self, new_parent, init]]: constant[Store the gui/wx object parent for this component] name[self]._parent assign[=] call[name[get], parameter[name[new_parent], name[init]]]
keyword[def] identifier[set_parent] ( identifier[self] , identifier[new_parent] , identifier[init] = keyword[False] ): literal[string] identifier[self] . identifier[_parent] = identifier[get] ( identifier[new_parent] , identifier[init] )
def set_parent(self, new_parent, init=False): """Store the gui/wx object parent for this component""" # set init=True if this is called from the constructor self._parent = get(new_parent, init)
def parse_ents(doc, options={}): """Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents. """ ents = [ {"start": ent.start_char, "end": ent.end_char, "label": ent.label_} for ent in doc.ents ] if not ents: user_warning(Warnings.W006) title = doc.user_data.get("title", None) if hasattr(doc, "user_data") else None settings = get_doc_settings(doc) return {"text": doc.text, "ents": ents, "title": title, "settings": settings}
def function[parse_ents, parameter[doc, options]]: constant[Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents. ] variable[ents] assign[=] <ast.ListComp object at 0x7da1b1eac280> if <ast.UnaryOp object at 0x7da1b1ead330> begin[:] call[name[user_warning], parameter[name[Warnings].W006]] variable[title] assign[=] <ast.IfExp object at 0x7da1b1eaf9a0> variable[settings] assign[=] call[name[get_doc_settings], parameter[name[doc]]] return[dictionary[[<ast.Constant object at 0x7da1b1eaedd0>, <ast.Constant object at 0x7da1b1eaf1c0>, <ast.Constant object at 0x7da1b1eac9d0>, <ast.Constant object at 0x7da1b1ead6f0>], [<ast.Attribute object at 0x7da1b1eac3a0>, <ast.Name object at 0x7da1b1ead8a0>, <ast.Name object at 0x7da1b1ead780>, <ast.Name object at 0x7da1b1ead8d0>]]]
keyword[def] identifier[parse_ents] ( identifier[doc] , identifier[options] ={}): literal[string] identifier[ents] =[ { literal[string] : identifier[ent] . identifier[start_char] , literal[string] : identifier[ent] . identifier[end_char] , literal[string] : identifier[ent] . identifier[label_] } keyword[for] identifier[ent] keyword[in] identifier[doc] . identifier[ents] ] keyword[if] keyword[not] identifier[ents] : identifier[user_warning] ( identifier[Warnings] . identifier[W006] ) identifier[title] = identifier[doc] . identifier[user_data] . identifier[get] ( literal[string] , keyword[None] ) keyword[if] identifier[hasattr] ( identifier[doc] , literal[string] ) keyword[else] keyword[None] identifier[settings] = identifier[get_doc_settings] ( identifier[doc] ) keyword[return] { literal[string] : identifier[doc] . identifier[text] , literal[string] : identifier[ents] , literal[string] : identifier[title] , literal[string] : identifier[settings] }
def parse_ents(doc, options={}): """Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents. """ ents = [{'start': ent.start_char, 'end': ent.end_char, 'label': ent.label_} for ent in doc.ents] if not ents: user_warning(Warnings.W006) # depends on [control=['if'], data=[]] title = doc.user_data.get('title', None) if hasattr(doc, 'user_data') else None settings = get_doc_settings(doc) return {'text': doc.text, 'ents': ents, 'title': title, 'settings': settings}
def blocks_to_mark_complete_on_view(self, blocks): """ Returns a set of blocks which should be marked complete on view and haven't been yet. """ blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)} completions = self.get_completions({block.location for block in blocks}) return {block for block in blocks if completions.get(block.location, 0) < 1.0}
def function[blocks_to_mark_complete_on_view, parameter[self, blocks]]: constant[ Returns a set of blocks which should be marked complete on view and haven't been yet. ] variable[blocks] assign[=] <ast.SetComp object at 0x7da1b04a7310> variable[completions] assign[=] call[name[self].get_completions, parameter[<ast.SetComp object at 0x7da1b04a4880>]] return[<ast.SetComp object at 0x7da1b04a6920>]
keyword[def] identifier[blocks_to_mark_complete_on_view] ( identifier[self] , identifier[blocks] ): literal[string] identifier[blocks] ={ identifier[block] keyword[for] identifier[block] keyword[in] identifier[blocks] keyword[if] identifier[self] . identifier[can_mark_block_complete_on_view] ( identifier[block] )} identifier[completions] = identifier[self] . identifier[get_completions] ({ identifier[block] . identifier[location] keyword[for] identifier[block] keyword[in] identifier[blocks] }) keyword[return] { identifier[block] keyword[for] identifier[block] keyword[in] identifier[blocks] keyword[if] identifier[completions] . identifier[get] ( identifier[block] . identifier[location] , literal[int] )< literal[int] }
def blocks_to_mark_complete_on_view(self, blocks): """ Returns a set of blocks which should be marked complete on view and haven't been yet. """ blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)} completions = self.get_completions({block.location for block in blocks}) return {block for block in blocks if completions.get(block.location, 0) < 1.0}
def seq_lrepr( iterable: Iterable[Any], start: str, end: str, meta=None, **kwargs ) -> str: """Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = kwargs["print_level"] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL kwargs = _process_kwargs(**kwargs) trailer = [] print_dup = kwargs["print_dup"] print_length = kwargs["print_length"] if not print_dup and isinstance(print_length, int): items = seq(iterable).take(print_length + 1).to_list() if len(items) > print_length: items.pop() trailer.append(SURPASSED_PRINT_LENGTH) else: items = iterable items = list(map(lambda o: lrepr(o, **kwargs), items)) seq_lrepr = PRINT_SEPARATOR.join(items + trailer) print_meta = kwargs["print_meta"] if print_meta and meta: return f"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}" return f"{start}{seq_lrepr}{end}"
def function[seq_lrepr, parameter[iterable, start, end, meta]]: constant[Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.] variable[print_level] assign[=] call[name[kwargs]][constant[print_level]] if <ast.BoolOp object at 0x7da1b03282b0> begin[:] return[name[SURPASSED_PRINT_LEVEL]] variable[kwargs] assign[=] call[name[_process_kwargs], parameter[]] variable[trailer] assign[=] list[[]] variable[print_dup] assign[=] call[name[kwargs]][constant[print_dup]] variable[print_length] assign[=] call[name[kwargs]][constant[print_length]] if <ast.BoolOp object at 0x7da1b0212890> begin[:] variable[items] assign[=] call[call[call[name[seq], parameter[name[iterable]]].take, parameter[binary_operation[name[print_length] + constant[1]]]].to_list, parameter[]] if compare[call[name[len], parameter[name[items]]] greater[>] name[print_length]] begin[:] call[name[items].pop, parameter[]] call[name[trailer].append, parameter[name[SURPASSED_PRINT_LENGTH]]] variable[items] assign[=] call[name[list], parameter[call[name[map], parameter[<ast.Lambda object at 0x7da1b0211ab0>, name[items]]]]] variable[seq_lrepr] assign[=] call[name[PRINT_SEPARATOR].join, parameter[binary_operation[name[items] + name[trailer]]]] variable[print_meta] assign[=] call[name[kwargs]][constant[print_meta]] if <ast.BoolOp object at 0x7da1b0213760> begin[:] return[<ast.JoinedStr object at 0x7da1b02126b0>] return[<ast.JoinedStr object at 0x7da1b0213100>]
keyword[def] identifier[seq_lrepr] ( identifier[iterable] : identifier[Iterable] [ identifier[Any] ], identifier[start] : identifier[str] , identifier[end] : identifier[str] , identifier[meta] = keyword[None] ,** identifier[kwargs] )-> identifier[str] : literal[string] identifier[print_level] = identifier[kwargs] [ literal[string] ] keyword[if] identifier[isinstance] ( identifier[print_level] , identifier[int] ) keyword[and] identifier[print_level] < literal[int] : keyword[return] identifier[SURPASSED_PRINT_LEVEL] identifier[kwargs] = identifier[_process_kwargs] (** identifier[kwargs] ) identifier[trailer] =[] identifier[print_dup] = identifier[kwargs] [ literal[string] ] identifier[print_length] = identifier[kwargs] [ literal[string] ] keyword[if] keyword[not] identifier[print_dup] keyword[and] identifier[isinstance] ( identifier[print_length] , identifier[int] ): identifier[items] = identifier[seq] ( identifier[iterable] ). identifier[take] ( identifier[print_length] + literal[int] ). identifier[to_list] () keyword[if] identifier[len] ( identifier[items] )> identifier[print_length] : identifier[items] . identifier[pop] () identifier[trailer] . identifier[append] ( identifier[SURPASSED_PRINT_LENGTH] ) keyword[else] : identifier[items] = identifier[iterable] identifier[items] = identifier[list] ( identifier[map] ( keyword[lambda] identifier[o] : identifier[lrepr] ( identifier[o] ,** identifier[kwargs] ), identifier[items] )) identifier[seq_lrepr] = identifier[PRINT_SEPARATOR] . identifier[join] ( identifier[items] + identifier[trailer] ) identifier[print_meta] = identifier[kwargs] [ literal[string] ] keyword[if] identifier[print_meta] keyword[and] identifier[meta] : keyword[return] literal[string] keyword[return] literal[string]
def seq_lrepr(iterable: Iterable[Any], start: str, end: str, meta=None, **kwargs) -> str: """Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = kwargs['print_level'] if isinstance(print_level, int) and print_level < 1: return SURPASSED_PRINT_LEVEL # depends on [control=['if'], data=[]] kwargs = _process_kwargs(**kwargs) trailer = [] print_dup = kwargs['print_dup'] print_length = kwargs['print_length'] if not print_dup and isinstance(print_length, int): items = seq(iterable).take(print_length + 1).to_list() if len(items) > print_length: items.pop() trailer.append(SURPASSED_PRINT_LENGTH) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: items = iterable items = list(map(lambda o: lrepr(o, **kwargs), items)) seq_lrepr = PRINT_SEPARATOR.join(items + trailer) print_meta = kwargs['print_meta'] if print_meta and meta: return f'^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}' # depends on [control=['if'], data=[]] return f'{start}{seq_lrepr}{end}'
def get_compositions_by_repositories(self, repository_ids): """Gets the list of ``Compositions`` corresponding to a list of ``Repository`` objects. arg: repository_ids (osid.id.IdList): list of repository ``Ids`` return: (osid.repository.CompositionList) - list of Compositions raise: NullArgument - ``repository_ids`` 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.ResourceBinSession.get_resources_by_bins composition_list = [] for repository_id in repository_ids: composition_list += list( self.get_compositions_by_repository(repository_id)) return objects.CompositionList(composition_list)
def function[get_compositions_by_repositories, parameter[self, repository_ids]]: constant[Gets the list of ``Compositions`` corresponding to a list of ``Repository`` objects. arg: repository_ids (osid.id.IdList): list of repository ``Ids`` return: (osid.repository.CompositionList) - list of Compositions raise: NullArgument - ``repository_ids`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* ] variable[composition_list] assign[=] list[[]] for taget[name[repository_id]] in starred[name[repository_ids]] begin[:] <ast.AugAssign object at 0x7da1b0a66410> return[call[name[objects].CompositionList, parameter[name[composition_list]]]]
keyword[def] identifier[get_compositions_by_repositories] ( identifier[self] , identifier[repository_ids] ): literal[string] identifier[composition_list] =[] keyword[for] identifier[repository_id] keyword[in] identifier[repository_ids] : identifier[composition_list] += identifier[list] ( identifier[self] . identifier[get_compositions_by_repository] ( identifier[repository_id] )) keyword[return] identifier[objects] . identifier[CompositionList] ( identifier[composition_list] )
def get_compositions_by_repositories(self, repository_ids): """Gets the list of ``Compositions`` corresponding to a list of ``Repository`` objects. arg: repository_ids (osid.id.IdList): list of repository ``Ids`` return: (osid.repository.CompositionList) - list of Compositions raise: NullArgument - ``repository_ids`` 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.ResourceBinSession.get_resources_by_bins composition_list = [] for repository_id in repository_ids: composition_list += list(self.get_compositions_by_repository(repository_id)) # depends on [control=['for'], data=['repository_id']] return objects.CompositionList(composition_list)
def selector(self): """ Creates a selector expression of the offset. :rtype: bytes """ operator = ">=" if self.inclusive else ">" if isinstance(self.value, datetime.datetime): timestamp = (calendar.timegm(self.value.utctimetuple()) * 1000) + (self.value.microsecond/1000) return ("amqp.annotation.x-opt-enqueued-time {} '{}'".format(operator, int(timestamp))).encode('utf-8') if isinstance(self.value, six.integer_types): return ("amqp.annotation.x-opt-sequence-number {} '{}'".format(operator, self.value)).encode('utf-8') return ("amqp.annotation.x-opt-offset {} '{}'".format(operator, self.value)).encode('utf-8')
def function[selector, parameter[self]]: constant[ Creates a selector expression of the offset. :rtype: bytes ] variable[operator] assign[=] <ast.IfExp object at 0x7da204622590> if call[name[isinstance], parameter[name[self].value, name[datetime].datetime]] begin[:] variable[timestamp] assign[=] binary_operation[binary_operation[call[name[calendar].timegm, parameter[call[name[self].value.utctimetuple, parameter[]]]] * constant[1000]] + binary_operation[name[self].value.microsecond / constant[1000]]] return[call[call[constant[amqp.annotation.x-opt-enqueued-time {} '{}'].format, parameter[name[operator], call[name[int], parameter[name[timestamp]]]]].encode, parameter[constant[utf-8]]]] if call[name[isinstance], parameter[name[self].value, name[six].integer_types]] begin[:] return[call[call[constant[amqp.annotation.x-opt-sequence-number {} '{}'].format, parameter[name[operator], name[self].value]].encode, parameter[constant[utf-8]]]] return[call[call[constant[amqp.annotation.x-opt-offset {} '{}'].format, parameter[name[operator], name[self].value]].encode, parameter[constant[utf-8]]]]
keyword[def] identifier[selector] ( identifier[self] ): literal[string] identifier[operator] = literal[string] keyword[if] identifier[self] . identifier[inclusive] keyword[else] literal[string] keyword[if] identifier[isinstance] ( identifier[self] . identifier[value] , identifier[datetime] . identifier[datetime] ): identifier[timestamp] =( identifier[calendar] . identifier[timegm] ( identifier[self] . identifier[value] . identifier[utctimetuple] ())* literal[int] )+( identifier[self] . identifier[value] . identifier[microsecond] / literal[int] ) keyword[return] ( literal[string] . identifier[format] ( identifier[operator] , identifier[int] ( identifier[timestamp] ))). identifier[encode] ( literal[string] ) keyword[if] identifier[isinstance] ( identifier[self] . identifier[value] , identifier[six] . identifier[integer_types] ): keyword[return] ( literal[string] . identifier[format] ( identifier[operator] , identifier[self] . identifier[value] )). identifier[encode] ( literal[string] ) keyword[return] ( literal[string] . identifier[format] ( identifier[operator] , identifier[self] . identifier[value] )). identifier[encode] ( literal[string] )
def selector(self): """ Creates a selector expression of the offset. :rtype: bytes """ operator = '>=' if self.inclusive else '>' if isinstance(self.value, datetime.datetime): timestamp = calendar.timegm(self.value.utctimetuple()) * 1000 + self.value.microsecond / 1000 return "amqp.annotation.x-opt-enqueued-time {} '{}'".format(operator, int(timestamp)).encode('utf-8') # depends on [control=['if'], data=[]] if isinstance(self.value, six.integer_types): return "amqp.annotation.x-opt-sequence-number {} '{}'".format(operator, self.value).encode('utf-8') # depends on [control=['if'], data=[]] return "amqp.annotation.x-opt-offset {} '{}'".format(operator, self.value).encode('utf-8')
def output_latex(self, filename_or_file_handle): """ Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return: """ if isinstance(filename_or_file_handle, basestring): file_handle = file(filename_or_file_handle, 'w') we_opened = True else: file_handle = filename_or_file_handle we_opened = False try: file_handle.write(self.latex) finally: if we_opened: file_handle.close()
def function[output_latex, parameter[self, filename_or_file_handle]]: constant[ Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return: ] if call[name[isinstance], parameter[name[filename_or_file_handle], name[basestring]]] begin[:] variable[file_handle] assign[=] call[name[file], parameter[name[filename_or_file_handle], constant[w]]] variable[we_opened] assign[=] constant[True] <ast.Try object at 0x7da1b0917a60>
keyword[def] identifier[output_latex] ( identifier[self] , identifier[filename_or_file_handle] ): literal[string] keyword[if] identifier[isinstance] ( identifier[filename_or_file_handle] , identifier[basestring] ): identifier[file_handle] = identifier[file] ( identifier[filename_or_file_handle] , literal[string] ) identifier[we_opened] = keyword[True] keyword[else] : identifier[file_handle] = identifier[filename_or_file_handle] identifier[we_opened] = keyword[False] keyword[try] : identifier[file_handle] . identifier[write] ( identifier[self] . identifier[latex] ) keyword[finally] : keyword[if] identifier[we_opened] : identifier[file_handle] . identifier[close] ()
def output_latex(self, filename_or_file_handle): """ Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return: """ if isinstance(filename_or_file_handle, basestring): file_handle = file(filename_or_file_handle, 'w') we_opened = True # depends on [control=['if'], data=[]] else: file_handle = filename_or_file_handle we_opened = False try: file_handle.write(self.latex) # depends on [control=['try'], data=[]] finally: if we_opened: file_handle.close() # depends on [control=['if'], data=[]]
def get_col_width(self, col, tab): """Returns column width""" try: return self.col_widths[(col, tab)] except KeyError: return config["default_col_width"]
def function[get_col_width, parameter[self, col, tab]]: constant[Returns column width] <ast.Try object at 0x7da1b1615a80>
keyword[def] identifier[get_col_width] ( identifier[self] , identifier[col] , identifier[tab] ): literal[string] keyword[try] : keyword[return] identifier[self] . identifier[col_widths] [( identifier[col] , identifier[tab] )] keyword[except] identifier[KeyError] : keyword[return] identifier[config] [ literal[string] ]
def get_col_width(self, col, tab): """Returns column width""" try: return self.col_widths[col, tab] # depends on [control=['try'], data=[]] except KeyError: return config['default_col_width'] # depends on [control=['except'], data=[]]
def is_js_date_utc(json): """Check if the string contains Date.UTC function and return match group(s) if there is """ JS_date_utc_pattern = r'Date\.UTC\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\)' re_date = re.compile(JS_date_utc_pattern, re.M) if re_date.search(json): return re_date.search(json).group(0) else: return False
def function[is_js_date_utc, parameter[json]]: constant[Check if the string contains Date.UTC function and return match group(s) if there is ] variable[JS_date_utc_pattern] assign[=] constant[Date\.UTC\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\)] variable[re_date] assign[=] call[name[re].compile, parameter[name[JS_date_utc_pattern], name[re].M]] if call[name[re_date].search, parameter[name[json]]] begin[:] return[call[call[name[re_date].search, parameter[name[json]]].group, parameter[constant[0]]]]
keyword[def] identifier[is_js_date_utc] ( identifier[json] ): literal[string] identifier[JS_date_utc_pattern] = literal[string] identifier[re_date] = identifier[re] . identifier[compile] ( identifier[JS_date_utc_pattern] , identifier[re] . identifier[M] ) keyword[if] identifier[re_date] . identifier[search] ( identifier[json] ): keyword[return] identifier[re_date] . identifier[search] ( identifier[json] ). identifier[group] ( literal[int] ) keyword[else] : keyword[return] keyword[False]
def is_js_date_utc(json): """Check if the string contains Date.UTC function and return match group(s) if there is """ JS_date_utc_pattern = 'Date\\.UTC\\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\\)' re_date = re.compile(JS_date_utc_pattern, re.M) if re_date.search(json): return re_date.search(json).group(0) # depends on [control=['if'], data=[]] else: return False
def get_posts_with_limits(self, include_draft=False, **limits): """ Get all posts and filter them as needed. :param include_draft: return draft posts or not :param limits: other limits to the attrs of the result, should be a dict with string or list values :return: an iterable of Post objects """ filter_funcs = [] for attr in ('title', 'layout', 'author', 'email', 'tags', 'categories'): if limits.get(attr): filter_set = set(to_list(limits.get(attr))) def get_filter_func(filter_set_, attr_): return lambda p: filter_set_.intersection( to_list(getattr(p, attr_))) filter_funcs.append(get_filter_func(filter_set, attr)) for attr in ('created', 'updated'): interval = limits.get(attr) if isinstance(interval, (list, tuple)) and len(interval) == 2 \ and isinstance(interval[0], date) and isinstance( interval[1], date): # [start date(time), end date(time)] start, end = interval start = to_datetime(start) if not isinstance(end, datetime): # 'end' is a date, # we should convert it to 00:00:00 of the next day, # so that posts of that day will be included end = datetime.strptime( '%04d-%02d-%02d' % (end.year, end.month, end.day), '%Y-%m-%d') end += timedelta(days=1) def get_filter_func(attr_, start_dt, end_dt): return lambda p: start_dt <= getattr(p, attr_) < end_dt filter_funcs.append(get_filter_func(attr, start, end)) return self.get_posts(include_draft=include_draft, filter_functions=filter_funcs)
def function[get_posts_with_limits, parameter[self, include_draft]]: constant[ Get all posts and filter them as needed. :param include_draft: return draft posts or not :param limits: other limits to the attrs of the result, should be a dict with string or list values :return: an iterable of Post objects ] variable[filter_funcs] assign[=] list[[]] for taget[name[attr]] in starred[tuple[[<ast.Constant object at 0x7da18bcc83a0>, <ast.Constant object at 0x7da18bcc9ba0>, <ast.Constant object at 0x7da18bcc8a30>, <ast.Constant object at 0x7da18bcc81c0>, <ast.Constant object at 0x7da18bcc8280>, <ast.Constant object at 0x7da18bccb2e0>]]] begin[:] if call[name[limits].get, parameter[name[attr]]] begin[:] variable[filter_set] assign[=] call[name[set], parameter[call[name[to_list], parameter[call[name[limits].get, parameter[name[attr]]]]]]] def function[get_filter_func, parameter[filter_set_, attr_]]: return[<ast.Lambda object at 0x7da18dc059c0>] call[name[filter_funcs].append, parameter[call[name[get_filter_func], parameter[name[filter_set], name[attr]]]]] for taget[name[attr]] in starred[tuple[[<ast.Constant object at 0x7da2041d8370>, <ast.Constant object at 0x7da2041d9fc0>]]] begin[:] variable[interval] assign[=] call[name[limits].get, parameter[name[attr]]] if <ast.BoolOp object at 0x7da2041da530> begin[:] <ast.Tuple object at 0x7da2041da6e0> assign[=] name[interval] variable[start] assign[=] call[name[to_datetime], parameter[name[start]]] if <ast.UnaryOp object at 0x7da2041d97e0> begin[:] variable[end] assign[=] call[name[datetime].strptime, parameter[binary_operation[constant[%04d-%02d-%02d] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da2041da1d0>, <ast.Attribute object at 0x7da2041db490>, <ast.Attribute object at 0x7da2041db550>]]], constant[%Y-%m-%d]]] <ast.AugAssign object at 0x7da2041d9510> def function[get_filter_func, parameter[attr_, start_dt, end_dt]]: return[<ast.Lambda object at 0x7da2041d8190>] call[name[filter_funcs].append, parameter[call[name[get_filter_func], parameter[name[attr], name[start], name[end]]]]] return[call[name[self].get_posts, parameter[]]]
keyword[def] identifier[get_posts_with_limits] ( identifier[self] , identifier[include_draft] = keyword[False] ,** identifier[limits] ): literal[string] identifier[filter_funcs] =[] keyword[for] identifier[attr] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ): keyword[if] identifier[limits] . identifier[get] ( identifier[attr] ): identifier[filter_set] = identifier[set] ( identifier[to_list] ( identifier[limits] . identifier[get] ( identifier[attr] ))) keyword[def] identifier[get_filter_func] ( identifier[filter_set_] , identifier[attr_] ): keyword[return] keyword[lambda] identifier[p] : identifier[filter_set_] . identifier[intersection] ( identifier[to_list] ( identifier[getattr] ( identifier[p] , identifier[attr_] ))) identifier[filter_funcs] . identifier[append] ( identifier[get_filter_func] ( identifier[filter_set] , identifier[attr] )) keyword[for] identifier[attr] keyword[in] ( literal[string] , literal[string] ): identifier[interval] = identifier[limits] . identifier[get] ( identifier[attr] ) keyword[if] identifier[isinstance] ( identifier[interval] ,( identifier[list] , identifier[tuple] )) keyword[and] identifier[len] ( identifier[interval] )== literal[int] keyword[and] identifier[isinstance] ( identifier[interval] [ literal[int] ], identifier[date] ) keyword[and] identifier[isinstance] ( identifier[interval] [ literal[int] ], identifier[date] ): identifier[start] , identifier[end] = identifier[interval] identifier[start] = identifier[to_datetime] ( identifier[start] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[end] , identifier[datetime] ): identifier[end] = identifier[datetime] . identifier[strptime] ( literal[string] %( identifier[end] . identifier[year] , identifier[end] . identifier[month] , identifier[end] . identifier[day] ), literal[string] ) identifier[end] += identifier[timedelta] ( identifier[days] = literal[int] ) keyword[def] identifier[get_filter_func] ( identifier[attr_] , identifier[start_dt] , identifier[end_dt] ): keyword[return] keyword[lambda] identifier[p] : identifier[start_dt] <= identifier[getattr] ( identifier[p] , identifier[attr_] )< identifier[end_dt] identifier[filter_funcs] . identifier[append] ( identifier[get_filter_func] ( identifier[attr] , identifier[start] , identifier[end] )) keyword[return] identifier[self] . identifier[get_posts] ( identifier[include_draft] = identifier[include_draft] , identifier[filter_functions] = identifier[filter_funcs] )
def get_posts_with_limits(self, include_draft=False, **limits): """ Get all posts and filter them as needed. :param include_draft: return draft posts or not :param limits: other limits to the attrs of the result, should be a dict with string or list values :return: an iterable of Post objects """ filter_funcs = [] for attr in ('title', 'layout', 'author', 'email', 'tags', 'categories'): if limits.get(attr): filter_set = set(to_list(limits.get(attr))) def get_filter_func(filter_set_, attr_): return lambda p: filter_set_.intersection(to_list(getattr(p, attr_))) filter_funcs.append(get_filter_func(filter_set, attr)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['attr']] for attr in ('created', 'updated'): interval = limits.get(attr) if isinstance(interval, (list, tuple)) and len(interval) == 2 and isinstance(interval[0], date) and isinstance(interval[1], date): # [start date(time), end date(time)] (start, end) = interval start = to_datetime(start) if not isinstance(end, datetime): # 'end' is a date, # we should convert it to 00:00:00 of the next day, # so that posts of that day will be included end = datetime.strptime('%04d-%02d-%02d' % (end.year, end.month, end.day), '%Y-%m-%d') end += timedelta(days=1) # depends on [control=['if'], data=[]] def get_filter_func(attr_, start_dt, end_dt): return lambda p: start_dt <= getattr(p, attr_) < end_dt filter_funcs.append(get_filter_func(attr, start, end)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['attr']] return self.get_posts(include_draft=include_draft, filter_functions=filter_funcs)
def remover(self, id_egrupo): """Remove um grupo de equipamento a partir do seu identificador. :param id_egrupo: Identificador do grupo de equipamento. :return: None :raise GrupoEquipamentoNaoExisteError: Grupo de equipamento não cadastrado. :raise InvalidParameterError: O identificador do grupo é nulo ou inválido. :raise GroupDontRemoveError: :raise DataBaseError: Falha na networkapi ao acessar o banco de dados. :raise XMLError: Falha na networkapi ao gerar o XML de resposta. """ if not is_valid_int_param(id_egrupo): raise InvalidParameterError( u'O identificador do grupo de equipamento é inválido ou não foi informado.') url = 'egrupo/' + str(id_egrupo) + '/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
def function[remover, parameter[self, id_egrupo]]: constant[Remove um grupo de equipamento a partir do seu identificador. :param id_egrupo: Identificador do grupo de equipamento. :return: None :raise GrupoEquipamentoNaoExisteError: Grupo de equipamento não cadastrado. :raise InvalidParameterError: O identificador do grupo é nulo ou inválido. :raise GroupDontRemoveError: :raise DataBaseError: Falha na networkapi ao acessar o banco de dados. :raise XMLError: Falha na networkapi ao gerar o XML de resposta. ] if <ast.UnaryOp object at 0x7da20c7ca140> begin[:] <ast.Raise object at 0x7da20c7cbfa0> variable[url] assign[=] binary_operation[binary_operation[constant[egrupo/] + call[name[str], parameter[name[id_egrupo]]]] + constant[/]] <ast.Tuple object at 0x7da20c7c9150> assign[=] call[name[self].submit, parameter[constant[None], constant[DELETE], name[url]]] return[call[name[self].response, parameter[name[code], name[xml]]]]
keyword[def] identifier[remover] ( identifier[self] , identifier[id_egrupo] ): literal[string] keyword[if] keyword[not] identifier[is_valid_int_param] ( identifier[id_egrupo] ): keyword[raise] identifier[InvalidParameterError] ( literal[string] ) identifier[url] = literal[string] + identifier[str] ( identifier[id_egrupo] )+ literal[string] identifier[code] , identifier[xml] = identifier[self] . identifier[submit] ( keyword[None] , literal[string] , identifier[url] ) keyword[return] identifier[self] . identifier[response] ( identifier[code] , identifier[xml] )
def remover(self, id_egrupo): """Remove um grupo de equipamento a partir do seu identificador. :param id_egrupo: Identificador do grupo de equipamento. :return: None :raise GrupoEquipamentoNaoExisteError: Grupo de equipamento não cadastrado. :raise InvalidParameterError: O identificador do grupo é nulo ou inválido. :raise GroupDontRemoveError: :raise DataBaseError: Falha na networkapi ao acessar o banco de dados. :raise XMLError: Falha na networkapi ao gerar o XML de resposta. """ if not is_valid_int_param(id_egrupo): raise InvalidParameterError(u'O identificador do grupo de equipamento é inválido ou não foi informado.') # depends on [control=['if'], data=[]] url = 'egrupo/' + str(id_egrupo) + '/' (code, xml) = self.submit(None, 'DELETE', url) return self.response(code, xml)
def disassembler(co, lasti= -1): """Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. """ code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) i = 0 extended_arg = 0 lineno = 0 free = None for i, op, oparg in _walk_ops(co): if i in linestarts: lineno = linestarts[i] instr = Instruction(i=i, op=op, lineno=lineno) instr.linestart = i in linestarts if i == lasti: instr.lasti = True else: instr.lasti = False if i in labels: instr.label = True else: instr.label = False instr.oparg = oparg extended_arg = 0 if op == dis.EXTENDED_ARG: extended_arg = oparg * 65536 instr.extended_arg = extended_arg if op >= dis.HAVE_ARGUMENT: if op in dis.hasconst: instr.arg = co.co_consts[oparg] elif op in dis.hasname: instr.arg = co.co_names[oparg] elif op in dis.hasjrel: instr.arg = i + oparg elif op in dis.haslocal: instr.arg = co.co_varnames[oparg] elif op in dis.hascompare: instr.arg = dis.cmp_op[oparg] elif op in dis.hasfree: if free is None: free = co.co_cellvars + co.co_freevars instr.arg = free[oparg] yield instr
def function[disassembler, parameter[co, lasti]]: constant[Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. ] variable[code] assign[=] name[co].co_code variable[labels] assign[=] call[name[dis].findlabels, parameter[name[code]]] variable[linestarts] assign[=] call[name[dict], parameter[call[name[dis].findlinestarts, parameter[name[co]]]]] variable[i] assign[=] constant[0] variable[extended_arg] assign[=] constant[0] variable[lineno] assign[=] constant[0] variable[free] assign[=] constant[None] for taget[tuple[[<ast.Name object at 0x7da1b21ef490>, <ast.Name object at 0x7da1b21ed5d0>, <ast.Name object at 0x7da1b21ef9a0>]]] in starred[call[name[_walk_ops], parameter[name[co]]]] begin[:] if compare[name[i] in name[linestarts]] begin[:] variable[lineno] assign[=] call[name[linestarts]][name[i]] variable[instr] assign[=] call[name[Instruction], parameter[]] name[instr].linestart assign[=] compare[name[i] in name[linestarts]] if compare[name[i] equal[==] name[lasti]] begin[:] name[instr].lasti assign[=] constant[True] if compare[name[i] in name[labels]] begin[:] name[instr].label assign[=] constant[True] name[instr].oparg assign[=] name[oparg] variable[extended_arg] assign[=] constant[0] if compare[name[op] equal[==] name[dis].EXTENDED_ARG] begin[:] variable[extended_arg] assign[=] binary_operation[name[oparg] * constant[65536]] name[instr].extended_arg assign[=] name[extended_arg] if compare[name[op] greater_or_equal[>=] name[dis].HAVE_ARGUMENT] begin[:] if compare[name[op] in name[dis].hasconst] begin[:] name[instr].arg assign[=] call[name[co].co_consts][name[oparg]] <ast.Yield object at 0x7da1b2161de0>
keyword[def] identifier[disassembler] ( identifier[co] , identifier[lasti] =- literal[int] ): literal[string] identifier[code] = identifier[co] . identifier[co_code] identifier[labels] = identifier[dis] . identifier[findlabels] ( identifier[code] ) identifier[linestarts] = identifier[dict] ( identifier[dis] . identifier[findlinestarts] ( identifier[co] )) identifier[i] = literal[int] identifier[extended_arg] = literal[int] identifier[lineno] = literal[int] identifier[free] = keyword[None] keyword[for] identifier[i] , identifier[op] , identifier[oparg] keyword[in] identifier[_walk_ops] ( identifier[co] ): keyword[if] identifier[i] keyword[in] identifier[linestarts] : identifier[lineno] = identifier[linestarts] [ identifier[i] ] identifier[instr] = identifier[Instruction] ( identifier[i] = identifier[i] , identifier[op] = identifier[op] , identifier[lineno] = identifier[lineno] ) identifier[instr] . identifier[linestart] = identifier[i] keyword[in] identifier[linestarts] keyword[if] identifier[i] == identifier[lasti] : identifier[instr] . identifier[lasti] = keyword[True] keyword[else] : identifier[instr] . identifier[lasti] = keyword[False] keyword[if] identifier[i] keyword[in] identifier[labels] : identifier[instr] . identifier[label] = keyword[True] keyword[else] : identifier[instr] . identifier[label] = keyword[False] identifier[instr] . identifier[oparg] = identifier[oparg] identifier[extended_arg] = literal[int] keyword[if] identifier[op] == identifier[dis] . identifier[EXTENDED_ARG] : identifier[extended_arg] = identifier[oparg] * literal[int] identifier[instr] . identifier[extended_arg] = identifier[extended_arg] keyword[if] identifier[op] >= identifier[dis] . identifier[HAVE_ARGUMENT] : keyword[if] identifier[op] keyword[in] identifier[dis] . identifier[hasconst] : identifier[instr] . identifier[arg] = identifier[co] . identifier[co_consts] [ identifier[oparg] ] keyword[elif] identifier[op] keyword[in] identifier[dis] . identifier[hasname] : identifier[instr] . identifier[arg] = identifier[co] . identifier[co_names] [ identifier[oparg] ] keyword[elif] identifier[op] keyword[in] identifier[dis] . identifier[hasjrel] : identifier[instr] . identifier[arg] = identifier[i] + identifier[oparg] keyword[elif] identifier[op] keyword[in] identifier[dis] . identifier[haslocal] : identifier[instr] . identifier[arg] = identifier[co] . identifier[co_varnames] [ identifier[oparg] ] keyword[elif] identifier[op] keyword[in] identifier[dis] . identifier[hascompare] : identifier[instr] . identifier[arg] = identifier[dis] . identifier[cmp_op] [ identifier[oparg] ] keyword[elif] identifier[op] keyword[in] identifier[dis] . identifier[hasfree] : keyword[if] identifier[free] keyword[is] keyword[None] : identifier[free] = identifier[co] . identifier[co_cellvars] + identifier[co] . identifier[co_freevars] identifier[instr] . identifier[arg] = identifier[free] [ identifier[oparg] ] keyword[yield] identifier[instr]
def disassembler(co, lasti=-1): """Disassemble a code object. :param co: code object :param lasti: internal :yields: Instructions. """ code = co.co_code labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) i = 0 extended_arg = 0 lineno = 0 free = None for (i, op, oparg) in _walk_ops(co): if i in linestarts: lineno = linestarts[i] # depends on [control=['if'], data=['i', 'linestarts']] instr = Instruction(i=i, op=op, lineno=lineno) instr.linestart = i in linestarts if i == lasti: instr.lasti = True # depends on [control=['if'], data=[]] else: instr.lasti = False if i in labels: instr.label = True # depends on [control=['if'], data=[]] else: instr.label = False instr.oparg = oparg extended_arg = 0 if op == dis.EXTENDED_ARG: extended_arg = oparg * 65536 # depends on [control=['if'], data=[]] instr.extended_arg = extended_arg if op >= dis.HAVE_ARGUMENT: if op in dis.hasconst: instr.arg = co.co_consts[oparg] # depends on [control=['if'], data=[]] elif op in dis.hasname: instr.arg = co.co_names[oparg] # depends on [control=['if'], data=[]] elif op in dis.hasjrel: instr.arg = i + oparg # depends on [control=['if'], data=[]] elif op in dis.haslocal: instr.arg = co.co_varnames[oparg] # depends on [control=['if'], data=[]] elif op in dis.hascompare: instr.arg = dis.cmp_op[oparg] # depends on [control=['if'], data=[]] elif op in dis.hasfree: if free is None: free = co.co_cellvars + co.co_freevars # depends on [control=['if'], data=['free']] instr.arg = free[oparg] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['op']] yield instr # depends on [control=['for'], data=[]]
def ReadCronJobRun(self, job_id, run_id, cursor=None): """Reads a single cron job run from the db.""" query = ("SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs " "WHERE job_id = %s AND run_id = %s") num_runs = cursor.execute( query, [job_id, db_utils.CronJobRunIDToInt(run_id)]) if num_runs == 0: raise db.UnknownCronJobRunError( "Run with job id %s and run id %s not found." % (job_id, run_id)) return self._CronJobRunFromRow(cursor.fetchall()[0])
def function[ReadCronJobRun, parameter[self, job_id, run_id, cursor]]: constant[Reads a single cron job run from the db.] variable[query] assign[=] constant[SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs WHERE job_id = %s AND run_id = %s] variable[num_runs] assign[=] call[name[cursor].execute, parameter[name[query], list[[<ast.Name object at 0x7da1b1cc1c90>, <ast.Call object at 0x7da1b1cc1d20>]]]] if compare[name[num_runs] equal[==] constant[0]] begin[:] <ast.Raise object at 0x7da1b1cc0f70> return[call[name[self]._CronJobRunFromRow, parameter[call[call[name[cursor].fetchall, parameter[]]][constant[0]]]]]
keyword[def] identifier[ReadCronJobRun] ( identifier[self] , identifier[job_id] , identifier[run_id] , identifier[cursor] = keyword[None] ): literal[string] identifier[query] =( literal[string] literal[string] ) identifier[num_runs] = identifier[cursor] . identifier[execute] ( identifier[query] ,[ identifier[job_id] , identifier[db_utils] . identifier[CronJobRunIDToInt] ( identifier[run_id] )]) keyword[if] identifier[num_runs] == literal[int] : keyword[raise] identifier[db] . identifier[UnknownCronJobRunError] ( literal[string] %( identifier[job_id] , identifier[run_id] )) keyword[return] identifier[self] . identifier[_CronJobRunFromRow] ( identifier[cursor] . identifier[fetchall] ()[ literal[int] ])
def ReadCronJobRun(self, job_id, run_id, cursor=None): """Reads a single cron job run from the db.""" query = 'SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs WHERE job_id = %s AND run_id = %s' num_runs = cursor.execute(query, [job_id, db_utils.CronJobRunIDToInt(run_id)]) if num_runs == 0: raise db.UnknownCronJobRunError('Run with job id %s and run id %s not found.' % (job_id, run_id)) # depends on [control=['if'], data=[]] return self._CronJobRunFromRow(cursor.fetchall()[0])
def _api_all_views(self): """Glances API RESTful implementation. Return the JSON representation of all the plugins views HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error """ response.content_type = 'application/json; charset=utf-8' try: # Get the JSON value of the stat view limits = json.dumps(self.stats.getAllViewsAsDict()) except Exception as e: abort(404, "Cannot get views (%s)" % (str(e))) return limits
def function[_api_all_views, parameter[self]]: constant[Glances API RESTful implementation. Return the JSON representation of all the plugins views HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error ] name[response].content_type assign[=] constant[application/json; charset=utf-8] <ast.Try object at 0x7da1b21e0850> return[name[limits]]
keyword[def] identifier[_api_all_views] ( identifier[self] ): literal[string] identifier[response] . identifier[content_type] = literal[string] keyword[try] : identifier[limits] = identifier[json] . identifier[dumps] ( identifier[self] . identifier[stats] . identifier[getAllViewsAsDict] ()) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[abort] ( literal[int] , literal[string] %( identifier[str] ( identifier[e] ))) keyword[return] identifier[limits]
def _api_all_views(self): """Glances API RESTful implementation. Return the JSON representation of all the plugins views HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error """ response.content_type = 'application/json; charset=utf-8' try: # Get the JSON value of the stat view limits = json.dumps(self.stats.getAllViewsAsDict()) # depends on [control=['try'], data=[]] except Exception as e: abort(404, 'Cannot get views (%s)' % str(e)) # depends on [control=['except'], data=['e']] return limits
def validate_keys(self, *keys): """Validation helper to ensure that keys are present in data This method makes sure that all of keys received here are present in the data received from the caller. It is better to call this method in the `validate()` method of your event. Not in the `clean()` one, since the first will be called locally, making it easier to debug things and find problems. """ current_keys = set(self.data.keys()) needed_keys = set(keys) if not needed_keys.issubset(current_keys): raise ValidationError( 'One of the following keys are missing from the ' 'event\'s data: {}'.format( ', '.join(needed_keys.difference(current_keys))) ) return True
def function[validate_keys, parameter[self]]: constant[Validation helper to ensure that keys are present in data This method makes sure that all of keys received here are present in the data received from the caller. It is better to call this method in the `validate()` method of your event. Not in the `clean()` one, since the first will be called locally, making it easier to debug things and find problems. ] variable[current_keys] assign[=] call[name[set], parameter[call[name[self].data.keys, parameter[]]]] variable[needed_keys] assign[=] call[name[set], parameter[name[keys]]] if <ast.UnaryOp object at 0x7da1b27f6f20> begin[:] <ast.Raise object at 0x7da1b27f77f0> return[constant[True]]
keyword[def] identifier[validate_keys] ( identifier[self] ,* identifier[keys] ): literal[string] identifier[current_keys] = identifier[set] ( identifier[self] . identifier[data] . identifier[keys] ()) identifier[needed_keys] = identifier[set] ( identifier[keys] ) keyword[if] keyword[not] identifier[needed_keys] . identifier[issubset] ( identifier[current_keys] ): keyword[raise] identifier[ValidationError] ( literal[string] literal[string] . identifier[format] ( literal[string] . identifier[join] ( identifier[needed_keys] . identifier[difference] ( identifier[current_keys] ))) ) keyword[return] keyword[True]
def validate_keys(self, *keys): """Validation helper to ensure that keys are present in data This method makes sure that all of keys received here are present in the data received from the caller. It is better to call this method in the `validate()` method of your event. Not in the `clean()` one, since the first will be called locally, making it easier to debug things and find problems. """ current_keys = set(self.data.keys()) needed_keys = set(keys) if not needed_keys.issubset(current_keys): raise ValidationError("One of the following keys are missing from the event's data: {}".format(', '.join(needed_keys.difference(current_keys)))) # depends on [control=['if'], data=[]] return True
def save_gradebook_column(self, gradebook_column_form, *args, **kwargs): """Pass through to provider GradebookColumnAdminSession.update_gradebook_column""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if gradebook_column_form.is_for_update(): return self.update_gradebook_column(gradebook_column_form, *args, **kwargs) else: return self.create_gradebook_column(gradebook_column_form, *args, **kwargs)
def function[save_gradebook_column, parameter[self, gradebook_column_form]]: constant[Pass through to provider GradebookColumnAdminSession.update_gradebook_column] if call[name[gradebook_column_form].is_for_update, parameter[]] begin[:] return[call[name[self].update_gradebook_column, parameter[name[gradebook_column_form], <ast.Starred object at 0x7da20c7cbfd0>]]]
keyword[def] identifier[save_gradebook_column] ( identifier[self] , identifier[gradebook_column_form] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[gradebook_column_form] . identifier[is_for_update] (): keyword[return] identifier[self] . identifier[update_gradebook_column] ( identifier[gradebook_column_form] ,* identifier[args] ,** identifier[kwargs] ) keyword[else] : keyword[return] identifier[self] . identifier[create_gradebook_column] ( identifier[gradebook_column_form] ,* identifier[args] ,** identifier[kwargs] )
def save_gradebook_column(self, gradebook_column_form, *args, **kwargs): """Pass through to provider GradebookColumnAdminSession.update_gradebook_column""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if gradebook_column_form.is_for_update(): return self.update_gradebook_column(gradebook_column_form, *args, **kwargs) # depends on [control=['if'], data=[]] else: return self.create_gradebook_column(gradebook_column_form, *args, **kwargs)
def _tensor_proto_to_health_pill(self, tensor_event, node_name, device, output_slot): """Converts an event_accumulator.TensorEvent to a HealthPillEvent. Args: tensor_event: The event_accumulator.TensorEvent to convert. node_name: The name of the node (without the output slot). device: The device. output_slot: The integer output slot this health pill is relevant to. Returns: A HealthPillEvent. """ return self._process_health_pill_value( wall_time=tensor_event.wall_time, step=tensor_event.step, device_name=device, output_slot=output_slot, node_name=node_name, tensor_proto=tensor_event.tensor_proto)
def function[_tensor_proto_to_health_pill, parameter[self, tensor_event, node_name, device, output_slot]]: constant[Converts an event_accumulator.TensorEvent to a HealthPillEvent. Args: tensor_event: The event_accumulator.TensorEvent to convert. node_name: The name of the node (without the output slot). device: The device. output_slot: The integer output slot this health pill is relevant to. Returns: A HealthPillEvent. ] return[call[name[self]._process_health_pill_value, parameter[]]]
keyword[def] identifier[_tensor_proto_to_health_pill] ( identifier[self] , identifier[tensor_event] , identifier[node_name] , identifier[device] , identifier[output_slot] ): literal[string] keyword[return] identifier[self] . identifier[_process_health_pill_value] ( identifier[wall_time] = identifier[tensor_event] . identifier[wall_time] , identifier[step] = identifier[tensor_event] . identifier[step] , identifier[device_name] = identifier[device] , identifier[output_slot] = identifier[output_slot] , identifier[node_name] = identifier[node_name] , identifier[tensor_proto] = identifier[tensor_event] . identifier[tensor_proto] )
def _tensor_proto_to_health_pill(self, tensor_event, node_name, device, output_slot): """Converts an event_accumulator.TensorEvent to a HealthPillEvent. Args: tensor_event: The event_accumulator.TensorEvent to convert. node_name: The name of the node (without the output slot). device: The device. output_slot: The integer output slot this health pill is relevant to. Returns: A HealthPillEvent. """ return self._process_health_pill_value(wall_time=tensor_event.wall_time, step=tensor_event.step, device_name=device, output_slot=output_slot, node_name=node_name, tensor_proto=tensor_event.tensor_proto)
def get_par_css_dataframe(self): """ get a dataframe of composite scaled sensitivities. Includes both PEST-style and Hill-style. Returns ------- css : pandas.DataFrame """ assert self.jco is not None assert self.pst is not None jco = self.jco.to_dataframe() weights = self.pst.observation_data.loc[jco.index,"weight"].copy().values jco = (jco.T * weights).T dss_sum = jco.apply(np.linalg.norm) css = (dss_sum / float(self.pst.nnz_obs)).to_frame() css.columns = ["pest_css"] # log transform stuff self.pst.add_transform_columns() parval1 = self.pst.parameter_data.loc[dss_sum.index,"parval1_trans"].values css.loc[:,"hill_css"] = (dss_sum * parval1) / (float(self.pst.nnz_obs)**2) return css
def function[get_par_css_dataframe, parameter[self]]: constant[ get a dataframe of composite scaled sensitivities. Includes both PEST-style and Hill-style. Returns ------- css : pandas.DataFrame ] assert[compare[name[self].jco is_not constant[None]]] assert[compare[name[self].pst is_not constant[None]]] variable[jco] assign[=] call[name[self].jco.to_dataframe, parameter[]] variable[weights] assign[=] call[call[name[self].pst.observation_data.loc][tuple[[<ast.Attribute object at 0x7da1b1d45e10>, <ast.Constant object at 0x7da1b1d46620>]]].copy, parameter[]].values variable[jco] assign[=] binary_operation[name[jco].T * name[weights]].T variable[dss_sum] assign[=] call[name[jco].apply, parameter[name[np].linalg.norm]] variable[css] assign[=] call[binary_operation[name[dss_sum] / call[name[float], parameter[name[self].pst.nnz_obs]]].to_frame, parameter[]] name[css].columns assign[=] list[[<ast.Constant object at 0x7da1b1d44a90>]] call[name[self].pst.add_transform_columns, parameter[]] variable[parval1] assign[=] call[name[self].pst.parameter_data.loc][tuple[[<ast.Attribute object at 0x7da1b1d6c4c0>, <ast.Constant object at 0x7da1b1d6c1f0>]]].values call[name[css].loc][tuple[[<ast.Slice object at 0x7da1b1d6d900>, <ast.Constant object at 0x7da1b1d6dc30>]]] assign[=] binary_operation[binary_operation[name[dss_sum] * name[parval1]] / binary_operation[call[name[float], parameter[name[self].pst.nnz_obs]] ** constant[2]]] return[name[css]]
keyword[def] identifier[get_par_css_dataframe] ( identifier[self] ): literal[string] keyword[assert] identifier[self] . identifier[jco] keyword[is] keyword[not] keyword[None] keyword[assert] identifier[self] . identifier[pst] keyword[is] keyword[not] keyword[None] identifier[jco] = identifier[self] . identifier[jco] . identifier[to_dataframe] () identifier[weights] = identifier[self] . identifier[pst] . identifier[observation_data] . identifier[loc] [ identifier[jco] . identifier[index] , literal[string] ]. identifier[copy] (). identifier[values] identifier[jco] =( identifier[jco] . identifier[T] * identifier[weights] ). identifier[T] identifier[dss_sum] = identifier[jco] . identifier[apply] ( identifier[np] . identifier[linalg] . identifier[norm] ) identifier[css] =( identifier[dss_sum] / identifier[float] ( identifier[self] . identifier[pst] . identifier[nnz_obs] )). identifier[to_frame] () identifier[css] . identifier[columns] =[ literal[string] ] identifier[self] . identifier[pst] . identifier[add_transform_columns] () identifier[parval1] = identifier[self] . identifier[pst] . identifier[parameter_data] . identifier[loc] [ identifier[dss_sum] . identifier[index] , literal[string] ]. identifier[values] identifier[css] . identifier[loc] [:, literal[string] ]=( identifier[dss_sum] * identifier[parval1] )/( identifier[float] ( identifier[self] . identifier[pst] . identifier[nnz_obs] )** literal[int] ) keyword[return] identifier[css]
def get_par_css_dataframe(self): """ get a dataframe of composite scaled sensitivities. Includes both PEST-style and Hill-style. Returns ------- css : pandas.DataFrame """ assert self.jco is not None assert self.pst is not None jco = self.jco.to_dataframe() weights = self.pst.observation_data.loc[jco.index, 'weight'].copy().values jco = (jco.T * weights).T dss_sum = jco.apply(np.linalg.norm) css = (dss_sum / float(self.pst.nnz_obs)).to_frame() css.columns = ['pest_css'] # log transform stuff self.pst.add_transform_columns() parval1 = self.pst.parameter_data.loc[dss_sum.index, 'parval1_trans'].values css.loc[:, 'hill_css'] = dss_sum * parval1 / float(self.pst.nnz_obs) ** 2 return css
def to_bytes(self): r''' Create bytes from properties >>> message = EncapsulatedControlMessage(payload='Dummy') >>> message.to_bytes() '\x80\x00\x00\x00Dummy' ''' # Verify that properties make sense self.sanitize() # Start with the type bitstream = BitArray('uint:4=%d' % self.message_type) # Add the flags bitstream += BitArray('bool=%d, bool=%d' % (self.security, self.ddt_originated)) # Add padding bitstream += self._reserved1 # Determine payload payload = self.payload if hasattr(payload, 'to_bytes'): payload = payload.to_bytes() return bitstream.bytes + payload
def function[to_bytes, parameter[self]]: constant[ Create bytes from properties >>> message = EncapsulatedControlMessage(payload='Dummy') >>> message.to_bytes() '\x80\x00\x00\x00Dummy' ] call[name[self].sanitize, parameter[]] variable[bitstream] assign[=] call[name[BitArray], parameter[binary_operation[constant[uint:4=%d] <ast.Mod object at 0x7da2590d6920> name[self].message_type]]] <ast.AugAssign object at 0x7da1b09df0a0> <ast.AugAssign object at 0x7da1b09dfdc0> variable[payload] assign[=] name[self].payload if call[name[hasattr], parameter[name[payload], constant[to_bytes]]] begin[:] variable[payload] assign[=] call[name[payload].to_bytes, parameter[]] return[binary_operation[name[bitstream].bytes + name[payload]]]
keyword[def] identifier[to_bytes] ( identifier[self] ): literal[string] identifier[self] . identifier[sanitize] () identifier[bitstream] = identifier[BitArray] ( literal[string] % identifier[self] . identifier[message_type] ) identifier[bitstream] += identifier[BitArray] ( literal[string] %( identifier[self] . identifier[security] , identifier[self] . identifier[ddt_originated] )) identifier[bitstream] += identifier[self] . identifier[_reserved1] identifier[payload] = identifier[self] . identifier[payload] keyword[if] identifier[hasattr] ( identifier[payload] , literal[string] ): identifier[payload] = identifier[payload] . identifier[to_bytes] () keyword[return] identifier[bitstream] . identifier[bytes] + identifier[payload]
def to_bytes(self): """ Create bytes from properties >>> message = EncapsulatedControlMessage(payload='Dummy') >>> message.to_bytes() '\\x80\\x00\\x00\\x00Dummy' """ # Verify that properties make sense self.sanitize() # Start with the type bitstream = BitArray('uint:4=%d' % self.message_type) # Add the flags bitstream += BitArray('bool=%d, bool=%d' % (self.security, self.ddt_originated)) # Add padding bitstream += self._reserved1 # Determine payload payload = self.payload if hasattr(payload, 'to_bytes'): payload = payload.to_bytes() # depends on [control=['if'], data=[]] return bitstream.bytes + payload
def add_value(self, value, row, col): """ Adds a single value (cell) to a worksheet at (row, col). Return the (row, col) where the value has been put. :param value: Value to write to the sheet. :param row: Row where the value should be written. :param col: Column where the value should be written. """ self.__values[(row, col)] = value
def function[add_value, parameter[self, value, row, col]]: constant[ Adds a single value (cell) to a worksheet at (row, col). Return the (row, col) where the value has been put. :param value: Value to write to the sheet. :param row: Row where the value should be written. :param col: Column where the value should be written. ] call[name[self].__values][tuple[[<ast.Name object at 0x7da1b242b760>, <ast.Name object at 0x7da1b242b0d0>]]] assign[=] name[value]
keyword[def] identifier[add_value] ( identifier[self] , identifier[value] , identifier[row] , identifier[col] ): literal[string] identifier[self] . identifier[__values] [( identifier[row] , identifier[col] )]= identifier[value]
def add_value(self, value, row, col): """ Adds a single value (cell) to a worksheet at (row, col). Return the (row, col) where the value has been put. :param value: Value to write to the sheet. :param row: Row where the value should be written. :param col: Column where the value should be written. """ self.__values[row, col] = value
def get_set(self, fieldname): """Get all study items (e.g., geneids).""" set_items = set() for ntdata in self.nts: set_items |= getattr(ntdata, fieldname) return set_items
def function[get_set, parameter[self, fieldname]]: constant[Get all study items (e.g., geneids).] variable[set_items] assign[=] call[name[set], parameter[]] for taget[name[ntdata]] in starred[name[self].nts] begin[:] <ast.AugAssign object at 0x7da1b2345090> return[name[set_items]]
keyword[def] identifier[get_set] ( identifier[self] , identifier[fieldname] ): literal[string] identifier[set_items] = identifier[set] () keyword[for] identifier[ntdata] keyword[in] identifier[self] . identifier[nts] : identifier[set_items] |= identifier[getattr] ( identifier[ntdata] , identifier[fieldname] ) keyword[return] identifier[set_items]
def get_set(self, fieldname): """Get all study items (e.g., geneids).""" set_items = set() for ntdata in self.nts: set_items |= getattr(ntdata, fieldname) # depends on [control=['for'], data=['ntdata']] return set_items
def merge_requests(self, **kwargs): """List the merge requests related to this milestone. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): If set to False and no pagination option is defined, return a generator instead of a list **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabListError: If the list could not be retrieved Returns: RESTObjectList: The list of merge requests """ path = '%s/%s/merge_requests' % (self.manager.path, self.get_id()) data_list = self.manager.gitlab.http_list(path, as_list=False, **kwargs) manager = ProjectMergeRequestManager(self.manager.gitlab, parent=self.manager._parent) # FIXME(gpocentek): the computed manager path is not correct return RESTObjectList(manager, ProjectMergeRequest, data_list)
def function[merge_requests, parameter[self]]: constant[List the merge requests related to this milestone. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): If set to False and no pagination option is defined, return a generator instead of a list **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabListError: If the list could not be retrieved Returns: RESTObjectList: The list of merge requests ] variable[path] assign[=] binary_operation[constant[%s/%s/merge_requests] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da204345060>, <ast.Call object at 0x7da204345150>]]] variable[data_list] assign[=] call[name[self].manager.gitlab.http_list, parameter[name[path]]] variable[manager] assign[=] call[name[ProjectMergeRequestManager], parameter[name[self].manager.gitlab]] return[call[name[RESTObjectList], parameter[name[manager], name[ProjectMergeRequest], name[data_list]]]]
keyword[def] identifier[merge_requests] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[path] = literal[string] %( identifier[self] . identifier[manager] . identifier[path] , identifier[self] . identifier[get_id] ()) identifier[data_list] = identifier[self] . identifier[manager] . identifier[gitlab] . identifier[http_list] ( identifier[path] , identifier[as_list] = keyword[False] , ** identifier[kwargs] ) identifier[manager] = identifier[ProjectMergeRequestManager] ( identifier[self] . identifier[manager] . identifier[gitlab] , identifier[parent] = identifier[self] . identifier[manager] . identifier[_parent] ) keyword[return] identifier[RESTObjectList] ( identifier[manager] , identifier[ProjectMergeRequest] , identifier[data_list] )
def merge_requests(self, **kwargs): """List the merge requests related to this milestone. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): If set to False and no pagination option is defined, return a generator instead of a list **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabListError: If the list could not be retrieved Returns: RESTObjectList: The list of merge requests """ path = '%s/%s/merge_requests' % (self.manager.path, self.get_id()) data_list = self.manager.gitlab.http_list(path, as_list=False, **kwargs) manager = ProjectMergeRequestManager(self.manager.gitlab, parent=self.manager._parent) # FIXME(gpocentek): the computed manager path is not correct return RESTObjectList(manager, ProjectMergeRequest, data_list)
def systemInformationType16(): """SYSTEM INFORMATION TYPE 16 Section 9.1.43d""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x3d) # 00111101 d = Si16RestOctets() packet = a / b / c / d return packet
def function[systemInformationType16, parameter[]]: constant[SYSTEM INFORMATION TYPE 16 Section 9.1.43d] variable[a] assign[=] call[name[L2PseudoLength], parameter[]] variable[b] assign[=] call[name[TpPd], parameter[]] variable[c] assign[=] call[name[MessageType], parameter[]] variable[d] assign[=] call[name[Si16RestOctets], parameter[]] variable[packet] assign[=] binary_operation[binary_operation[binary_operation[name[a] / name[b]] / name[c]] / name[d]] return[name[packet]]
keyword[def] identifier[systemInformationType16] (): literal[string] identifier[a] = identifier[L2PseudoLength] ( identifier[l2pLength] = literal[int] ) identifier[b] = identifier[TpPd] ( identifier[pd] = literal[int] ) identifier[c] = identifier[MessageType] ( identifier[mesType] = literal[int] ) identifier[d] = identifier[Si16RestOctets] () identifier[packet] = identifier[a] / identifier[b] / identifier[c] / identifier[d] keyword[return] identifier[packet]
def systemInformationType16(): """SYSTEM INFORMATION TYPE 16 Section 9.1.43d""" a = L2PseudoLength(l2pLength=1) b = TpPd(pd=6) c = MessageType(mesType=61) # 00111101 d = Si16RestOctets() packet = a / b / c / d return packet
def set_range(self, accel=1, gyro=1): """Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range( accel=MPU6050I2C.RANGE_ACCEL_2G, gyro=MPU6050I2C.RANGE_GYRO_250DEG ) """ self.i2c_write_register(0x1c, accel) self.i2c_write_register(0x1b, gyro) self.accel_range = accel self.gyro_range = gyro
def function[set_range, parameter[self, accel, gyro]]: constant[Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range( accel=MPU6050I2C.RANGE_ACCEL_2G, gyro=MPU6050I2C.RANGE_GYRO_250DEG ) ] call[name[self].i2c_write_register, parameter[constant[28], name[accel]]] call[name[self].i2c_write_register, parameter[constant[27], name[gyro]]] name[self].accel_range assign[=] name[accel] name[self].gyro_range assign[=] name[gyro]
keyword[def] identifier[set_range] ( identifier[self] , identifier[accel] = literal[int] , identifier[gyro] = literal[int] ): literal[string] identifier[self] . identifier[i2c_write_register] ( literal[int] , identifier[accel] ) identifier[self] . identifier[i2c_write_register] ( literal[int] , identifier[gyro] ) identifier[self] . identifier[accel_range] = identifier[accel] identifier[self] . identifier[gyro_range] = identifier[gyro]
def set_range(self, accel=1, gyro=1): """Set the measurement range for the accel and gyro MEMS. Higher range means less resolution. :param accel: a RANGE_ACCEL_* constant :param gyro: a RANGE_GYRO_* constant :Example: .. code-block:: python sensor = MPU6050I2C(gateway_class_instance) sensor.set_range( accel=MPU6050I2C.RANGE_ACCEL_2G, gyro=MPU6050I2C.RANGE_GYRO_250DEG ) """ self.i2c_write_register(28, accel) self.i2c_write_register(27, gyro) self.accel_range = accel self.gyro_range = gyro
def stop_loss(self, accountID, **kwargs): """ Shortcut to create a Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopLossOrderRequest Returns: v20.response.Response containing the results from submitting the request """ return self.create( accountID, order=StopLossOrderRequest(**kwargs) )
def function[stop_loss, parameter[self, accountID]]: constant[ Shortcut to create a Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopLossOrderRequest Returns: v20.response.Response containing the results from submitting the request ] return[call[name[self].create, parameter[name[accountID]]]]
keyword[def] identifier[stop_loss] ( identifier[self] , identifier[accountID] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[self] . identifier[create] ( identifier[accountID] , identifier[order] = identifier[StopLossOrderRequest] (** identifier[kwargs] ) )
def stop_loss(self, accountID, **kwargs): """ Shortcut to create a Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopLossOrderRequest Returns: v20.response.Response containing the results from submitting the request """ return self.create(accountID, order=StopLossOrderRequest(**kwargs))
def group_cache_valid(self, col_list): """ Checks whether the column has a factorization that exists and is not older than the source :param col: :return: """ cache_valid = False if self.rootdir: col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + \ '.values/__attrs__' exists_group_index = os.path.exists(col_values_file_check) missing_col_check = [1 for col in col_list if not os.path.exists(self[col].rootdir + '/__attrs__')] cache_valid = (exists_group_index and not missing_col_check) return cache_valid
def function[group_cache_valid, parameter[self, col_list]]: constant[ Checks whether the column has a factorization that exists and is not older than the source :param col: :return: ] variable[cache_valid] assign[=] constant[False] if name[self].rootdir begin[:] variable[col_values_file_check] assign[=] binary_operation[call[name[os].path.join, parameter[name[self].rootdir, call[name[self].create_group_base_name, parameter[name[col_list]]]]] + constant[.values/__attrs__]] variable[exists_group_index] assign[=] call[name[os].path.exists, parameter[name[col_values_file_check]]] variable[missing_col_check] assign[=] <ast.ListComp object at 0x7da1b196dde0> variable[cache_valid] assign[=] <ast.BoolOp object at 0x7da1b198ca90> return[name[cache_valid]]
keyword[def] identifier[group_cache_valid] ( identifier[self] , identifier[col_list] ): literal[string] identifier[cache_valid] = keyword[False] keyword[if] identifier[self] . identifier[rootdir] : identifier[col_values_file_check] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[rootdir] , identifier[self] . identifier[create_group_base_name] ( identifier[col_list] ))+ literal[string] identifier[exists_group_index] = identifier[os] . identifier[path] . identifier[exists] ( identifier[col_values_file_check] ) identifier[missing_col_check] =[ literal[int] keyword[for] identifier[col] keyword[in] identifier[col_list] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] [ identifier[col] ]. identifier[rootdir] + literal[string] )] identifier[cache_valid] =( identifier[exists_group_index] keyword[and] keyword[not] identifier[missing_col_check] ) keyword[return] identifier[cache_valid]
def group_cache_valid(self, col_list): """ Checks whether the column has a factorization that exists and is not older than the source :param col: :return: """ cache_valid = False if self.rootdir: col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + '.values/__attrs__' exists_group_index = os.path.exists(col_values_file_check) missing_col_check = [1 for col in col_list if not os.path.exists(self[col].rootdir + '/__attrs__')] cache_valid = exists_group_index and (not missing_col_check) # depends on [control=['if'], data=[]] return cache_valid
def set_env_vars(init_run=None, n_runs=None, lab_path=None, dir_path=None, reproduce=None): """Construct the environment variables used by payu for resubmissions.""" payu_env_vars = {} # Setup Python dynamic library link lib_paths = sysconfig.get_config_vars('LIBDIR') payu_env_vars['LD_LIBRARY_PATH'] = ':'.join(lib_paths) if 'PYTHONPATH' in os.environ: payu_env_vars['PYTHONPATH'] = os.environ['PYTHONPATH'] # Set (or import) the path to the PAYU scripts (PAYU_PATH) # NOTE: We may be able to use sys.path[0] here. payu_binpath = os.environ.get('PAYU_PATH') if not payu_binpath or not os.path.isdir(payu_binpath): payu_binpath = os.path.dirname(sys.argv[0]) payu_env_vars['PAYU_PATH'] = payu_binpath # Set the run counters if init_run: init_run = int(init_run) assert init_run >= 0 payu_env_vars['PAYU_CURRENT_RUN'] = init_run if n_runs: n_runs = int(n_runs) assert n_runs > 0 payu_env_vars['PAYU_N_RUNS'] = n_runs # Import explicit project paths if lab_path: payu_env_vars['PAYU_LAB_PATH'] = os.path.normpath(lab_path) if dir_path: payu_env_vars['PAYU_DIR_PATH'] = os.path.normpath(dir_path) if reproduce: payu_env_vars['PAYU_REPRODUCE'] = reproduce return payu_env_vars
def function[set_env_vars, parameter[init_run, n_runs, lab_path, dir_path, reproduce]]: constant[Construct the environment variables used by payu for resubmissions.] variable[payu_env_vars] assign[=] dictionary[[], []] variable[lib_paths] assign[=] call[name[sysconfig].get_config_vars, parameter[constant[LIBDIR]]] call[name[payu_env_vars]][constant[LD_LIBRARY_PATH]] assign[=] call[constant[:].join, parameter[name[lib_paths]]] if compare[constant[PYTHONPATH] in name[os].environ] begin[:] call[name[payu_env_vars]][constant[PYTHONPATH]] assign[=] call[name[os].environ][constant[PYTHONPATH]] variable[payu_binpath] assign[=] call[name[os].environ.get, parameter[constant[PAYU_PATH]]] if <ast.BoolOp object at 0x7da1b02d9450> begin[:] variable[payu_binpath] assign[=] call[name[os].path.dirname, parameter[call[name[sys].argv][constant[0]]]] call[name[payu_env_vars]][constant[PAYU_PATH]] assign[=] name[payu_binpath] if name[init_run] begin[:] variable[init_run] assign[=] call[name[int], parameter[name[init_run]]] assert[compare[name[init_run] greater_or_equal[>=] constant[0]]] call[name[payu_env_vars]][constant[PAYU_CURRENT_RUN]] assign[=] name[init_run] if name[n_runs] begin[:] variable[n_runs] assign[=] call[name[int], parameter[name[n_runs]]] assert[compare[name[n_runs] greater[>] constant[0]]] call[name[payu_env_vars]][constant[PAYU_N_RUNS]] assign[=] name[n_runs] if name[lab_path] begin[:] call[name[payu_env_vars]][constant[PAYU_LAB_PATH]] assign[=] call[name[os].path.normpath, parameter[name[lab_path]]] if name[dir_path] begin[:] call[name[payu_env_vars]][constant[PAYU_DIR_PATH]] assign[=] call[name[os].path.normpath, parameter[name[dir_path]]] if name[reproduce] begin[:] call[name[payu_env_vars]][constant[PAYU_REPRODUCE]] assign[=] name[reproduce] return[name[payu_env_vars]]
keyword[def] identifier[set_env_vars] ( identifier[init_run] = keyword[None] , identifier[n_runs] = keyword[None] , identifier[lab_path] = keyword[None] , identifier[dir_path] = keyword[None] , identifier[reproduce] = keyword[None] ): literal[string] identifier[payu_env_vars] ={} identifier[lib_paths] = identifier[sysconfig] . identifier[get_config_vars] ( literal[string] ) identifier[payu_env_vars] [ literal[string] ]= literal[string] . identifier[join] ( identifier[lib_paths] ) keyword[if] literal[string] keyword[in] identifier[os] . identifier[environ] : identifier[payu_env_vars] [ literal[string] ]= identifier[os] . identifier[environ] [ literal[string] ] identifier[payu_binpath] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[payu_binpath] keyword[or] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[payu_binpath] ): identifier[payu_binpath] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[sys] . identifier[argv] [ literal[int] ]) identifier[payu_env_vars] [ literal[string] ]= identifier[payu_binpath] keyword[if] identifier[init_run] : identifier[init_run] = identifier[int] ( identifier[init_run] ) keyword[assert] identifier[init_run] >= literal[int] identifier[payu_env_vars] [ literal[string] ]= identifier[init_run] keyword[if] identifier[n_runs] : identifier[n_runs] = identifier[int] ( identifier[n_runs] ) keyword[assert] identifier[n_runs] > literal[int] identifier[payu_env_vars] [ literal[string] ]= identifier[n_runs] keyword[if] identifier[lab_path] : identifier[payu_env_vars] [ literal[string] ]= identifier[os] . identifier[path] . identifier[normpath] ( identifier[lab_path] ) keyword[if] identifier[dir_path] : identifier[payu_env_vars] [ literal[string] ]= identifier[os] . identifier[path] . identifier[normpath] ( identifier[dir_path] ) keyword[if] identifier[reproduce] : identifier[payu_env_vars] [ literal[string] ]= identifier[reproduce] keyword[return] identifier[payu_env_vars]
def set_env_vars(init_run=None, n_runs=None, lab_path=None, dir_path=None, reproduce=None): """Construct the environment variables used by payu for resubmissions.""" payu_env_vars = {} # Setup Python dynamic library link lib_paths = sysconfig.get_config_vars('LIBDIR') payu_env_vars['LD_LIBRARY_PATH'] = ':'.join(lib_paths) if 'PYTHONPATH' in os.environ: payu_env_vars['PYTHONPATH'] = os.environ['PYTHONPATH'] # depends on [control=['if'], data=[]] # Set (or import) the path to the PAYU scripts (PAYU_PATH) # NOTE: We may be able to use sys.path[0] here. payu_binpath = os.environ.get('PAYU_PATH') if not payu_binpath or not os.path.isdir(payu_binpath): payu_binpath = os.path.dirname(sys.argv[0]) # depends on [control=['if'], data=[]] payu_env_vars['PAYU_PATH'] = payu_binpath # Set the run counters if init_run: init_run = int(init_run) assert init_run >= 0 payu_env_vars['PAYU_CURRENT_RUN'] = init_run # depends on [control=['if'], data=[]] if n_runs: n_runs = int(n_runs) assert n_runs > 0 payu_env_vars['PAYU_N_RUNS'] = n_runs # depends on [control=['if'], data=[]] # Import explicit project paths if lab_path: payu_env_vars['PAYU_LAB_PATH'] = os.path.normpath(lab_path) # depends on [control=['if'], data=[]] if dir_path: payu_env_vars['PAYU_DIR_PATH'] = os.path.normpath(dir_path) # depends on [control=['if'], data=[]] if reproduce: payu_env_vars['PAYU_REPRODUCE'] = reproduce # depends on [control=['if'], data=[]] return payu_env_vars
def _wait_for_status(linode_id, status=None, timeout=300, quiet=True): ''' Wait for a certain status from Linode. linode_id The ID of the Linode to wait on. Required. status The status to look for to update. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise, logs to info. ''' if status is None: status = _get_status_id_by_name('brand_new') status_desc_waiting = _get_status_descr_by_id(status) interval = 5 iterations = int(timeout / interval) for i in range(0, iterations): result = get_linode(kwargs={'linode_id': linode_id}) if result['STATUS'] == status: return True status_desc_result = _get_status_descr_by_id(result['STATUS']) time.sleep(interval) log.log( logging.INFO if not quiet else logging.DEBUG, 'Status for Linode %s is \'%s\', waiting for \'%s\'.', linode_id, status_desc_result, status_desc_waiting ) return False
def function[_wait_for_status, parameter[linode_id, status, timeout, quiet]]: constant[ Wait for a certain status from Linode. linode_id The ID of the Linode to wait on. Required. status The status to look for to update. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise, logs to info. ] if compare[name[status] is constant[None]] begin[:] variable[status] assign[=] call[name[_get_status_id_by_name], parameter[constant[brand_new]]] variable[status_desc_waiting] assign[=] call[name[_get_status_descr_by_id], parameter[name[status]]] variable[interval] assign[=] constant[5] variable[iterations] assign[=] call[name[int], parameter[binary_operation[name[timeout] / name[interval]]]] for taget[name[i]] in starred[call[name[range], parameter[constant[0], name[iterations]]]] begin[:] variable[result] assign[=] call[name[get_linode], parameter[]] if compare[call[name[result]][constant[STATUS]] equal[==] name[status]] begin[:] return[constant[True]] variable[status_desc_result] assign[=] call[name[_get_status_descr_by_id], parameter[call[name[result]][constant[STATUS]]]] call[name[time].sleep, parameter[name[interval]]] call[name[log].log, parameter[<ast.IfExp object at 0x7da1b2021300>, constant[Status for Linode %s is '%s', waiting for '%s'.], name[linode_id], name[status_desc_result], name[status_desc_waiting]]] return[constant[False]]
keyword[def] identifier[_wait_for_status] ( identifier[linode_id] , identifier[status] = keyword[None] , identifier[timeout] = literal[int] , identifier[quiet] = keyword[True] ): literal[string] keyword[if] identifier[status] keyword[is] keyword[None] : identifier[status] = identifier[_get_status_id_by_name] ( literal[string] ) identifier[status_desc_waiting] = identifier[_get_status_descr_by_id] ( identifier[status] ) identifier[interval] = literal[int] identifier[iterations] = identifier[int] ( identifier[timeout] / identifier[interval] ) keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[iterations] ): identifier[result] = identifier[get_linode] ( identifier[kwargs] ={ literal[string] : identifier[linode_id] }) keyword[if] identifier[result] [ literal[string] ]== identifier[status] : keyword[return] keyword[True] identifier[status_desc_result] = identifier[_get_status_descr_by_id] ( identifier[result] [ literal[string] ]) identifier[time] . identifier[sleep] ( identifier[interval] ) identifier[log] . identifier[log] ( identifier[logging] . identifier[INFO] keyword[if] keyword[not] identifier[quiet] keyword[else] identifier[logging] . identifier[DEBUG] , literal[string] , identifier[linode_id] , identifier[status_desc_result] , identifier[status_desc_waiting] ) keyword[return] keyword[False]
def _wait_for_status(linode_id, status=None, timeout=300, quiet=True): """ Wait for a certain status from Linode. linode_id The ID of the Linode to wait on. Required. status The status to look for to update. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise, logs to info. """ if status is None: status = _get_status_id_by_name('brand_new') # depends on [control=['if'], data=['status']] status_desc_waiting = _get_status_descr_by_id(status) interval = 5 iterations = int(timeout / interval) for i in range(0, iterations): result = get_linode(kwargs={'linode_id': linode_id}) if result['STATUS'] == status: return True # depends on [control=['if'], data=[]] status_desc_result = _get_status_descr_by_id(result['STATUS']) time.sleep(interval) log.log(logging.INFO if not quiet else logging.DEBUG, "Status for Linode %s is '%s', waiting for '%s'.", linode_id, status_desc_result, status_desc_waiting) # depends on [control=['for'], data=[]] return False
def time_context_from_dct(dct): """Return a time context object given a DCT entry.""" time_text = dct.get('text') start = _get_time_stamp(dct.get('start')) end = _get_time_stamp(dct.get('end')) duration = dct.get('duration') tc = TimeContext(text=time_text, start=start, end=end, duration=duration) return tc
def function[time_context_from_dct, parameter[dct]]: constant[Return a time context object given a DCT entry.] variable[time_text] assign[=] call[name[dct].get, parameter[constant[text]]] variable[start] assign[=] call[name[_get_time_stamp], parameter[call[name[dct].get, parameter[constant[start]]]]] variable[end] assign[=] call[name[_get_time_stamp], parameter[call[name[dct].get, parameter[constant[end]]]]] variable[duration] assign[=] call[name[dct].get, parameter[constant[duration]]] variable[tc] assign[=] call[name[TimeContext], parameter[]] return[name[tc]]
keyword[def] identifier[time_context_from_dct] ( identifier[dct] ): literal[string] identifier[time_text] = identifier[dct] . identifier[get] ( literal[string] ) identifier[start] = identifier[_get_time_stamp] ( identifier[dct] . identifier[get] ( literal[string] )) identifier[end] = identifier[_get_time_stamp] ( identifier[dct] . identifier[get] ( literal[string] )) identifier[duration] = identifier[dct] . identifier[get] ( literal[string] ) identifier[tc] = identifier[TimeContext] ( identifier[text] = identifier[time_text] , identifier[start] = identifier[start] , identifier[end] = identifier[end] , identifier[duration] = identifier[duration] ) keyword[return] identifier[tc]
def time_context_from_dct(dct): """Return a time context object given a DCT entry.""" time_text = dct.get('text') start = _get_time_stamp(dct.get('start')) end = _get_time_stamp(dct.get('end')) duration = dct.get('duration') tc = TimeContext(text=time_text, start=start, end=end, duration=duration) return tc
def subst_favorite_query_args(query, args): """replace positional parameters ($1...$N) in query.""" for idx, val in enumerate(args): subst_var = '$' + str(idx + 1) if subst_var not in query: return [None, 'query does not have substitution parameter ' + subst_var + ':\n ' + query] query = query.replace(subst_var, val) match = re.search('\\$\d+', query) if match: return[None, 'missing substitution for ' + match.group(0) + ' in query:\n ' + query] return [query, None]
def function[subst_favorite_query_args, parameter[query, args]]: constant[replace positional parameters ($1...$N) in query.] for taget[tuple[[<ast.Name object at 0x7da18fe92b00>, <ast.Name object at 0x7da18fe900a0>]]] in starred[call[name[enumerate], parameter[name[args]]]] begin[:] variable[subst_var] assign[=] binary_operation[constant[$] + call[name[str], parameter[binary_operation[name[idx] + constant[1]]]]] if compare[name[subst_var] <ast.NotIn object at 0x7da2590d7190> name[query]] begin[:] return[list[[<ast.Constant object at 0x7da18fe92530>, <ast.BinOp object at 0x7da18fe91f90>]]] variable[query] assign[=] call[name[query].replace, parameter[name[subst_var], name[val]]] variable[match] assign[=] call[name[re].search, parameter[constant[\$\d+], name[query]]] if name[match] begin[:] return[list[[<ast.Constant object at 0x7da2041da110>, <ast.BinOp object at 0x7da2041d85e0>]]] return[list[[<ast.Name object at 0x7da2041d8760>, <ast.Constant object at 0x7da2041d8100>]]]
keyword[def] identifier[subst_favorite_query_args] ( identifier[query] , identifier[args] ): literal[string] keyword[for] identifier[idx] , identifier[val] keyword[in] identifier[enumerate] ( identifier[args] ): identifier[subst_var] = literal[string] + identifier[str] ( identifier[idx] + literal[int] ) keyword[if] identifier[subst_var] keyword[not] keyword[in] identifier[query] : keyword[return] [ keyword[None] , literal[string] + identifier[subst_var] + literal[string] + identifier[query] ] identifier[query] = identifier[query] . identifier[replace] ( identifier[subst_var] , identifier[val] ) identifier[match] = identifier[re] . identifier[search] ( literal[string] , identifier[query] ) keyword[if] identifier[match] : keyword[return] [ keyword[None] , literal[string] + identifier[match] . identifier[group] ( literal[int] )+ literal[string] + identifier[query] ] keyword[return] [ identifier[query] , keyword[None] ]
def subst_favorite_query_args(query, args): """replace positional parameters ($1...$N) in query.""" for (idx, val) in enumerate(args): subst_var = '$' + str(idx + 1) if subst_var not in query: return [None, 'query does not have substitution parameter ' + subst_var + ':\n ' + query] # depends on [control=['if'], data=['subst_var', 'query']] query = query.replace(subst_var, val) # depends on [control=['for'], data=[]] match = re.search('\\$\\d+', query) if match: return [None, 'missing substitution for ' + match.group(0) + ' in query:\n ' + query] # depends on [control=['if'], data=[]] return [query, None]
def _read_module_definitions(self, graph): """ Read graph and add module defintions to document """ for e in self._get_elements(graph, SBOL.ModuleDefinition): identity = e[0] m = self._get_rdf_identified(graph, identity) m['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) functional_components = {} for func_comp in graph.triples((identity, SBOL.functionalComponent, None)): func_identity = func_comp[2] fc = self._get_rdf_identified(graph, func_identity) definition = self._get_triplet_value(graph, func_identity, SBOL.definition) fc['definition'] = self._components[definition] fc['access'] = self._get_triplet_value(graph, func_identity, SBOL.access) fc['direction'] = self._get_triplet_value(graph, func_identity, SBOL.direction) functional_components[func_identity.toPython()] = FunctionalComponent(**fc) self._functional_component_store[func_identity.toPython()] = \ functional_components[func_identity.toPython()] interactions = [] for inter in graph.triples((identity, SBOL.interaction, None)): inter_identity = inter[2] it = self._get_rdf_identified(graph, inter_identity) it['types'] = self._get_triplet_value_list(graph, inter_identity, SBOL.types) participations = [] for p in graph.triples((inter_identity, SBOL.participation, None)): pc = self._get_rdf_identified(graph, p[2]) roles = self._get_triplet_value_list(graph, p[2], SBOL.role) # Need to use one of the functional component created above participant_id = self._get_triplet_value(graph, p[2], SBOL.participant) participant = functional_components[participant_id] participations.append(Participation(roles=roles, participant=participant, **pc)) interactions.append(Interaction(participations=participations, **it)) obj = ModuleDefinition(functional_components=functional_components.values(), interactions=interactions, **m) self._modules[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
def function[_read_module_definitions, parameter[self, graph]]: constant[ Read graph and add module defintions to document ] for taget[name[e]] in starred[call[name[self]._get_elements, parameter[name[graph], name[SBOL].ModuleDefinition]]] begin[:] variable[identity] assign[=] call[name[e]][constant[0]] variable[m] assign[=] call[name[self]._get_rdf_identified, parameter[name[graph], name[identity]]] call[name[m]][constant[roles]] assign[=] call[name[self]._get_triplet_value_list, parameter[name[graph], name[identity], name[SBOL].role]] variable[functional_components] assign[=] dictionary[[], []] for taget[name[func_comp]] in starred[call[name[graph].triples, parameter[tuple[[<ast.Name object at 0x7da20e797e80>, <ast.Attribute object at 0x7da18fe905b0>, <ast.Constant object at 0x7da18fe930d0>]]]]] begin[:] variable[func_identity] assign[=] call[name[func_comp]][constant[2]] variable[fc] assign[=] call[name[self]._get_rdf_identified, parameter[name[graph], name[func_identity]]] variable[definition] assign[=] call[name[self]._get_triplet_value, parameter[name[graph], name[func_identity], name[SBOL].definition]] call[name[fc]][constant[definition]] assign[=] call[name[self]._components][name[definition]] call[name[fc]][constant[access]] assign[=] call[name[self]._get_triplet_value, parameter[name[graph], name[func_identity], name[SBOL].access]] call[name[fc]][constant[direction]] assign[=] call[name[self]._get_triplet_value, parameter[name[graph], name[func_identity], name[SBOL].direction]] call[name[functional_components]][call[name[func_identity].toPython, parameter[]]] assign[=] call[name[FunctionalComponent], parameter[]] call[name[self]._functional_component_store][call[name[func_identity].toPython, parameter[]]] assign[=] call[name[functional_components]][call[name[func_identity].toPython, parameter[]]] variable[interactions] assign[=] list[[]] for taget[name[inter]] in starred[call[name[graph].triples, parameter[tuple[[<ast.Name object at 0x7da20c992f80>, <ast.Attribute object at 0x7da20c992470>, <ast.Constant object at 0x7da20c990190>]]]]] begin[:] variable[inter_identity] assign[=] call[name[inter]][constant[2]] variable[it] assign[=] call[name[self]._get_rdf_identified, parameter[name[graph], name[inter_identity]]] call[name[it]][constant[types]] assign[=] call[name[self]._get_triplet_value_list, parameter[name[graph], name[inter_identity], name[SBOL].types]] variable[participations] assign[=] list[[]] for taget[name[p]] in starred[call[name[graph].triples, parameter[tuple[[<ast.Name object at 0x7da20eb29cc0>, <ast.Attribute object at 0x7da20eb2bdf0>, <ast.Constant object at 0x7da20eb2a140>]]]]] begin[:] variable[pc] assign[=] call[name[self]._get_rdf_identified, parameter[name[graph], call[name[p]][constant[2]]]] variable[roles] assign[=] call[name[self]._get_triplet_value_list, parameter[name[graph], call[name[p]][constant[2]], name[SBOL].role]] variable[participant_id] assign[=] call[name[self]._get_triplet_value, parameter[name[graph], call[name[p]][constant[2]], name[SBOL].participant]] variable[participant] assign[=] call[name[functional_components]][name[participant_id]] call[name[participations].append, parameter[call[name[Participation], parameter[]]]] call[name[interactions].append, parameter[call[name[Interaction], parameter[]]]] variable[obj] assign[=] call[name[ModuleDefinition], parameter[]] call[name[self]._modules][call[name[identity].toPython, parameter[]]] assign[=] name[obj] call[name[self]._collection_store][call[name[identity].toPython, parameter[]]] assign[=] name[obj]
keyword[def] identifier[_read_module_definitions] ( identifier[self] , identifier[graph] ): literal[string] keyword[for] identifier[e] keyword[in] identifier[self] . identifier[_get_elements] ( identifier[graph] , identifier[SBOL] . identifier[ModuleDefinition] ): identifier[identity] = identifier[e] [ literal[int] ] identifier[m] = identifier[self] . identifier[_get_rdf_identified] ( identifier[graph] , identifier[identity] ) identifier[m] [ literal[string] ]= identifier[self] . identifier[_get_triplet_value_list] ( identifier[graph] , identifier[identity] , identifier[SBOL] . identifier[role] ) identifier[functional_components] ={} keyword[for] identifier[func_comp] keyword[in] identifier[graph] . identifier[triples] (( identifier[identity] , identifier[SBOL] . identifier[functionalComponent] , keyword[None] )): identifier[func_identity] = identifier[func_comp] [ literal[int] ] identifier[fc] = identifier[self] . identifier[_get_rdf_identified] ( identifier[graph] , identifier[func_identity] ) identifier[definition] = identifier[self] . identifier[_get_triplet_value] ( identifier[graph] , identifier[func_identity] , identifier[SBOL] . identifier[definition] ) identifier[fc] [ literal[string] ]= identifier[self] . identifier[_components] [ identifier[definition] ] identifier[fc] [ literal[string] ]= identifier[self] . identifier[_get_triplet_value] ( identifier[graph] , identifier[func_identity] , identifier[SBOL] . identifier[access] ) identifier[fc] [ literal[string] ]= identifier[self] . identifier[_get_triplet_value] ( identifier[graph] , identifier[func_identity] , identifier[SBOL] . identifier[direction] ) identifier[functional_components] [ identifier[func_identity] . identifier[toPython] ()]= identifier[FunctionalComponent] (** identifier[fc] ) identifier[self] . identifier[_functional_component_store] [ identifier[func_identity] . identifier[toPython] ()]= identifier[functional_components] [ identifier[func_identity] . identifier[toPython] ()] identifier[interactions] =[] keyword[for] identifier[inter] keyword[in] identifier[graph] . identifier[triples] (( identifier[identity] , identifier[SBOL] . identifier[interaction] , keyword[None] )): identifier[inter_identity] = identifier[inter] [ literal[int] ] identifier[it] = identifier[self] . identifier[_get_rdf_identified] ( identifier[graph] , identifier[inter_identity] ) identifier[it] [ literal[string] ]= identifier[self] . identifier[_get_triplet_value_list] ( identifier[graph] , identifier[inter_identity] , identifier[SBOL] . identifier[types] ) identifier[participations] =[] keyword[for] identifier[p] keyword[in] identifier[graph] . identifier[triples] (( identifier[inter_identity] , identifier[SBOL] . identifier[participation] , keyword[None] )): identifier[pc] = identifier[self] . identifier[_get_rdf_identified] ( identifier[graph] , identifier[p] [ literal[int] ]) identifier[roles] = identifier[self] . identifier[_get_triplet_value_list] ( identifier[graph] , identifier[p] [ literal[int] ], identifier[SBOL] . identifier[role] ) identifier[participant_id] = identifier[self] . identifier[_get_triplet_value] ( identifier[graph] , identifier[p] [ literal[int] ], identifier[SBOL] . identifier[participant] ) identifier[participant] = identifier[functional_components] [ identifier[participant_id] ] identifier[participations] . identifier[append] ( identifier[Participation] ( identifier[roles] = identifier[roles] , identifier[participant] = identifier[participant] ,** identifier[pc] )) identifier[interactions] . identifier[append] ( identifier[Interaction] ( identifier[participations] = identifier[participations] ,** identifier[it] )) identifier[obj] = identifier[ModuleDefinition] ( identifier[functional_components] = identifier[functional_components] . identifier[values] (), identifier[interactions] = identifier[interactions] , ** identifier[m] ) identifier[self] . identifier[_modules] [ identifier[identity] . identifier[toPython] ()]= identifier[obj] identifier[self] . identifier[_collection_store] [ identifier[identity] . identifier[toPython] ()]= identifier[obj]
def _read_module_definitions(self, graph): """ Read graph and add module defintions to document """ for e in self._get_elements(graph, SBOL.ModuleDefinition): identity = e[0] m = self._get_rdf_identified(graph, identity) m['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) functional_components = {} for func_comp in graph.triples((identity, SBOL.functionalComponent, None)): func_identity = func_comp[2] fc = self._get_rdf_identified(graph, func_identity) definition = self._get_triplet_value(graph, func_identity, SBOL.definition) fc['definition'] = self._components[definition] fc['access'] = self._get_triplet_value(graph, func_identity, SBOL.access) fc['direction'] = self._get_triplet_value(graph, func_identity, SBOL.direction) functional_components[func_identity.toPython()] = FunctionalComponent(**fc) self._functional_component_store[func_identity.toPython()] = functional_components[func_identity.toPython()] # depends on [control=['for'], data=['func_comp']] interactions = [] for inter in graph.triples((identity, SBOL.interaction, None)): inter_identity = inter[2] it = self._get_rdf_identified(graph, inter_identity) it['types'] = self._get_triplet_value_list(graph, inter_identity, SBOL.types) participations = [] for p in graph.triples((inter_identity, SBOL.participation, None)): pc = self._get_rdf_identified(graph, p[2]) roles = self._get_triplet_value_list(graph, p[2], SBOL.role) # Need to use one of the functional component created above participant_id = self._get_triplet_value(graph, p[2], SBOL.participant) participant = functional_components[participant_id] participations.append(Participation(roles=roles, participant=participant, **pc)) # depends on [control=['for'], data=['p']] interactions.append(Interaction(participations=participations, **it)) # depends on [control=['for'], data=['inter']] obj = ModuleDefinition(functional_components=functional_components.values(), interactions=interactions, **m) self._modules[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj # depends on [control=['for'], data=['e']]
def coroutine(func): """Basic decorator to implement the coroutine pattern.""" def __start(*args, **kwargs): """Automatically calls next() on the internal generator function.""" __cr = func(*args, **kwargs) next(__cr) return __cr return __start
def function[coroutine, parameter[func]]: constant[Basic decorator to implement the coroutine pattern.] def function[__start, parameter[]]: constant[Automatically calls next() on the internal generator function.] variable[__cr] assign[=] call[name[func], parameter[<ast.Starred object at 0x7da2049630a0>]] call[name[next], parameter[name[__cr]]] return[name[__cr]] return[name[__start]]
keyword[def] identifier[coroutine] ( identifier[func] ): literal[string] keyword[def] identifier[__start] (* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[__cr] = identifier[func] (* identifier[args] ,** identifier[kwargs] ) identifier[next] ( identifier[__cr] ) keyword[return] identifier[__cr] keyword[return] identifier[__start]
def coroutine(func): """Basic decorator to implement the coroutine pattern.""" def __start(*args, **kwargs): """Automatically calls next() on the internal generator function.""" __cr = func(*args, **kwargs) next(__cr) return __cr return __start
def parse_verilog_file(fname): '''Parse a named Verilog file Args: fname (str): File to parse. Returns: List of parsed objects. ''' with open(fname, 'rt') as fh: text = fh.read() return parse_verilog(text)
def function[parse_verilog_file, parameter[fname]]: constant[Parse a named Verilog file Args: fname (str): File to parse. Returns: List of parsed objects. ] with call[name[open], parameter[name[fname], constant[rt]]] begin[:] variable[text] assign[=] call[name[fh].read, parameter[]] return[call[name[parse_verilog], parameter[name[text]]]]
keyword[def] identifier[parse_verilog_file] ( identifier[fname] ): literal[string] keyword[with] identifier[open] ( identifier[fname] , literal[string] ) keyword[as] identifier[fh] : identifier[text] = identifier[fh] . identifier[read] () keyword[return] identifier[parse_verilog] ( identifier[text] )
def parse_verilog_file(fname): """Parse a named Verilog file Args: fname (str): File to parse. Returns: List of parsed objects. """ with open(fname, 'rt') as fh: text = fh.read() # depends on [control=['with'], data=['fh']] return parse_verilog(text)
def ed25519_public_key_to_string(key): """Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw, ), None).decode('utf-8')
def function[ed25519_public_key_to_string, parameter[key]]: constant[Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str ] return[call[call[name[base64].b64encode, parameter[call[name[key].public_bytes, parameter[]], constant[None]]].decode, parameter[constant[utf-8]]]]
keyword[def] identifier[ed25519_public_key_to_string] ( identifier[key] ): literal[string] keyword[return] identifier[base64] . identifier[b64encode] ( identifier[key] . identifier[public_bytes] ( identifier[encoding] = identifier[serialization] . identifier[Encoding] . identifier[Raw] , identifier[format] = identifier[serialization] . identifier[PublicFormat] . identifier[Raw] , ), keyword[None] ). identifier[decode] ( literal[string] )
def ed25519_public_key_to_string(key): """Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw), None).decode('utf-8')
def behave(cmdline, cwd=".", **kwargs): """ Run behave as subprocess command and return process/shell instance with results (collected output, returncode). """ assert isinstance(cmdline, six.string_types) return run("behave " + cmdline, cwd=cwd, **kwargs)
def function[behave, parameter[cmdline, cwd]]: constant[ Run behave as subprocess command and return process/shell instance with results (collected output, returncode). ] assert[call[name[isinstance], parameter[name[cmdline], name[six].string_types]]] return[call[name[run], parameter[binary_operation[constant[behave ] + name[cmdline]]]]]
keyword[def] identifier[behave] ( identifier[cmdline] , identifier[cwd] = literal[string] ,** identifier[kwargs] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[cmdline] , identifier[six] . identifier[string_types] ) keyword[return] identifier[run] ( literal[string] + identifier[cmdline] , identifier[cwd] = identifier[cwd] ,** identifier[kwargs] )
def behave(cmdline, cwd='.', **kwargs): """ Run behave as subprocess command and return process/shell instance with results (collected output, returncode). """ assert isinstance(cmdline, six.string_types) return run('behave ' + cmdline, cwd=cwd, **kwargs)
def on_connection_closed(self, _, reply_code, reply_text): """Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds: (%s) %s', reply_code, reply_text) self._connection.add_timeout(5, self.reconnect)
def function[on_connection_closed, parameter[self, _, reply_code, reply_text]]: constant[Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given ] name[self]._channel assign[=] constant[None] if name[self]._closing begin[:] call[name[self]._connection.ioloop.stop, parameter[]]
keyword[def] identifier[on_connection_closed] ( identifier[self] , identifier[_] , identifier[reply_code] , identifier[reply_text] ): literal[string] identifier[self] . identifier[_channel] = keyword[None] keyword[if] identifier[self] . identifier[_closing] : identifier[self] . identifier[_connection] . identifier[ioloop] . identifier[stop] () keyword[else] : identifier[logger] . identifier[warning] ( literal[string] , identifier[reply_code] , identifier[reply_text] ) identifier[self] . identifier[_connection] . identifier[add_timeout] ( literal[int] , identifier[self] . identifier[reconnect] )
def on_connection_closed(self, _, reply_code, reply_text): """Called by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection _: The closed connection object :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() # depends on [control=['if'], data=[]] else: logger.warning('Connection closed, reopening in 5 seconds: (%s) %s', reply_code, reply_text) self._connection.add_timeout(5, self.reconnect)
def get_digest(self, alias=None, manifest=None, verify=True, dcd=None): """ (v2 schema only) Get the hash of an alias's configuration blob. For an alias created using ``dxf``, this is the hash of the first blob assigned to the alias. For a Docker image tag, this is the same as ``docker inspect alias --format='{{.Id}}'``. :param alias: Alias name. You almost definitely will only need to pass this argument. :type alias: str :param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to do this. :type manifest: str :param verify: (v1 schema only) Whether to verify the integrity of the alias definition in the registry itself. You almost definitely won't need to change this from the default (``True``). :type verify: bool :param dcd: (if ``manifest`` is specified) The Docker-Content-Digest header returned when getting the manifest. If present, this is checked against the manifest. :type dcd: str :rtype: str :returns: Hash of the alias's configuration blob. """ return self._get_alias(alias, manifest, verify, False, dcd, True)
def function[get_digest, parameter[self, alias, manifest, verify, dcd]]: constant[ (v2 schema only) Get the hash of an alias's configuration blob. For an alias created using ``dxf``, this is the hash of the first blob assigned to the alias. For a Docker image tag, this is the same as ``docker inspect alias --format='{{.Id}}'``. :param alias: Alias name. You almost definitely will only need to pass this argument. :type alias: str :param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to do this. :type manifest: str :param verify: (v1 schema only) Whether to verify the integrity of the alias definition in the registry itself. You almost definitely won't need to change this from the default (``True``). :type verify: bool :param dcd: (if ``manifest`` is specified) The Docker-Content-Digest header returned when getting the manifest. If present, this is checked against the manifest. :type dcd: str :rtype: str :returns: Hash of the alias's configuration blob. ] return[call[name[self]._get_alias, parameter[name[alias], name[manifest], name[verify], constant[False], name[dcd], constant[True]]]]
keyword[def] identifier[get_digest] ( identifier[self] , identifier[alias] = keyword[None] , identifier[manifest] = keyword[None] , identifier[verify] = keyword[True] , identifier[dcd] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[_get_alias] ( identifier[alias] , identifier[manifest] , identifier[verify] , keyword[False] , identifier[dcd] , keyword[True] )
def get_digest(self, alias=None, manifest=None, verify=True, dcd=None): """ (v2 schema only) Get the hash of an alias's configuration blob. For an alias created using ``dxf``, this is the hash of the first blob assigned to the alias. For a Docker image tag, this is the same as ``docker inspect alias --format='{{.Id}}'``. :param alias: Alias name. You almost definitely will only need to pass this argument. :type alias: str :param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to do this. :type manifest: str :param verify: (v1 schema only) Whether to verify the integrity of the alias definition in the registry itself. You almost definitely won't need to change this from the default (``True``). :type verify: bool :param dcd: (if ``manifest`` is specified) The Docker-Content-Digest header returned when getting the manifest. If present, this is checked against the manifest. :type dcd: str :rtype: str :returns: Hash of the alias's configuration blob. """ return self._get_alias(alias, manifest, verify, False, dcd, True)
def console_load_apf(con: tcod.console.Console, filename: str) -> bool: """Update a console from an ASCII Paint `.apf` file.""" return bool( lib.TCOD_console_load_apf(_console(con), filename.encode("utf-8")) )
def function[console_load_apf, parameter[con, filename]]: constant[Update a console from an ASCII Paint `.apf` file.] return[call[name[bool], parameter[call[name[lib].TCOD_console_load_apf, parameter[call[name[_console], parameter[name[con]]], call[name[filename].encode, parameter[constant[utf-8]]]]]]]]
keyword[def] identifier[console_load_apf] ( identifier[con] : identifier[tcod] . identifier[console] . identifier[Console] , identifier[filename] : identifier[str] )-> identifier[bool] : literal[string] keyword[return] identifier[bool] ( identifier[lib] . identifier[TCOD_console_load_apf] ( identifier[_console] ( identifier[con] ), identifier[filename] . identifier[encode] ( literal[string] )) )
def console_load_apf(con: tcod.console.Console, filename: str) -> bool: """Update a console from an ASCII Paint `.apf` file.""" return bool(lib.TCOD_console_load_apf(_console(con), filename.encode('utf-8')))
def build(self, client, pull=False, usecache=True): """ Drives an individual build step. Build steps are separated by build_directory. If a build has zero one or less build_directories, it will be built in a single step. Args: client (docker.Client): docker client object that will build the image pull (bool): whether to pull dependent layers from remote repositories usecache (bool): whether to use cached layers or rebuild from scratch """ print(colored(' Building step', 'blue'), colored(self.imagename, 'blue', attrs=['bold']), colored('defined in', 'blue'), colored(self.sourcefile, 'blue', attrs=['bold'])) if self.build_first and not self.build_first.built: self.build_external_dockerfile(client, self.build_first) if self.bust_cache: usecache = False if not usecache: cprint(' Build cache disabled - this image will be rebuilt from scratch', 'yellow') dockerfile = u'\n'.join(self.dockerfile_lines) kwargs = dict(tag=self.buildname, pull=pull, nocache=not usecache, decode=True, rm=True, buildargs=self.buildargs, squash=self.squash) if usecache: utils.set_build_cachefrom(self.cache_from, kwargs, client) if self.build_dir is not None: tempdir = self.write_dockerfile(dockerfile) context_path = os.path.abspath(os.path.expanduser(self.build_dir)) kwargs.update(fileobj=None, dockerfile=os.path.join(DOCKER_TMPDIR, 'Dockerfile')) print(colored(' Build context:', 'blue'), colored(os.path.relpath(context_path), 'blue', attrs=['bold'])) if not self.custom_exclude: kwargs.update(path=context_path) else: print(colored(' Custom .dockerignore from:', 'blue'), colored(os.path.relpath(self.ignoredefs_file), 'blue', attrs=['bold'])) # AMV - this is a brittle call to an apparently "private' docker sdk method context = docker.utils.tar(self.build_dir, exclude=self.custom_exclude, dockerfile=(os.path.join(DOCKER_TMPDIR, 'Dockerfile'), dockerfile), gzip=False) kwargs.update(fileobj=context, custom_context=True) else: if sys.version_info.major == 2: fileobj = StringIO(dockerfile) else: fileobj = BytesIO(dockerfile.encode('utf-8')) kwargs.update(fileobj=fileobj, path=None, dockerfile=None) tempdir = None # start the build stream = client.api.build(**kwargs) try: utils.stream_docker_logs(stream, self.buildname) except docker.errors.APIError as e: if self.squash and not client.version().get('Experimental', False): raise errors.ExperimentalDaemonRequiredError( 'Docker error message:\n ' + str(e) + '\n\nUsing `squash` and/or `secret_files` requires a docker' " daemon with experimental features enabled. See\n" " https://github.com/docker/docker-ce/blob/master/components/cli/" "experimental/README.md") else: raise errors.BuildError(dockerfile, str(e), kwargs) except ValueError as e: raise errors.BuildError(dockerfile, str(e), kwargs) if self.squash and not self.bust_cache: self._resolve_squash_cache(client) # remove the temporary dockerfile if tempdir is not None: os.unlink(os.path.join(tempdir, 'Dockerfile')) os.rmdir(tempdir)
def function[build, parameter[self, client, pull, usecache]]: constant[ Drives an individual build step. Build steps are separated by build_directory. If a build has zero one or less build_directories, it will be built in a single step. Args: client (docker.Client): docker client object that will build the image pull (bool): whether to pull dependent layers from remote repositories usecache (bool): whether to use cached layers or rebuild from scratch ] call[name[print], parameter[call[name[colored], parameter[constant[ Building step], constant[blue]]], call[name[colored], parameter[name[self].imagename, constant[blue]]], call[name[colored], parameter[constant[defined in], constant[blue]]], call[name[colored], parameter[name[self].sourcefile, constant[blue]]]]] if <ast.BoolOp object at 0x7da1b0ef0220> begin[:] call[name[self].build_external_dockerfile, parameter[name[client], name[self].build_first]] if name[self].bust_cache begin[:] variable[usecache] assign[=] constant[False] if <ast.UnaryOp object at 0x7da1b0ef08b0> begin[:] call[name[cprint], parameter[constant[ Build cache disabled - this image will be rebuilt from scratch], constant[yellow]]] variable[dockerfile] assign[=] call[constant[ ].join, parameter[name[self].dockerfile_lines]] variable[kwargs] assign[=] call[name[dict], parameter[]] if name[usecache] begin[:] call[name[utils].set_build_cachefrom, parameter[name[self].cache_from, name[kwargs], name[client]]] if compare[name[self].build_dir is_not constant[None]] begin[:] variable[tempdir] assign[=] call[name[self].write_dockerfile, parameter[name[dockerfile]]] variable[context_path] assign[=] call[name[os].path.abspath, parameter[call[name[os].path.expanduser, parameter[name[self].build_dir]]]] call[name[kwargs].update, parameter[]] call[name[print], parameter[call[name[colored], parameter[constant[ Build context:], constant[blue]]], call[name[colored], parameter[call[name[os].path.relpath, parameter[name[context_path]]], constant[blue]]]]] if <ast.UnaryOp object at 0x7da18bcc9ba0> begin[:] call[name[kwargs].update, parameter[]] variable[stream] assign[=] call[name[client].api.build, parameter[]] <ast.Try object at 0x7da18bccbd30> if <ast.BoolOp object at 0x7da18bcc9600> begin[:] call[name[self]._resolve_squash_cache, parameter[name[client]]] if compare[name[tempdir] is_not constant[None]] begin[:] call[name[os].unlink, parameter[call[name[os].path.join, parameter[name[tempdir], constant[Dockerfile]]]]] call[name[os].rmdir, parameter[name[tempdir]]]
keyword[def] identifier[build] ( identifier[self] , identifier[client] , identifier[pull] = keyword[False] , identifier[usecache] = keyword[True] ): literal[string] identifier[print] ( identifier[colored] ( literal[string] , literal[string] ), identifier[colored] ( identifier[self] . identifier[imagename] , literal[string] , identifier[attrs] =[ literal[string] ]), identifier[colored] ( literal[string] , literal[string] ), identifier[colored] ( identifier[self] . identifier[sourcefile] , literal[string] , identifier[attrs] =[ literal[string] ])) keyword[if] identifier[self] . identifier[build_first] keyword[and] keyword[not] identifier[self] . identifier[build_first] . identifier[built] : identifier[self] . identifier[build_external_dockerfile] ( identifier[client] , identifier[self] . identifier[build_first] ) keyword[if] identifier[self] . identifier[bust_cache] : identifier[usecache] = keyword[False] keyword[if] keyword[not] identifier[usecache] : identifier[cprint] ( literal[string] , literal[string] ) identifier[dockerfile] = literal[string] . identifier[join] ( identifier[self] . identifier[dockerfile_lines] ) identifier[kwargs] = identifier[dict] ( identifier[tag] = identifier[self] . identifier[buildname] , identifier[pull] = identifier[pull] , identifier[nocache] = keyword[not] identifier[usecache] , identifier[decode] = keyword[True] , identifier[rm] = keyword[True] , identifier[buildargs] = identifier[self] . identifier[buildargs] , identifier[squash] = identifier[self] . identifier[squash] ) keyword[if] identifier[usecache] : identifier[utils] . identifier[set_build_cachefrom] ( identifier[self] . identifier[cache_from] , identifier[kwargs] , identifier[client] ) keyword[if] identifier[self] . identifier[build_dir] keyword[is] keyword[not] keyword[None] : identifier[tempdir] = identifier[self] . identifier[write_dockerfile] ( identifier[dockerfile] ) identifier[context_path] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[self] . identifier[build_dir] )) identifier[kwargs] . identifier[update] ( identifier[fileobj] = keyword[None] , identifier[dockerfile] = identifier[os] . identifier[path] . identifier[join] ( identifier[DOCKER_TMPDIR] , literal[string] )) identifier[print] ( identifier[colored] ( literal[string] , literal[string] ), identifier[colored] ( identifier[os] . identifier[path] . identifier[relpath] ( identifier[context_path] ), literal[string] , identifier[attrs] =[ literal[string] ])) keyword[if] keyword[not] identifier[self] . identifier[custom_exclude] : identifier[kwargs] . identifier[update] ( identifier[path] = identifier[context_path] ) keyword[else] : identifier[print] ( identifier[colored] ( literal[string] , literal[string] ), identifier[colored] ( identifier[os] . identifier[path] . identifier[relpath] ( identifier[self] . identifier[ignoredefs_file] ), literal[string] , identifier[attrs] =[ literal[string] ])) identifier[context] = identifier[docker] . identifier[utils] . identifier[tar] ( identifier[self] . identifier[build_dir] , identifier[exclude] = identifier[self] . identifier[custom_exclude] , identifier[dockerfile] =( identifier[os] . identifier[path] . identifier[join] ( identifier[DOCKER_TMPDIR] , literal[string] ), identifier[dockerfile] ), identifier[gzip] = keyword[False] ) identifier[kwargs] . identifier[update] ( identifier[fileobj] = identifier[context] , identifier[custom_context] = keyword[True] ) keyword[else] : keyword[if] identifier[sys] . identifier[version_info] . identifier[major] == literal[int] : identifier[fileobj] = identifier[StringIO] ( identifier[dockerfile] ) keyword[else] : identifier[fileobj] = identifier[BytesIO] ( identifier[dockerfile] . identifier[encode] ( literal[string] )) identifier[kwargs] . identifier[update] ( identifier[fileobj] = identifier[fileobj] , identifier[path] = keyword[None] , identifier[dockerfile] = keyword[None] ) identifier[tempdir] = keyword[None] identifier[stream] = identifier[client] . identifier[api] . identifier[build] (** identifier[kwargs] ) keyword[try] : identifier[utils] . identifier[stream_docker_logs] ( identifier[stream] , identifier[self] . identifier[buildname] ) keyword[except] identifier[docker] . identifier[errors] . identifier[APIError] keyword[as] identifier[e] : keyword[if] identifier[self] . identifier[squash] keyword[and] keyword[not] identifier[client] . identifier[version] (). identifier[get] ( literal[string] , keyword[False] ): keyword[raise] identifier[errors] . identifier[ExperimentalDaemonRequiredError] ( literal[string] + identifier[str] ( identifier[e] )+ literal[string] literal[string] literal[string] literal[string] ) keyword[else] : keyword[raise] identifier[errors] . identifier[BuildError] ( identifier[dockerfile] , identifier[str] ( identifier[e] ), identifier[kwargs] ) keyword[except] identifier[ValueError] keyword[as] identifier[e] : keyword[raise] identifier[errors] . identifier[BuildError] ( identifier[dockerfile] , identifier[str] ( identifier[e] ), identifier[kwargs] ) keyword[if] identifier[self] . identifier[squash] keyword[and] keyword[not] identifier[self] . identifier[bust_cache] : identifier[self] . identifier[_resolve_squash_cache] ( identifier[client] ) keyword[if] identifier[tempdir] keyword[is] keyword[not] keyword[None] : identifier[os] . identifier[unlink] ( identifier[os] . identifier[path] . identifier[join] ( identifier[tempdir] , literal[string] )) identifier[os] . identifier[rmdir] ( identifier[tempdir] )
def build(self, client, pull=False, usecache=True): """ Drives an individual build step. Build steps are separated by build_directory. If a build has zero one or less build_directories, it will be built in a single step. Args: client (docker.Client): docker client object that will build the image pull (bool): whether to pull dependent layers from remote repositories usecache (bool): whether to use cached layers or rebuild from scratch """ print(colored(' Building step', 'blue'), colored(self.imagename, 'blue', attrs=['bold']), colored('defined in', 'blue'), colored(self.sourcefile, 'blue', attrs=['bold'])) if self.build_first and (not self.build_first.built): self.build_external_dockerfile(client, self.build_first) # depends on [control=['if'], data=[]] if self.bust_cache: usecache = False # depends on [control=['if'], data=[]] if not usecache: cprint(' Build cache disabled - this image will be rebuilt from scratch', 'yellow') # depends on [control=['if'], data=[]] dockerfile = u'\n'.join(self.dockerfile_lines) kwargs = dict(tag=self.buildname, pull=pull, nocache=not usecache, decode=True, rm=True, buildargs=self.buildargs, squash=self.squash) if usecache: utils.set_build_cachefrom(self.cache_from, kwargs, client) # depends on [control=['if'], data=[]] if self.build_dir is not None: tempdir = self.write_dockerfile(dockerfile) context_path = os.path.abspath(os.path.expanduser(self.build_dir)) kwargs.update(fileobj=None, dockerfile=os.path.join(DOCKER_TMPDIR, 'Dockerfile')) print(colored(' Build context:', 'blue'), colored(os.path.relpath(context_path), 'blue', attrs=['bold'])) if not self.custom_exclude: kwargs.update(path=context_path) # depends on [control=['if'], data=[]] else: print(colored(' Custom .dockerignore from:', 'blue'), colored(os.path.relpath(self.ignoredefs_file), 'blue', attrs=['bold'])) # AMV - this is a brittle call to an apparently "private' docker sdk method context = docker.utils.tar(self.build_dir, exclude=self.custom_exclude, dockerfile=(os.path.join(DOCKER_TMPDIR, 'Dockerfile'), dockerfile), gzip=False) kwargs.update(fileobj=context, custom_context=True) # depends on [control=['if'], data=[]] else: if sys.version_info.major == 2: fileobj = StringIO(dockerfile) # depends on [control=['if'], data=[]] else: fileobj = BytesIO(dockerfile.encode('utf-8')) kwargs.update(fileobj=fileobj, path=None, dockerfile=None) tempdir = None # start the build stream = client.api.build(**kwargs) try: utils.stream_docker_logs(stream, self.buildname) # depends on [control=['try'], data=[]] except docker.errors.APIError as e: if self.squash and (not client.version().get('Experimental', False)): raise errors.ExperimentalDaemonRequiredError('Docker error message:\n ' + str(e) + '\n\nUsing `squash` and/or `secret_files` requires a docker daemon with experimental features enabled. See\n https://github.com/docker/docker-ce/blob/master/components/cli/experimental/README.md') # depends on [control=['if'], data=[]] else: raise errors.BuildError(dockerfile, str(e), kwargs) # depends on [control=['except'], data=['e']] except ValueError as e: raise errors.BuildError(dockerfile, str(e), kwargs) # depends on [control=['except'], data=['e']] if self.squash and (not self.bust_cache): self._resolve_squash_cache(client) # depends on [control=['if'], data=[]] # remove the temporary dockerfile if tempdir is not None: os.unlink(os.path.join(tempdir, 'Dockerfile')) os.rmdir(tempdir) # depends on [control=['if'], data=['tempdir']]
def percentage(value, digits=2): ''' Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 % ''' value = float(value) * 100.0 return u'' + '%s %%' % (_format(value, digits),)
def function[percentage, parameter[value, digits]]: constant[ Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 % ] variable[value] assign[=] binary_operation[call[name[float], parameter[name[value]]] * constant[100.0]] return[binary_operation[constant[] + binary_operation[constant[%s %%] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b2406440>]]]]]
keyword[def] identifier[percentage] ( identifier[value] , identifier[digits] = literal[int] ): literal[string] identifier[value] = identifier[float] ( identifier[value] )* literal[int] keyword[return] literal[string] + literal[string] %( identifier[_format] ( identifier[value] , identifier[digits] ),)
def percentage(value, digits=2): """ Converts a fraction to a formatted percentage. :param value: number :param digits: default ``2`` >>> print(percentage(1)) 100.00 % >>> print(percentage(0.23, digits=0)) 23 % >>> print(percentage(23.421)) 2,342.10 % """ value = float(value) * 100.0 return u'' + '%s %%' % (_format(value, digits),)
def _send_paginated_message(self, endpoint, params=None): """ Send API message that results in a paginated response. The paginated responses are abstracted away by making API requests on demand as the response is iterated over. Paginated API messages support 3 additional parameters: `before`, `after`, and `limit`. `before` and `after` are mutually exclusive. To use them, supply an index value for that endpoint (the field used for indexing varies by endpoint - get_fills() uses 'trade_id', for example). `before`: Only get data that occurs more recently than index `after`: Only get data that occurs further in the past than index `limit`: Set amount of data per HTTP response. Default (and maximum) of 100. Args: endpoint (str): Endpoint (to be added to base URL) params (Optional[dict]): HTTP request parameters Yields: dict: API response objects """ if params is None: params = dict() url = self.url + endpoint while True: r = self.session.get(url, params=params, auth=self.auth, timeout=30) results = r.json() for result in results: yield result # If there are no more pages, we're done. Otherwise update `after` # param to get next page. # If this request included `before` don't get any more pages - the # cbpro API doesn't support multiple pages in that case. if not r.headers.get('cb-after') or \ params.get('before') is not None: break else: params['after'] = r.headers['cb-after']
def function[_send_paginated_message, parameter[self, endpoint, params]]: constant[ Send API message that results in a paginated response. The paginated responses are abstracted away by making API requests on demand as the response is iterated over. Paginated API messages support 3 additional parameters: `before`, `after`, and `limit`. `before` and `after` are mutually exclusive. To use them, supply an index value for that endpoint (the field used for indexing varies by endpoint - get_fills() uses 'trade_id', for example). `before`: Only get data that occurs more recently than index `after`: Only get data that occurs further in the past than index `limit`: Set amount of data per HTTP response. Default (and maximum) of 100. Args: endpoint (str): Endpoint (to be added to base URL) params (Optional[dict]): HTTP request parameters Yields: dict: API response objects ] if compare[name[params] is constant[None]] begin[:] variable[params] assign[=] call[name[dict], parameter[]] variable[url] assign[=] binary_operation[name[self].url + name[endpoint]] while constant[True] begin[:] variable[r] assign[=] call[name[self].session.get, parameter[name[url]]] variable[results] assign[=] call[name[r].json, parameter[]] for taget[name[result]] in starred[name[results]] begin[:] <ast.Yield object at 0x7da1b18bf520> if <ast.BoolOp object at 0x7da1b18bcc70> begin[:] break
keyword[def] identifier[_send_paginated_message] ( identifier[self] , identifier[endpoint] , identifier[params] = keyword[None] ): literal[string] keyword[if] identifier[params] keyword[is] keyword[None] : identifier[params] = identifier[dict] () identifier[url] = identifier[self] . identifier[url] + identifier[endpoint] keyword[while] keyword[True] : identifier[r] = identifier[self] . identifier[session] . identifier[get] ( identifier[url] , identifier[params] = identifier[params] , identifier[auth] = identifier[self] . identifier[auth] , identifier[timeout] = literal[int] ) identifier[results] = identifier[r] . identifier[json] () keyword[for] identifier[result] keyword[in] identifier[results] : keyword[yield] identifier[result] keyword[if] keyword[not] identifier[r] . identifier[headers] . identifier[get] ( literal[string] ) keyword[or] identifier[params] . identifier[get] ( literal[string] ) keyword[is] keyword[not] keyword[None] : keyword[break] keyword[else] : identifier[params] [ literal[string] ]= identifier[r] . identifier[headers] [ literal[string] ]
def _send_paginated_message(self, endpoint, params=None): """ Send API message that results in a paginated response. The paginated responses are abstracted away by making API requests on demand as the response is iterated over. Paginated API messages support 3 additional parameters: `before`, `after`, and `limit`. `before` and `after` are mutually exclusive. To use them, supply an index value for that endpoint (the field used for indexing varies by endpoint - get_fills() uses 'trade_id', for example). `before`: Only get data that occurs more recently than index `after`: Only get data that occurs further in the past than index `limit`: Set amount of data per HTTP response. Default (and maximum) of 100. Args: endpoint (str): Endpoint (to be added to base URL) params (Optional[dict]): HTTP request parameters Yields: dict: API response objects """ if params is None: params = dict() # depends on [control=['if'], data=['params']] url = self.url + endpoint while True: r = self.session.get(url, params=params, auth=self.auth, timeout=30) results = r.json() for result in results: yield result # depends on [control=['for'], data=['result']] # If there are no more pages, we're done. Otherwise update `after` # param to get next page. # If this request included `before` don't get any more pages - the # cbpro API doesn't support multiple pages in that case. if not r.headers.get('cb-after') or params.get('before') is not None: break # depends on [control=['if'], data=[]] else: params['after'] = r.headers['cb-after'] # depends on [control=['while'], data=[]]
def _toggle_filming(self): """Toggles the camera system recording state""" if self._filming: self.log("Stopping operation") self._filming = False self.timer.stop() else: self.log("Starting operation") self._filming = True self.timer.start()
def function[_toggle_filming, parameter[self]]: constant[Toggles the camera system recording state] if name[self]._filming begin[:] call[name[self].log, parameter[constant[Stopping operation]]] name[self]._filming assign[=] constant[False] call[name[self].timer.stop, parameter[]]
keyword[def] identifier[_toggle_filming] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_filming] : identifier[self] . identifier[log] ( literal[string] ) identifier[self] . identifier[_filming] = keyword[False] identifier[self] . identifier[timer] . identifier[stop] () keyword[else] : identifier[self] . identifier[log] ( literal[string] ) identifier[self] . identifier[_filming] = keyword[True] identifier[self] . identifier[timer] . identifier[start] ()
def _toggle_filming(self): """Toggles the camera system recording state""" if self._filming: self.log('Stopping operation') self._filming = False self.timer.stop() # depends on [control=['if'], data=[]] else: self.log('Starting operation') self._filming = True self.timer.start()
def distance_quat(p1, p2): """ Returns the angle between two quaternions http://math.stackexchange.com/a/90098 :param q1, q2: two quaternions [x, y, z, w] or two poses [[x, y, z], [x, y, z, w]] or two PoseStamped :return: the angle between them (radians) """ if isinstance(p1, PoseStamped): p1 = pose_to_list(p1) if isinstance(p2, PoseStamped): p2 = pose_to_list(p2) if _is_indexable(p1) and _is_indexable(p1[0]): p1 = p1[1] p2 = p2[1] dotp = inner(array(p1), array(p2)) return arccos(2 * dotp * dotp - 1)
def function[distance_quat, parameter[p1, p2]]: constant[ Returns the angle between two quaternions http://math.stackexchange.com/a/90098 :param q1, q2: two quaternions [x, y, z, w] or two poses [[x, y, z], [x, y, z, w]] or two PoseStamped :return: the angle between them (radians) ] if call[name[isinstance], parameter[name[p1], name[PoseStamped]]] begin[:] variable[p1] assign[=] call[name[pose_to_list], parameter[name[p1]]] if call[name[isinstance], parameter[name[p2], name[PoseStamped]]] begin[:] variable[p2] assign[=] call[name[pose_to_list], parameter[name[p2]]] if <ast.BoolOp object at 0x7da20c6c4b20> begin[:] variable[p1] assign[=] call[name[p1]][constant[1]] variable[p2] assign[=] call[name[p2]][constant[1]] variable[dotp] assign[=] call[name[inner], parameter[call[name[array], parameter[name[p1]]], call[name[array], parameter[name[p2]]]]] return[call[name[arccos], parameter[binary_operation[binary_operation[binary_operation[constant[2] * name[dotp]] * name[dotp]] - constant[1]]]]]
keyword[def] identifier[distance_quat] ( identifier[p1] , identifier[p2] ): literal[string] keyword[if] identifier[isinstance] ( identifier[p1] , identifier[PoseStamped] ): identifier[p1] = identifier[pose_to_list] ( identifier[p1] ) keyword[if] identifier[isinstance] ( identifier[p2] , identifier[PoseStamped] ): identifier[p2] = identifier[pose_to_list] ( identifier[p2] ) keyword[if] identifier[_is_indexable] ( identifier[p1] ) keyword[and] identifier[_is_indexable] ( identifier[p1] [ literal[int] ]): identifier[p1] = identifier[p1] [ literal[int] ] identifier[p2] = identifier[p2] [ literal[int] ] identifier[dotp] = identifier[inner] ( identifier[array] ( identifier[p1] ), identifier[array] ( identifier[p2] )) keyword[return] identifier[arccos] ( literal[int] * identifier[dotp] * identifier[dotp] - literal[int] )
def distance_quat(p1, p2): """ Returns the angle between two quaternions http://math.stackexchange.com/a/90098 :param q1, q2: two quaternions [x, y, z, w] or two poses [[x, y, z], [x, y, z, w]] or two PoseStamped :return: the angle between them (radians) """ if isinstance(p1, PoseStamped): p1 = pose_to_list(p1) # depends on [control=['if'], data=[]] if isinstance(p2, PoseStamped): p2 = pose_to_list(p2) # depends on [control=['if'], data=[]] if _is_indexable(p1) and _is_indexable(p1[0]): p1 = p1[1] p2 = p2[1] # depends on [control=['if'], data=[]] dotp = inner(array(p1), array(p2)) return arccos(2 * dotp * dotp - 1)
def hook_inform(self, inform_name, callback): """Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function The function to be called. """ # Do not hook the same callback multiple times if callback not in self._inform_hooks[inform_name]: self._inform_hooks[inform_name].append(callback)
def function[hook_inform, parameter[self, inform_name, callback]]: constant[Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function The function to be called. ] if compare[name[callback] <ast.NotIn object at 0x7da2590d7190> call[name[self]._inform_hooks][name[inform_name]]] begin[:] call[call[name[self]._inform_hooks][name[inform_name]].append, parameter[name[callback]]]
keyword[def] identifier[hook_inform] ( identifier[self] , identifier[inform_name] , identifier[callback] ): literal[string] keyword[if] identifier[callback] keyword[not] keyword[in] identifier[self] . identifier[_inform_hooks] [ identifier[inform_name] ]: identifier[self] . identifier[_inform_hooks] [ identifier[inform_name] ]. identifier[append] ( identifier[callback] )
def hook_inform(self, inform_name, callback): """Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function The function to be called. """ # Do not hook the same callback multiple times if callback not in self._inform_hooks[inform_name]: self._inform_hooks[inform_name].append(callback) # depends on [control=['if'], data=['callback']]
def goto_position(self, position, duration, control=None, wait=False): """ Automatically sets the goal position and the moving speed to reach the desired position within the duration. """ if control is None: control = self.goto_behavior if control == 'minjerk': goto_min_jerk = GotoMinJerk(self, position, duration) goto_min_jerk.start() if wait: goto_min_jerk.wait_to_stop() elif control == 'dummy': dp = abs(self.present_position - position) speed = (dp / float(duration)) if duration > 0 else numpy.inf self.moving_speed = speed self.goal_position = position if wait: time.sleep(duration)
def function[goto_position, parameter[self, position, duration, control, wait]]: constant[ Automatically sets the goal position and the moving speed to reach the desired position within the duration. ] if compare[name[control] is constant[None]] begin[:] variable[control] assign[=] name[self].goto_behavior if compare[name[control] equal[==] constant[minjerk]] begin[:] variable[goto_min_jerk] assign[=] call[name[GotoMinJerk], parameter[name[self], name[position], name[duration]]] call[name[goto_min_jerk].start, parameter[]] if name[wait] begin[:] call[name[goto_min_jerk].wait_to_stop, parameter[]]
keyword[def] identifier[goto_position] ( identifier[self] , identifier[position] , identifier[duration] , identifier[control] = keyword[None] , identifier[wait] = keyword[False] ): literal[string] keyword[if] identifier[control] keyword[is] keyword[None] : identifier[control] = identifier[self] . identifier[goto_behavior] keyword[if] identifier[control] == literal[string] : identifier[goto_min_jerk] = identifier[GotoMinJerk] ( identifier[self] , identifier[position] , identifier[duration] ) identifier[goto_min_jerk] . identifier[start] () keyword[if] identifier[wait] : identifier[goto_min_jerk] . identifier[wait_to_stop] () keyword[elif] identifier[control] == literal[string] : identifier[dp] = identifier[abs] ( identifier[self] . identifier[present_position] - identifier[position] ) identifier[speed] =( identifier[dp] / identifier[float] ( identifier[duration] )) keyword[if] identifier[duration] > literal[int] keyword[else] identifier[numpy] . identifier[inf] identifier[self] . identifier[moving_speed] = identifier[speed] identifier[self] . identifier[goal_position] = identifier[position] keyword[if] identifier[wait] : identifier[time] . identifier[sleep] ( identifier[duration] )
def goto_position(self, position, duration, control=None, wait=False): """ Automatically sets the goal position and the moving speed to reach the desired position within the duration. """ if control is None: control = self.goto_behavior # depends on [control=['if'], data=['control']] if control == 'minjerk': goto_min_jerk = GotoMinJerk(self, position, duration) goto_min_jerk.start() if wait: goto_min_jerk.wait_to_stop() # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif control == 'dummy': dp = abs(self.present_position - position) speed = dp / float(duration) if duration > 0 else numpy.inf self.moving_speed = speed self.goal_position = position if wait: time.sleep(duration) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
def VerifyCoARequest(self): """Verify request authenticator. :return: True if verification failed else False :rtype: boolean """ assert(self.raw_packet) hash = md5_constructor(self.raw_packet[0:4] + 16 * six.b('\x00') + self.raw_packet[20:] + self.secret).digest() return hash == self.authenticator
def function[VerifyCoARequest, parameter[self]]: constant[Verify request authenticator. :return: True if verification failed else False :rtype: boolean ] assert[name[self].raw_packet] variable[hash] assign[=] call[call[name[md5_constructor], parameter[binary_operation[binary_operation[binary_operation[call[name[self].raw_packet][<ast.Slice object at 0x7da18bcc9060>] + binary_operation[constant[16] * call[name[six].b, parameter[constant[]]]]] + call[name[self].raw_packet][<ast.Slice object at 0x7da18bcc9d80>]] + name[self].secret]]].digest, parameter[]] return[compare[name[hash] equal[==] name[self].authenticator]]
keyword[def] identifier[VerifyCoARequest] ( identifier[self] ): literal[string] keyword[assert] ( identifier[self] . identifier[raw_packet] ) identifier[hash] = identifier[md5_constructor] ( identifier[self] . identifier[raw_packet] [ literal[int] : literal[int] ]+ literal[int] * identifier[six] . identifier[b] ( literal[string] )+ identifier[self] . identifier[raw_packet] [ literal[int] :]+ identifier[self] . identifier[secret] ). identifier[digest] () keyword[return] identifier[hash] == identifier[self] . identifier[authenticator]
def VerifyCoARequest(self): """Verify request authenticator. :return: True if verification failed else False :rtype: boolean """ assert self.raw_packet hash = md5_constructor(self.raw_packet[0:4] + 16 * six.b('\x00') + self.raw_packet[20:] + self.secret).digest() return hash == self.authenticator
def remove_observations_below_value(x, y, z, val=0): r"""Remove all x, y, and z where z is less than val. Will not destroy original values. Parameters ---------- x: array_like x coordinate. y: array_like y coordinate. z: array_like Observation value. val: float Value at which to threshold z. Returns ------- x, y, z List of coordinate observation pairs without observation values less than val. """ x_ = x[z >= val] y_ = y[z >= val] z_ = z[z >= val] return x_, y_, z_
def function[remove_observations_below_value, parameter[x, y, z, val]]: constant[Remove all x, y, and z where z is less than val. Will not destroy original values. Parameters ---------- x: array_like x coordinate. y: array_like y coordinate. z: array_like Observation value. val: float Value at which to threshold z. Returns ------- x, y, z List of coordinate observation pairs without observation values less than val. ] variable[x_] assign[=] call[name[x]][compare[name[z] greater_or_equal[>=] name[val]]] variable[y_] assign[=] call[name[y]][compare[name[z] greater_or_equal[>=] name[val]]] variable[z_] assign[=] call[name[z]][compare[name[z] greater_or_equal[>=] name[val]]] return[tuple[[<ast.Name object at 0x7da1b22bab90>, <ast.Name object at 0x7da1b22ba2f0>, <ast.Name object at 0x7da1b22bb4f0>]]]
keyword[def] identifier[remove_observations_below_value] ( identifier[x] , identifier[y] , identifier[z] , identifier[val] = literal[int] ): literal[string] identifier[x_] = identifier[x] [ identifier[z] >= identifier[val] ] identifier[y_] = identifier[y] [ identifier[z] >= identifier[val] ] identifier[z_] = identifier[z] [ identifier[z] >= identifier[val] ] keyword[return] identifier[x_] , identifier[y_] , identifier[z_]
def remove_observations_below_value(x, y, z, val=0): """Remove all x, y, and z where z is less than val. Will not destroy original values. Parameters ---------- x: array_like x coordinate. y: array_like y coordinate. z: array_like Observation value. val: float Value at which to threshold z. Returns ------- x, y, z List of coordinate observation pairs without observation values less than val. """ x_ = x[z >= val] y_ = y[z >= val] z_ = z[z >= val] return (x_, y_, z_)
def all(self): """ Returns all the arguments passed with the request Sample Usage ++++++++++++ .. code:: python from bast import Controller class MyController(Controller): def index(self): data = self.all() Returns a dictionary of all the request arguments """ data = {} args = self.request.arguments for key, value in args.items(): data[key] = self.get_argument(key) return data
def function[all, parameter[self]]: constant[ Returns all the arguments passed with the request Sample Usage ++++++++++++ .. code:: python from bast import Controller class MyController(Controller): def index(self): data = self.all() Returns a dictionary of all the request arguments ] variable[data] assign[=] dictionary[[], []] variable[args] assign[=] name[self].request.arguments for taget[tuple[[<ast.Name object at 0x7da1b2463e20>, <ast.Name object at 0x7da1b24627a0>]]] in starred[call[name[args].items, parameter[]]] begin[:] call[name[data]][name[key]] assign[=] call[name[self].get_argument, parameter[name[key]]] return[name[data]]
keyword[def] identifier[all] ( identifier[self] ): literal[string] identifier[data] ={} identifier[args] = identifier[self] . identifier[request] . identifier[arguments] keyword[for] identifier[key] , identifier[value] keyword[in] identifier[args] . identifier[items] (): identifier[data] [ identifier[key] ]= identifier[self] . identifier[get_argument] ( identifier[key] ) keyword[return] identifier[data]
def all(self): """ Returns all the arguments passed with the request Sample Usage ++++++++++++ .. code:: python from bast import Controller class MyController(Controller): def index(self): data = self.all() Returns a dictionary of all the request arguments """ data = {} args = self.request.arguments for (key, value) in args.items(): data[key] = self.get_argument(key) # depends on [control=['for'], data=[]] return data
def get_chemical_diseases(self, direct_evidence=None, inference_gene_symbol=None, inference_score=None, inference_score_operator=None, cas_rn=None, chemical_name=None, chemical_id=None, chemical_definition=None, disease_definition=None, disease_id=None, disease_name=None, limit=None, as_df=False): """Get chemical–disease associations with inference gene :param direct_evidence: direct evidence :param inference_gene_symbol: inference gene symbol :param inference_score: inference score :param inference_score_operator: inference score operator :param cas_rn: :param chemical_name: chemical name :param chemical_id: :param chemical_definition: :param disease_definition: :param disease_id: :param disease_name: disease name :param int limit: maximum number of results :param bool as_df: if set to True result returns as `pandas.DataFrame` :return: list of :class:`pyctd.manager.database.models.ChemicalDisease` objects .. seealso:: :class:`pyctd.manager.models.ChemicalDisease` which is linked to: :class:`pyctd.manager.models.Disease` :class:`pyctd.manager.models.Chemical` """ q = self.session.query(models.ChemicalDisease) if direct_evidence: q = q.filter(models.ChemicalDisease.direct_evidence.like(direct_evidence)) if inference_gene_symbol: q = q.filter(models.ChemicalDisease.inference_gene_symbol.like(inference_gene_symbol)) if inference_score: if inference_score_operator == ">": q = q.filter_by(models.ChemicalDisease.inference_score > inference_score) elif inference_score_operator == "<": q = q.filter_by(models.ChemicalDisease.inference_score > inference_score) q = self._join_chemical(q, cas_rn=cas_rn, chemical_id=chemical_id, chemical_name=chemical_name, chemical_definition=chemical_definition) q = self._join_disease(q, disease_definition=disease_definition, disease_id=disease_id, disease_name=disease_name) return self._limit_and_df(q, limit, as_df)
def function[get_chemical_diseases, parameter[self, direct_evidence, inference_gene_symbol, inference_score, inference_score_operator, cas_rn, chemical_name, chemical_id, chemical_definition, disease_definition, disease_id, disease_name, limit, as_df]]: constant[Get chemical–disease associations with inference gene :param direct_evidence: direct evidence :param inference_gene_symbol: inference gene symbol :param inference_score: inference score :param inference_score_operator: inference score operator :param cas_rn: :param chemical_name: chemical name :param chemical_id: :param chemical_definition: :param disease_definition: :param disease_id: :param disease_name: disease name :param int limit: maximum number of results :param bool as_df: if set to True result returns as `pandas.DataFrame` :return: list of :class:`pyctd.manager.database.models.ChemicalDisease` objects .. seealso:: :class:`pyctd.manager.models.ChemicalDisease` which is linked to: :class:`pyctd.manager.models.Disease` :class:`pyctd.manager.models.Chemical` ] variable[q] assign[=] call[name[self].session.query, parameter[name[models].ChemicalDisease]] if name[direct_evidence] begin[:] variable[q] assign[=] call[name[q].filter, parameter[call[name[models].ChemicalDisease.direct_evidence.like, parameter[name[direct_evidence]]]]] if name[inference_gene_symbol] begin[:] variable[q] assign[=] call[name[q].filter, parameter[call[name[models].ChemicalDisease.inference_gene_symbol.like, parameter[name[inference_gene_symbol]]]]] if name[inference_score] begin[:] if compare[name[inference_score_operator] equal[==] constant[>]] begin[:] variable[q] assign[=] call[name[q].filter_by, parameter[compare[name[models].ChemicalDisease.inference_score greater[>] name[inference_score]]]] variable[q] assign[=] call[name[self]._join_chemical, parameter[name[q]]] variable[q] assign[=] call[name[self]._join_disease, parameter[name[q]]] return[call[name[self]._limit_and_df, parameter[name[q], name[limit], name[as_df]]]]
keyword[def] identifier[get_chemical_diseases] ( identifier[self] , identifier[direct_evidence] = keyword[None] , identifier[inference_gene_symbol] = keyword[None] , identifier[inference_score] = keyword[None] , identifier[inference_score_operator] = keyword[None] , identifier[cas_rn] = keyword[None] , identifier[chemical_name] = keyword[None] , identifier[chemical_id] = keyword[None] , identifier[chemical_definition] = keyword[None] , identifier[disease_definition] = keyword[None] , identifier[disease_id] = keyword[None] , identifier[disease_name] = keyword[None] , identifier[limit] = keyword[None] , identifier[as_df] = keyword[False] ): literal[string] identifier[q] = identifier[self] . identifier[session] . identifier[query] ( identifier[models] . identifier[ChemicalDisease] ) keyword[if] identifier[direct_evidence] : identifier[q] = identifier[q] . identifier[filter] ( identifier[models] . identifier[ChemicalDisease] . identifier[direct_evidence] . identifier[like] ( identifier[direct_evidence] )) keyword[if] identifier[inference_gene_symbol] : identifier[q] = identifier[q] . identifier[filter] ( identifier[models] . identifier[ChemicalDisease] . identifier[inference_gene_symbol] . identifier[like] ( identifier[inference_gene_symbol] )) keyword[if] identifier[inference_score] : keyword[if] identifier[inference_score_operator] == literal[string] : identifier[q] = identifier[q] . identifier[filter_by] ( identifier[models] . identifier[ChemicalDisease] . identifier[inference_score] > identifier[inference_score] ) keyword[elif] identifier[inference_score_operator] == literal[string] : identifier[q] = identifier[q] . identifier[filter_by] ( identifier[models] . identifier[ChemicalDisease] . identifier[inference_score] > identifier[inference_score] ) identifier[q] = identifier[self] . identifier[_join_chemical] ( identifier[q] , identifier[cas_rn] = identifier[cas_rn] , identifier[chemical_id] = identifier[chemical_id] , identifier[chemical_name] = identifier[chemical_name] , identifier[chemical_definition] = identifier[chemical_definition] ) identifier[q] = identifier[self] . identifier[_join_disease] ( identifier[q] , identifier[disease_definition] = identifier[disease_definition] , identifier[disease_id] = identifier[disease_id] , identifier[disease_name] = identifier[disease_name] ) keyword[return] identifier[self] . identifier[_limit_and_df] ( identifier[q] , identifier[limit] , identifier[as_df] )
def get_chemical_diseases(self, direct_evidence=None, inference_gene_symbol=None, inference_score=None, inference_score_operator=None, cas_rn=None, chemical_name=None, chemical_id=None, chemical_definition=None, disease_definition=None, disease_id=None, disease_name=None, limit=None, as_df=False): """Get chemical–disease associations with inference gene :param direct_evidence: direct evidence :param inference_gene_symbol: inference gene symbol :param inference_score: inference score :param inference_score_operator: inference score operator :param cas_rn: :param chemical_name: chemical name :param chemical_id: :param chemical_definition: :param disease_definition: :param disease_id: :param disease_name: disease name :param int limit: maximum number of results :param bool as_df: if set to True result returns as `pandas.DataFrame` :return: list of :class:`pyctd.manager.database.models.ChemicalDisease` objects .. seealso:: :class:`pyctd.manager.models.ChemicalDisease` which is linked to: :class:`pyctd.manager.models.Disease` :class:`pyctd.manager.models.Chemical` """ q = self.session.query(models.ChemicalDisease) if direct_evidence: q = q.filter(models.ChemicalDisease.direct_evidence.like(direct_evidence)) # depends on [control=['if'], data=[]] if inference_gene_symbol: q = q.filter(models.ChemicalDisease.inference_gene_symbol.like(inference_gene_symbol)) # depends on [control=['if'], data=[]] if inference_score: if inference_score_operator == '>': q = q.filter_by(models.ChemicalDisease.inference_score > inference_score) # depends on [control=['if'], data=[]] elif inference_score_operator == '<': q = q.filter_by(models.ChemicalDisease.inference_score > inference_score) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] q = self._join_chemical(q, cas_rn=cas_rn, chemical_id=chemical_id, chemical_name=chemical_name, chemical_definition=chemical_definition) q = self._join_disease(q, disease_definition=disease_definition, disease_id=disease_id, disease_name=disease_name) return self._limit_and_df(q, limit, as_df)
def count_divisors(n): """ Count the number of divisors of an integer n Args: n (int): strictly positive integer Returns: The number of distinct divisors of n Raises: TypeError: if n is not an integer ValueError: if n is negative """ if not isinstance(n, int): raise TypeError("Expecting a strictly positive integer") if n <= 0: raise ValueError("Expecting a strictly positive integer") number_of_divisors = 1 remain = n for p in prime_generator(): if p > n: return number_of_divisors exponent = 1 while remain % p == 0: remain = remain // p exponent += 1 number_of_divisors *= exponent if remain == 1: return number_of_divisors
def function[count_divisors, parameter[n]]: constant[ Count the number of divisors of an integer n Args: n (int): strictly positive integer Returns: The number of distinct divisors of n Raises: TypeError: if n is not an integer ValueError: if n is negative ] if <ast.UnaryOp object at 0x7da20e955150> begin[:] <ast.Raise object at 0x7da20e956710> if compare[name[n] less_or_equal[<=] constant[0]] begin[:] <ast.Raise object at 0x7da20e9547c0> variable[number_of_divisors] assign[=] constant[1] variable[remain] assign[=] name[n] for taget[name[p]] in starred[call[name[prime_generator], parameter[]]] begin[:] if compare[name[p] greater[>] name[n]] begin[:] return[name[number_of_divisors]] variable[exponent] assign[=] constant[1] while compare[binary_operation[name[remain] <ast.Mod object at 0x7da2590d6920> name[p]] equal[==] constant[0]] begin[:] variable[remain] assign[=] binary_operation[name[remain] <ast.FloorDiv object at 0x7da2590d6bc0> name[p]] <ast.AugAssign object at 0x7da20e955ae0> <ast.AugAssign object at 0x7da1b0926440> if compare[name[remain] equal[==] constant[1]] begin[:] return[name[number_of_divisors]]
keyword[def] identifier[count_divisors] ( identifier[n] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[n] , identifier[int] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[n] <= literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[number_of_divisors] = literal[int] identifier[remain] = identifier[n] keyword[for] identifier[p] keyword[in] identifier[prime_generator] (): keyword[if] identifier[p] > identifier[n] : keyword[return] identifier[number_of_divisors] identifier[exponent] = literal[int] keyword[while] identifier[remain] % identifier[p] == literal[int] : identifier[remain] = identifier[remain] // identifier[p] identifier[exponent] += literal[int] identifier[number_of_divisors] *= identifier[exponent] keyword[if] identifier[remain] == literal[int] : keyword[return] identifier[number_of_divisors]
def count_divisors(n): """ Count the number of divisors of an integer n Args: n (int): strictly positive integer Returns: The number of distinct divisors of n Raises: TypeError: if n is not an integer ValueError: if n is negative """ if not isinstance(n, int): raise TypeError('Expecting a strictly positive integer') # depends on [control=['if'], data=[]] if n <= 0: raise ValueError('Expecting a strictly positive integer') # depends on [control=['if'], data=[]] number_of_divisors = 1 remain = n for p in prime_generator(): if p > n: return number_of_divisors # depends on [control=['if'], data=[]] exponent = 1 while remain % p == 0: remain = remain // p exponent += 1 # depends on [control=['while'], data=[]] number_of_divisors *= exponent if remain == 1: return number_of_divisors # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['p']]
def publish(self, page): """ Publish the page in all languages. """ assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page publish_page(page, languages=self.languages)
def function[publish, parameter[self, page]]: constant[ Publish the page in all languages. ] assert[compare[name[page].publisher_is_draft equal[==] constant[True]]] call[name[publish_page], parameter[name[page]]]
keyword[def] identifier[publish] ( identifier[self] , identifier[page] ): literal[string] keyword[assert] identifier[page] . identifier[publisher_is_draft] == keyword[True] , literal[string] % identifier[page] identifier[publish_page] ( identifier[page] , identifier[languages] = identifier[self] . identifier[languages] )
def publish(self, page): """ Publish the page in all languages. """ assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page publish_page(page, languages=self.languages)
def from_networkx(graph, layout_function, **kwargs): ''' Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx layout function. Any keyword arguments will be passed to the layout function. Only two dimensional layouts are supported. Args: graph (networkx.Graph) : a networkx graph to render layout_function (function or dict) : a networkx layout function or mapping of node keys to positions. The position is a two element sequence containing the x and y coordinate. Returns: instance (GraphRenderer) .. note:: Node and edge attributes may be lists or tuples. However, a given attribute must either have *all* lists or tuple values, or *all* scalar values, for nodes or edges it is defined on. .. warning:: Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored. If you want to convert these attributes, please re-label them to other names. Raises: ValueError ''' # inline import to prevent circular imports from ..models.renderers import GraphRenderer from ..models.graphs import StaticLayoutProvider # Handles nx 1.x vs 2.x data structure change # Convert node attributes node_dict = dict() node_attr_keys = [attr_key for node in list(graph.nodes(data=True)) for attr_key in node[1].keys()] node_attr_keys = list(set(node_attr_keys)) for attr_key in node_attr_keys: values = [node_attr[attr_key] if attr_key in node_attr.keys() else None for _, node_attr in graph.nodes(data=True)] values = _handle_sublists(values) node_dict[attr_key] = values if 'index' in node_attr_keys: from warnings import warn warn("Converting node attributes labeled 'index' are skipped. " "If you want to convert these attributes, please re-label with other names.") node_dict['index'] = list(graph.nodes()) # Convert edge attributes edge_dict = dict() edge_attr_keys = [attr_key for edge in graph.edges(data=True) for attr_key in edge[2].keys()] edge_attr_keys = list(set(edge_attr_keys)) for attr_key in edge_attr_keys: values = [edge_attr[attr_key] if attr_key in edge_attr.keys() else None for _, _, edge_attr in graph.edges(data=True)] values = _handle_sublists(values) edge_dict[attr_key] = values if 'start' in edge_attr_keys or 'end' in edge_attr_keys: from warnings import warn warn("Converting edge attributes labeled 'start' or 'end' are skipped. " "If you want to convert these attributes, please re-label them with other names.") edge_dict['start'] = [x[0] for x in graph.edges()] edge_dict['end'] = [x[1] for x in graph.edges()] node_source = ColumnDataSource(data=node_dict) edge_source = ColumnDataSource(data=edge_dict) graph_renderer = GraphRenderer() graph_renderer.node_renderer.data_source.data = node_source.data graph_renderer.edge_renderer.data_source.data = edge_source.data if callable(layout_function): graph_layout = layout_function(graph, **kwargs) else: graph_layout = layout_function node_keys = graph_renderer.node_renderer.data_source.data['index'] if set(node_keys) != set(layout_function.keys()): from warnings import warn warn("Node keys in 'layout_function' don't match node keys in the graph. " "These nodes may not be displayed correctly.") graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) return graph_renderer
def function[from_networkx, parameter[graph, layout_function]]: constant[ Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx layout function. Any keyword arguments will be passed to the layout function. Only two dimensional layouts are supported. Args: graph (networkx.Graph) : a networkx graph to render layout_function (function or dict) : a networkx layout function or mapping of node keys to positions. The position is a two element sequence containing the x and y coordinate. Returns: instance (GraphRenderer) .. note:: Node and edge attributes may be lists or tuples. However, a given attribute must either have *all* lists or tuple values, or *all* scalar values, for nodes or edges it is defined on. .. warning:: Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored. If you want to convert these attributes, please re-label them to other names. Raises: ValueError ] from relative_module[models.renderers] import module[GraphRenderer] from relative_module[models.graphs] import module[StaticLayoutProvider] variable[node_dict] assign[=] call[name[dict], parameter[]] variable[node_attr_keys] assign[=] <ast.ListComp object at 0x7da20c990370> variable[node_attr_keys] assign[=] call[name[list], parameter[call[name[set], parameter[name[node_attr_keys]]]]] for taget[name[attr_key]] in starred[name[node_attr_keys]] begin[:] variable[values] assign[=] <ast.ListComp object at 0x7da20c990190> variable[values] assign[=] call[name[_handle_sublists], parameter[name[values]]] call[name[node_dict]][name[attr_key]] assign[=] name[values] if compare[constant[index] in name[node_attr_keys]] begin[:] from relative_module[warnings] import module[warn] call[name[warn], parameter[constant[Converting node attributes labeled 'index' are skipped. If you want to convert these attributes, please re-label with other names.]]] call[name[node_dict]][constant[index]] assign[=] call[name[list], parameter[call[name[graph].nodes, parameter[]]]] variable[edge_dict] assign[=] call[name[dict], parameter[]] variable[edge_attr_keys] assign[=] <ast.ListComp object at 0x7da1b1f62560> variable[edge_attr_keys] assign[=] call[name[list], parameter[call[name[set], parameter[name[edge_attr_keys]]]]] for taget[name[attr_key]] in starred[name[edge_attr_keys]] begin[:] variable[values] assign[=] <ast.ListComp object at 0x7da1b1f61a20> variable[values] assign[=] call[name[_handle_sublists], parameter[name[values]]] call[name[edge_dict]][name[attr_key]] assign[=] name[values] if <ast.BoolOp object at 0x7da1b1f601f0> begin[:] from relative_module[warnings] import module[warn] call[name[warn], parameter[constant[Converting edge attributes labeled 'start' or 'end' are skipped. If you want to convert these attributes, please re-label them with other names.]]] call[name[edge_dict]][constant[start]] assign[=] <ast.ListComp object at 0x7da1b1f634c0> call[name[edge_dict]][constant[end]] assign[=] <ast.ListComp object at 0x7da1b1f60d00> variable[node_source] assign[=] call[name[ColumnDataSource], parameter[]] variable[edge_source] assign[=] call[name[ColumnDataSource], parameter[]] variable[graph_renderer] assign[=] call[name[GraphRenderer], parameter[]] name[graph_renderer].node_renderer.data_source.data assign[=] name[node_source].data name[graph_renderer].edge_renderer.data_source.data assign[=] name[edge_source].data if call[name[callable], parameter[name[layout_function]]] begin[:] variable[graph_layout] assign[=] call[name[layout_function], parameter[name[graph]]] name[graph_renderer].layout_provider assign[=] call[name[StaticLayoutProvider], parameter[]] return[name[graph_renderer]]
keyword[def] identifier[from_networkx] ( identifier[graph] , identifier[layout_function] ,** identifier[kwargs] ): literal[string] keyword[from] .. identifier[models] . identifier[renderers] keyword[import] identifier[GraphRenderer] keyword[from] .. identifier[models] . identifier[graphs] keyword[import] identifier[StaticLayoutProvider] identifier[node_dict] = identifier[dict] () identifier[node_attr_keys] =[ identifier[attr_key] keyword[for] identifier[node] keyword[in] identifier[list] ( identifier[graph] . identifier[nodes] ( identifier[data] = keyword[True] )) keyword[for] identifier[attr_key] keyword[in] identifier[node] [ literal[int] ]. identifier[keys] ()] identifier[node_attr_keys] = identifier[list] ( identifier[set] ( identifier[node_attr_keys] )) keyword[for] identifier[attr_key] keyword[in] identifier[node_attr_keys] : identifier[values] =[ identifier[node_attr] [ identifier[attr_key] ] keyword[if] identifier[attr_key] keyword[in] identifier[node_attr] . identifier[keys] () keyword[else] keyword[None] keyword[for] identifier[_] , identifier[node_attr] keyword[in] identifier[graph] . identifier[nodes] ( identifier[data] = keyword[True] )] identifier[values] = identifier[_handle_sublists] ( identifier[values] ) identifier[node_dict] [ identifier[attr_key] ]= identifier[values] keyword[if] literal[string] keyword[in] identifier[node_attr_keys] : keyword[from] identifier[warnings] keyword[import] identifier[warn] identifier[warn] ( literal[string] literal[string] ) identifier[node_dict] [ literal[string] ]= identifier[list] ( identifier[graph] . identifier[nodes] ()) identifier[edge_dict] = identifier[dict] () identifier[edge_attr_keys] =[ identifier[attr_key] keyword[for] identifier[edge] keyword[in] identifier[graph] . identifier[edges] ( identifier[data] = keyword[True] ) keyword[for] identifier[attr_key] keyword[in] identifier[edge] [ literal[int] ]. identifier[keys] ()] identifier[edge_attr_keys] = identifier[list] ( identifier[set] ( identifier[edge_attr_keys] )) keyword[for] identifier[attr_key] keyword[in] identifier[edge_attr_keys] : identifier[values] =[ identifier[edge_attr] [ identifier[attr_key] ] keyword[if] identifier[attr_key] keyword[in] identifier[edge_attr] . identifier[keys] () keyword[else] keyword[None] keyword[for] identifier[_] , identifier[_] , identifier[edge_attr] keyword[in] identifier[graph] . identifier[edges] ( identifier[data] = keyword[True] )] identifier[values] = identifier[_handle_sublists] ( identifier[values] ) identifier[edge_dict] [ identifier[attr_key] ]= identifier[values] keyword[if] literal[string] keyword[in] identifier[edge_attr_keys] keyword[or] literal[string] keyword[in] identifier[edge_attr_keys] : keyword[from] identifier[warnings] keyword[import] identifier[warn] identifier[warn] ( literal[string] literal[string] ) identifier[edge_dict] [ literal[string] ]=[ identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in] identifier[graph] . identifier[edges] ()] identifier[edge_dict] [ literal[string] ]=[ identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in] identifier[graph] . identifier[edges] ()] identifier[node_source] = identifier[ColumnDataSource] ( identifier[data] = identifier[node_dict] ) identifier[edge_source] = identifier[ColumnDataSource] ( identifier[data] = identifier[edge_dict] ) identifier[graph_renderer] = identifier[GraphRenderer] () identifier[graph_renderer] . identifier[node_renderer] . identifier[data_source] . identifier[data] = identifier[node_source] . identifier[data] identifier[graph_renderer] . identifier[edge_renderer] . identifier[data_source] . identifier[data] = identifier[edge_source] . identifier[data] keyword[if] identifier[callable] ( identifier[layout_function] ): identifier[graph_layout] = identifier[layout_function] ( identifier[graph] ,** identifier[kwargs] ) keyword[else] : identifier[graph_layout] = identifier[layout_function] identifier[node_keys] = identifier[graph_renderer] . identifier[node_renderer] . identifier[data_source] . identifier[data] [ literal[string] ] keyword[if] identifier[set] ( identifier[node_keys] )!= identifier[set] ( identifier[layout_function] . identifier[keys] ()): keyword[from] identifier[warnings] keyword[import] identifier[warn] identifier[warn] ( literal[string] literal[string] ) identifier[graph_renderer] . identifier[layout_provider] = identifier[StaticLayoutProvider] ( identifier[graph_layout] = identifier[graph_layout] ) keyword[return] identifier[graph_renderer]
def from_networkx(graph, layout_function, **kwargs): """ Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx layout function. Any keyword arguments will be passed to the layout function. Only two dimensional layouts are supported. Args: graph (networkx.Graph) : a networkx graph to render layout_function (function or dict) : a networkx layout function or mapping of node keys to positions. The position is a two element sequence containing the x and y coordinate. Returns: instance (GraphRenderer) .. note:: Node and edge attributes may be lists or tuples. However, a given attribute must either have *all* lists or tuple values, or *all* scalar values, for nodes or edges it is defined on. .. warning:: Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored. If you want to convert these attributes, please re-label them to other names. Raises: ValueError """ # inline import to prevent circular imports from ..models.renderers import GraphRenderer from ..models.graphs import StaticLayoutProvider # Handles nx 1.x vs 2.x data structure change # Convert node attributes node_dict = dict() node_attr_keys = [attr_key for node in list(graph.nodes(data=True)) for attr_key in node[1].keys()] node_attr_keys = list(set(node_attr_keys)) for attr_key in node_attr_keys: values = [node_attr[attr_key] if attr_key in node_attr.keys() else None for (_, node_attr) in graph.nodes(data=True)] values = _handle_sublists(values) node_dict[attr_key] = values # depends on [control=['for'], data=['attr_key']] if 'index' in node_attr_keys: from warnings import warn warn("Converting node attributes labeled 'index' are skipped. If you want to convert these attributes, please re-label with other names.") # depends on [control=['if'], data=[]] node_dict['index'] = list(graph.nodes()) # Convert edge attributes edge_dict = dict() edge_attr_keys = [attr_key for edge in graph.edges(data=True) for attr_key in edge[2].keys()] edge_attr_keys = list(set(edge_attr_keys)) for attr_key in edge_attr_keys: values = [edge_attr[attr_key] if attr_key in edge_attr.keys() else None for (_, _, edge_attr) in graph.edges(data=True)] values = _handle_sublists(values) edge_dict[attr_key] = values # depends on [control=['for'], data=['attr_key']] if 'start' in edge_attr_keys or 'end' in edge_attr_keys: from warnings import warn warn("Converting edge attributes labeled 'start' or 'end' are skipped. If you want to convert these attributes, please re-label them with other names.") # depends on [control=['if'], data=[]] edge_dict['start'] = [x[0] for x in graph.edges()] edge_dict['end'] = [x[1] for x in graph.edges()] node_source = ColumnDataSource(data=node_dict) edge_source = ColumnDataSource(data=edge_dict) graph_renderer = GraphRenderer() graph_renderer.node_renderer.data_source.data = node_source.data graph_renderer.edge_renderer.data_source.data = edge_source.data if callable(layout_function): graph_layout = layout_function(graph, **kwargs) # depends on [control=['if'], data=[]] else: graph_layout = layout_function node_keys = graph_renderer.node_renderer.data_source.data['index'] if set(node_keys) != set(layout_function.keys()): from warnings import warn warn("Node keys in 'layout_function' don't match node keys in the graph. These nodes may not be displayed correctly.") # depends on [control=['if'], data=[]] graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) return graph_renderer
async def exit_rescue_mode( self, wait: bool = False, wait_interval: int = 5): """ Exit rescue mode. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data = await self._handler.exit_rescue_mode( system_id=self.system_id ) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to exit rescue mode." raise OperationNotAllowed(message) from error else: raise if not wait: return self else: # Wait for machine to finish exiting rescue mode while self.status == NodeStatus.EXITING_RESCUE_MODE: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_EXITING_RESCUE_MODE: msg = "{hostname} failed to exit rescue mode.".format( hostname=self.hostname ) raise RescueModeFailure(msg, self) return self
<ast.AsyncFunctionDef object at 0x7da20c76f3d0>
keyword[async] keyword[def] identifier[exit_rescue_mode] ( identifier[self] , identifier[wait] : identifier[bool] = keyword[False] , identifier[wait_interval] : identifier[int] = literal[int] ): literal[string] keyword[try] : identifier[self] . identifier[_data] = keyword[await] identifier[self] . identifier[_handler] . identifier[exit_rescue_mode] ( identifier[system_id] = identifier[self] . identifier[system_id] ) keyword[except] identifier[CallError] keyword[as] identifier[error] : keyword[if] identifier[error] . identifier[status] == identifier[HTTPStatus] . identifier[FORBIDDEN] : identifier[message] = literal[string] keyword[raise] identifier[OperationNotAllowed] ( identifier[message] ) keyword[from] identifier[error] keyword[else] : keyword[raise] keyword[if] keyword[not] identifier[wait] : keyword[return] identifier[self] keyword[else] : keyword[while] identifier[self] . identifier[status] == identifier[NodeStatus] . identifier[EXITING_RESCUE_MODE] : keyword[await] identifier[asyncio] . identifier[sleep] ( identifier[wait_interval] ) identifier[self] . identifier[_data] = keyword[await] identifier[self] . identifier[_handler] . identifier[read] ( identifier[system_id] = identifier[self] . identifier[system_id] ) keyword[if] identifier[self] . identifier[status] == identifier[NodeStatus] . identifier[FAILED_EXITING_RESCUE_MODE] : identifier[msg] = literal[string] . identifier[format] ( identifier[hostname] = identifier[self] . identifier[hostname] ) keyword[raise] identifier[RescueModeFailure] ( identifier[msg] , identifier[self] ) keyword[return] identifier[self]
async def exit_rescue_mode(self, wait: bool=False, wait_interval: int=5): """ Exit rescue mode. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data = await self._handler.exit_rescue_mode(system_id=self.system_id) # depends on [control=['try'], data=[]] except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = 'Not allowed to exit rescue mode.' raise OperationNotAllowed(message) from error # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=['error']] if not wait: return self # depends on [control=['if'], data=[]] else: # Wait for machine to finish exiting rescue mode while self.status == NodeStatus.EXITING_RESCUE_MODE: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) # depends on [control=['while'], data=[]] if self.status == NodeStatus.FAILED_EXITING_RESCUE_MODE: msg = '{hostname} failed to exit rescue mode.'.format(hostname=self.hostname) raise RescueModeFailure(msg, self) # depends on [control=['if'], data=[]] return self
def get_container_create_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """ policy = self._policy client_config = action.client_config container_map = action.container_map container_config = action.config image_tag = container_map.get_image(container_config.image or action.config_id.config_name) default_paths = policy.default_volume_paths[action.config_id.map_name] c_kwargs = dict( name=container_name, image=format_image_tag(image_tag), volumes=get_volumes(container_map, container_config, default_paths, client_config.features['volumes']), user=extract_user(container_config.user), ports=[resolve_value(port_binding.exposed_port) for port_binding in container_config.exposes if port_binding.exposed_port], hostname=policy.get_hostname(container_name, action.client_name) if container_map.set_hostname else None, domainname=resolve_value(client_config.get('domainname', container_map.default_domain)) or None, ) if container_config.network_mode == 'none': c_kwargs['network_disabled'] = True elif client_config.features['networks'] and container_config.networks: first_network = container_config.networks[0] c_kwargs['networking_config'] = NetworkingConfig({ policy.nname(action.config_id.map_name, first_network.network_name): EndpointConfig( client_config.version, **self.get_network_create_endpoint_kwargs(action, first_network) ) }) if client_config.features['stop_signal'] and container_config.stop_signal: c_kwargs['stop_signal'] = container_config.stop_signal hc_extra_kwargs = kwargs.pop('host_config', None) if kwargs else None use_host_config = client_config.features['host_config'] if use_host_config: hc_kwargs = self.get_container_host_config_kwargs(action, None, kwargs=hc_extra_kwargs) if hc_kwargs: if use_host_config == USE_HC_MERGE: c_kwargs.update(hc_kwargs) else: c_kwargs['host_config'] = HostConfig(version=client_config.version, **hc_kwargs) if client_config.features['stop_timeout'] and container_config.stop_timeout: c_kwargs['stop_timeout'] = container_config.stop_timeout if client_config.features['healthcheck'] and container_config.healthcheck: c_kwargs['healthcheck'] = container_config.healthcheck._asdict() update_kwargs(c_kwargs, init_options(container_config.create_options), kwargs) return c_kwargs
def function[get_container_create_kwargs, parameter[self, action, container_name, kwargs]]: constant[ Generates keyword arguments for the Docker client to create a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict ] variable[policy] assign[=] name[self]._policy variable[client_config] assign[=] name[action].client_config variable[container_map] assign[=] name[action].container_map variable[container_config] assign[=] name[action].config variable[image_tag] assign[=] call[name[container_map].get_image, parameter[<ast.BoolOp object at 0x7da1b2844370>]] variable[default_paths] assign[=] call[name[policy].default_volume_paths][name[action].config_id.map_name] variable[c_kwargs] assign[=] call[name[dict], parameter[]] if compare[name[container_config].network_mode equal[==] constant[none]] begin[:] call[name[c_kwargs]][constant[network_disabled]] assign[=] constant[True] if <ast.BoolOp object at 0x7da1b27edea0> begin[:] call[name[c_kwargs]][constant[stop_signal]] assign[=] name[container_config].stop_signal variable[hc_extra_kwargs] assign[=] <ast.IfExp object at 0x7da1b27ed780> variable[use_host_config] assign[=] call[name[client_config].features][constant[host_config]] if name[use_host_config] begin[:] variable[hc_kwargs] assign[=] call[name[self].get_container_host_config_kwargs, parameter[name[action], constant[None]]] if name[hc_kwargs] begin[:] if compare[name[use_host_config] equal[==] name[USE_HC_MERGE]] begin[:] call[name[c_kwargs].update, parameter[name[hc_kwargs]]] if <ast.BoolOp object at 0x7da18c4ce470> begin[:] call[name[c_kwargs]][constant[stop_timeout]] assign[=] name[container_config].stop_timeout if <ast.BoolOp object at 0x7da18c4ccdf0> begin[:] call[name[c_kwargs]][constant[healthcheck]] assign[=] call[name[container_config].healthcheck._asdict, parameter[]] call[name[update_kwargs], parameter[name[c_kwargs], call[name[init_options], parameter[name[container_config].create_options]], name[kwargs]]] return[name[c_kwargs]]
keyword[def] identifier[get_container_create_kwargs] ( identifier[self] , identifier[action] , identifier[container_name] , identifier[kwargs] = keyword[None] ): literal[string] identifier[policy] = identifier[self] . identifier[_policy] identifier[client_config] = identifier[action] . identifier[client_config] identifier[container_map] = identifier[action] . identifier[container_map] identifier[container_config] = identifier[action] . identifier[config] identifier[image_tag] = identifier[container_map] . identifier[get_image] ( identifier[container_config] . identifier[image] keyword[or] identifier[action] . identifier[config_id] . identifier[config_name] ) identifier[default_paths] = identifier[policy] . identifier[default_volume_paths] [ identifier[action] . identifier[config_id] . identifier[map_name] ] identifier[c_kwargs] = identifier[dict] ( identifier[name] = identifier[container_name] , identifier[image] = identifier[format_image_tag] ( identifier[image_tag] ), identifier[volumes] = identifier[get_volumes] ( identifier[container_map] , identifier[container_config] , identifier[default_paths] , identifier[client_config] . identifier[features] [ literal[string] ]), identifier[user] = identifier[extract_user] ( identifier[container_config] . identifier[user] ), identifier[ports] =[ identifier[resolve_value] ( identifier[port_binding] . identifier[exposed_port] ) keyword[for] identifier[port_binding] keyword[in] identifier[container_config] . identifier[exposes] keyword[if] identifier[port_binding] . identifier[exposed_port] ], identifier[hostname] = identifier[policy] . identifier[get_hostname] ( identifier[container_name] , identifier[action] . identifier[client_name] ) keyword[if] identifier[container_map] . identifier[set_hostname] keyword[else] keyword[None] , identifier[domainname] = identifier[resolve_value] ( identifier[client_config] . identifier[get] ( literal[string] , identifier[container_map] . identifier[default_domain] )) keyword[or] keyword[None] , ) keyword[if] identifier[container_config] . identifier[network_mode] == literal[string] : identifier[c_kwargs] [ literal[string] ]= keyword[True] keyword[elif] identifier[client_config] . identifier[features] [ literal[string] ] keyword[and] identifier[container_config] . identifier[networks] : identifier[first_network] = identifier[container_config] . identifier[networks] [ literal[int] ] identifier[c_kwargs] [ literal[string] ]= identifier[NetworkingConfig] ({ identifier[policy] . identifier[nname] ( identifier[action] . identifier[config_id] . identifier[map_name] , identifier[first_network] . identifier[network_name] ): identifier[EndpointConfig] ( identifier[client_config] . identifier[version] ,** identifier[self] . identifier[get_network_create_endpoint_kwargs] ( identifier[action] , identifier[first_network] ) ) }) keyword[if] identifier[client_config] . identifier[features] [ literal[string] ] keyword[and] identifier[container_config] . identifier[stop_signal] : identifier[c_kwargs] [ literal[string] ]= identifier[container_config] . identifier[stop_signal] identifier[hc_extra_kwargs] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) keyword[if] identifier[kwargs] keyword[else] keyword[None] identifier[use_host_config] = identifier[client_config] . identifier[features] [ literal[string] ] keyword[if] identifier[use_host_config] : identifier[hc_kwargs] = identifier[self] . identifier[get_container_host_config_kwargs] ( identifier[action] , keyword[None] , identifier[kwargs] = identifier[hc_extra_kwargs] ) keyword[if] identifier[hc_kwargs] : keyword[if] identifier[use_host_config] == identifier[USE_HC_MERGE] : identifier[c_kwargs] . identifier[update] ( identifier[hc_kwargs] ) keyword[else] : identifier[c_kwargs] [ literal[string] ]= identifier[HostConfig] ( identifier[version] = identifier[client_config] . identifier[version] ,** identifier[hc_kwargs] ) keyword[if] identifier[client_config] . identifier[features] [ literal[string] ] keyword[and] identifier[container_config] . identifier[stop_timeout] : identifier[c_kwargs] [ literal[string] ]= identifier[container_config] . identifier[stop_timeout] keyword[if] identifier[client_config] . identifier[features] [ literal[string] ] keyword[and] identifier[container_config] . identifier[healthcheck] : identifier[c_kwargs] [ literal[string] ]= identifier[container_config] . identifier[healthcheck] . identifier[_asdict] () identifier[update_kwargs] ( identifier[c_kwargs] , identifier[init_options] ( identifier[container_config] . identifier[create_options] ), identifier[kwargs] ) keyword[return] identifier[c_kwargs]
def get_container_create_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """ policy = self._policy client_config = action.client_config container_map = action.container_map container_config = action.config image_tag = container_map.get_image(container_config.image or action.config_id.config_name) default_paths = policy.default_volume_paths[action.config_id.map_name] c_kwargs = dict(name=container_name, image=format_image_tag(image_tag), volumes=get_volumes(container_map, container_config, default_paths, client_config.features['volumes']), user=extract_user(container_config.user), ports=[resolve_value(port_binding.exposed_port) for port_binding in container_config.exposes if port_binding.exposed_port], hostname=policy.get_hostname(container_name, action.client_name) if container_map.set_hostname else None, domainname=resolve_value(client_config.get('domainname', container_map.default_domain)) or None) if container_config.network_mode == 'none': c_kwargs['network_disabled'] = True # depends on [control=['if'], data=[]] elif client_config.features['networks'] and container_config.networks: first_network = container_config.networks[0] c_kwargs['networking_config'] = NetworkingConfig({policy.nname(action.config_id.map_name, first_network.network_name): EndpointConfig(client_config.version, **self.get_network_create_endpoint_kwargs(action, first_network))}) # depends on [control=['if'], data=[]] if client_config.features['stop_signal'] and container_config.stop_signal: c_kwargs['stop_signal'] = container_config.stop_signal # depends on [control=['if'], data=[]] hc_extra_kwargs = kwargs.pop('host_config', None) if kwargs else None use_host_config = client_config.features['host_config'] if use_host_config: hc_kwargs = self.get_container_host_config_kwargs(action, None, kwargs=hc_extra_kwargs) if hc_kwargs: if use_host_config == USE_HC_MERGE: c_kwargs.update(hc_kwargs) # depends on [control=['if'], data=[]] else: c_kwargs['host_config'] = HostConfig(version=client_config.version, **hc_kwargs) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if client_config.features['stop_timeout'] and container_config.stop_timeout: c_kwargs['stop_timeout'] = container_config.stop_timeout # depends on [control=['if'], data=[]] if client_config.features['healthcheck'] and container_config.healthcheck: c_kwargs['healthcheck'] = container_config.healthcheck._asdict() # depends on [control=['if'], data=[]] update_kwargs(c_kwargs, init_options(container_config.create_options), kwargs) return c_kwargs
def revoke_security_group(self, group_name=None, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, group_id=None, src_security_group_group_id=None): """ Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful. """ if src_security_group_name: if from_port is None and to_port is None and ip_protocol is None: return self.revoke_security_group_deprecated( group_name, src_security_group_name, src_security_group_owner_id) params = {} if group_name is not None: params['GroupName'] = group_name if group_id is not None: params['GroupId'] = group_id if src_security_group_name: param_name = 'IpPermissions.1.Groups.1.GroupName' params[param_name] = src_security_group_name if src_security_group_group_id: param_name = 'IpPermissions.1.Groups.1.GroupId' params[param_name] = src_security_group_group_id if src_security_group_owner_id: param_name = 'IpPermissions.1.Groups.1.UserId' params[param_name] = src_security_group_owner_id if ip_protocol: params['IpPermissions.1.IpProtocol'] = ip_protocol if from_port is not None: params['IpPermissions.1.FromPort'] = from_port if to_port is not None: params['IpPermissions.1.ToPort'] = to_port if cidr_ip: params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip return self.get_status('RevokeSecurityGroupIngress', params, verb='POST')
def function[revoke_security_group, parameter[self, group_name, src_security_group_name, src_security_group_owner_id, ip_protocol, from_port, to_port, cidr_ip, group_id, src_security_group_group_id]]: constant[ Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful. ] if name[src_security_group_name] begin[:] if <ast.BoolOp object at 0x7da1b26a46d0> begin[:] return[call[name[self].revoke_security_group_deprecated, parameter[name[group_name], name[src_security_group_name], name[src_security_group_owner_id]]]] variable[params] assign[=] dictionary[[], []] if compare[name[group_name] is_not constant[None]] begin[:] call[name[params]][constant[GroupName]] assign[=] name[group_name] if compare[name[group_id] is_not constant[None]] begin[:] call[name[params]][constant[GroupId]] assign[=] name[group_id] if name[src_security_group_name] begin[:] variable[param_name] assign[=] constant[IpPermissions.1.Groups.1.GroupName] call[name[params]][name[param_name]] assign[=] name[src_security_group_name] if name[src_security_group_group_id] begin[:] variable[param_name] assign[=] constant[IpPermissions.1.Groups.1.GroupId] call[name[params]][name[param_name]] assign[=] name[src_security_group_group_id] if name[src_security_group_owner_id] begin[:] variable[param_name] assign[=] constant[IpPermissions.1.Groups.1.UserId] call[name[params]][name[param_name]] assign[=] name[src_security_group_owner_id] if name[ip_protocol] begin[:] call[name[params]][constant[IpPermissions.1.IpProtocol]] assign[=] name[ip_protocol] if compare[name[from_port] is_not constant[None]] begin[:] call[name[params]][constant[IpPermissions.1.FromPort]] assign[=] name[from_port] if compare[name[to_port] is_not constant[None]] begin[:] call[name[params]][constant[IpPermissions.1.ToPort]] assign[=] name[to_port] if name[cidr_ip] begin[:] call[name[params]][constant[IpPermissions.1.IpRanges.1.CidrIp]] assign[=] name[cidr_ip] return[call[name[self].get_status, parameter[constant[RevokeSecurityGroupIngress], name[params]]]]
keyword[def] identifier[revoke_security_group] ( identifier[self] , identifier[group_name] = keyword[None] , identifier[src_security_group_name] = keyword[None] , identifier[src_security_group_owner_id] = keyword[None] , identifier[ip_protocol] = keyword[None] , identifier[from_port] = keyword[None] , identifier[to_port] = keyword[None] , identifier[cidr_ip] = keyword[None] , identifier[group_id] = keyword[None] , identifier[src_security_group_group_id] = keyword[None] ): literal[string] keyword[if] identifier[src_security_group_name] : keyword[if] identifier[from_port] keyword[is] keyword[None] keyword[and] identifier[to_port] keyword[is] keyword[None] keyword[and] identifier[ip_protocol] keyword[is] keyword[None] : keyword[return] identifier[self] . identifier[revoke_security_group_deprecated] ( identifier[group_name] , identifier[src_security_group_name] , identifier[src_security_group_owner_id] ) identifier[params] ={} keyword[if] identifier[group_name] keyword[is] keyword[not] keyword[None] : identifier[params] [ literal[string] ]= identifier[group_name] keyword[if] identifier[group_id] keyword[is] keyword[not] keyword[None] : identifier[params] [ literal[string] ]= identifier[group_id] keyword[if] identifier[src_security_group_name] : identifier[param_name] = literal[string] identifier[params] [ identifier[param_name] ]= identifier[src_security_group_name] keyword[if] identifier[src_security_group_group_id] : identifier[param_name] = literal[string] identifier[params] [ identifier[param_name] ]= identifier[src_security_group_group_id] keyword[if] identifier[src_security_group_owner_id] : identifier[param_name] = literal[string] identifier[params] [ identifier[param_name] ]= identifier[src_security_group_owner_id] keyword[if] identifier[ip_protocol] : identifier[params] [ literal[string] ]= identifier[ip_protocol] keyword[if] identifier[from_port] keyword[is] keyword[not] keyword[None] : identifier[params] [ literal[string] ]= identifier[from_port] keyword[if] identifier[to_port] keyword[is] keyword[not] keyword[None] : identifier[params] [ literal[string] ]= identifier[to_port] keyword[if] identifier[cidr_ip] : identifier[params] [ literal[string] ]= identifier[cidr_ip] keyword[return] identifier[self] . identifier[get_status] ( literal[string] , identifier[params] , identifier[verb] = literal[string] )
def revoke_security_group(self, group_name=None, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, group_id=None, src_security_group_group_id=None): """ Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful. """ if src_security_group_name: if from_port is None and to_port is None and (ip_protocol is None): return self.revoke_security_group_deprecated(group_name, src_security_group_name, src_security_group_owner_id) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] params = {} if group_name is not None: params['GroupName'] = group_name # depends on [control=['if'], data=['group_name']] if group_id is not None: params['GroupId'] = group_id # depends on [control=['if'], data=['group_id']] if src_security_group_name: param_name = 'IpPermissions.1.Groups.1.GroupName' params[param_name] = src_security_group_name # depends on [control=['if'], data=[]] if src_security_group_group_id: param_name = 'IpPermissions.1.Groups.1.GroupId' params[param_name] = src_security_group_group_id # depends on [control=['if'], data=[]] if src_security_group_owner_id: param_name = 'IpPermissions.1.Groups.1.UserId' params[param_name] = src_security_group_owner_id # depends on [control=['if'], data=[]] if ip_protocol: params['IpPermissions.1.IpProtocol'] = ip_protocol # depends on [control=['if'], data=[]] if from_port is not None: params['IpPermissions.1.FromPort'] = from_port # depends on [control=['if'], data=['from_port']] if to_port is not None: params['IpPermissions.1.ToPort'] = to_port # depends on [control=['if'], data=['to_port']] if cidr_ip: params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip # depends on [control=['if'], data=[]] return self.get_status('RevokeSecurityGroupIngress', params, verb='POST')
def has_no_narrow_start(neuron, frac=0.9): '''Check if neurites have a narrow start Arguments: neuron(Neuron): The neuron object to test frac(float): Ratio that the second point must be smaller than the first Returns: CheckResult with a list of all first segments of neurites with a narrow start ''' bad_ids = [(neurite.root_node.id, [neurite.root_node.points[1]]) for neurite in neuron.neurites if neurite.root_node.points[1][COLS.R] < frac * neurite.root_node.points[2][COLS.R]] return CheckResult(len(bad_ids) == 0, bad_ids)
def function[has_no_narrow_start, parameter[neuron, frac]]: constant[Check if neurites have a narrow start Arguments: neuron(Neuron): The neuron object to test frac(float): Ratio that the second point must be smaller than the first Returns: CheckResult with a list of all first segments of neurites with a narrow start ] variable[bad_ids] assign[=] <ast.ListComp object at 0x7da20c76c190> return[call[name[CheckResult], parameter[compare[call[name[len], parameter[name[bad_ids]]] equal[==] constant[0]], name[bad_ids]]]]
keyword[def] identifier[has_no_narrow_start] ( identifier[neuron] , identifier[frac] = literal[int] ): literal[string] identifier[bad_ids] =[( identifier[neurite] . identifier[root_node] . identifier[id] ,[ identifier[neurite] . identifier[root_node] . identifier[points] [ literal[int] ]]) keyword[for] identifier[neurite] keyword[in] identifier[neuron] . identifier[neurites] keyword[if] identifier[neurite] . identifier[root_node] . identifier[points] [ literal[int] ][ identifier[COLS] . identifier[R] ]< identifier[frac] * identifier[neurite] . identifier[root_node] . identifier[points] [ literal[int] ][ identifier[COLS] . identifier[R] ]] keyword[return] identifier[CheckResult] ( identifier[len] ( identifier[bad_ids] )== literal[int] , identifier[bad_ids] )
def has_no_narrow_start(neuron, frac=0.9): """Check if neurites have a narrow start Arguments: neuron(Neuron): The neuron object to test frac(float): Ratio that the second point must be smaller than the first Returns: CheckResult with a list of all first segments of neurites with a narrow start """ bad_ids = [(neurite.root_node.id, [neurite.root_node.points[1]]) for neurite in neuron.neurites if neurite.root_node.points[1][COLS.R] < frac * neurite.root_node.points[2][COLS.R]] return CheckResult(len(bad_ids) == 0, bad_ids)
def traverse_ruffus_exception(exceptions, options, log): """Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples. The RethrownJobException has a list of exceptions like e.job_exceptions = [(5-tuple), (5-tuple), ...] ruffus < 2.7.0 had a bug with exception marshalling that would give different output whether the main or child process raised the exception. We no longer support this. Attempting to log the exception itself will re-marshall it to the logger which is normally running in another process. It's better to avoid re- marshalling. The exit code will be based on this, even if multiple exceptions occurred at the same time.""" exit_codes = [] for exc in exceptions: exit_code = do_ruffus_exception(exc, options, log) exit_codes.append(exit_code) return exit_codes[0]
def function[traverse_ruffus_exception, parameter[exceptions, options, log]]: constant[Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples. The RethrownJobException has a list of exceptions like e.job_exceptions = [(5-tuple), (5-tuple), ...] ruffus < 2.7.0 had a bug with exception marshalling that would give different output whether the main or child process raised the exception. We no longer support this. Attempting to log the exception itself will re-marshall it to the logger which is normally running in another process. It's better to avoid re- marshalling. The exit code will be based on this, even if multiple exceptions occurred at the same time.] variable[exit_codes] assign[=] list[[]] for taget[name[exc]] in starred[name[exceptions]] begin[:] variable[exit_code] assign[=] call[name[do_ruffus_exception], parameter[name[exc], name[options], name[log]]] call[name[exit_codes].append, parameter[name[exit_code]]] return[call[name[exit_codes]][constant[0]]]
keyword[def] identifier[traverse_ruffus_exception] ( identifier[exceptions] , identifier[options] , identifier[log] ): literal[string] identifier[exit_codes] =[] keyword[for] identifier[exc] keyword[in] identifier[exceptions] : identifier[exit_code] = identifier[do_ruffus_exception] ( identifier[exc] , identifier[options] , identifier[log] ) identifier[exit_codes] . identifier[append] ( identifier[exit_code] ) keyword[return] identifier[exit_codes] [ literal[int] ]
def traverse_ruffus_exception(exceptions, options, log): """Traverse a RethrownJobError and output the exceptions Ruffus presents exceptions as 5 element tuples. The RethrownJobException has a list of exceptions like e.job_exceptions = [(5-tuple), (5-tuple), ...] ruffus < 2.7.0 had a bug with exception marshalling that would give different output whether the main or child process raised the exception. We no longer support this. Attempting to log the exception itself will re-marshall it to the logger which is normally running in another process. It's better to avoid re- marshalling. The exit code will be based on this, even if multiple exceptions occurred at the same time.""" exit_codes = [] for exc in exceptions: exit_code = do_ruffus_exception(exc, options, log) exit_codes.append(exit_code) # depends on [control=['for'], data=['exc']] return exit_codes[0]
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: if ( isinstance(decorator, astroid.Attribute) and getattr(decorator.expr, "name", None) == node.name ): return True return False
def function[redefined_by_decorator, parameter[node]]: constant[return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value ] if name[node].decorators begin[:] for taget[name[decorator]] in starred[name[node].decorators.nodes] begin[:] if <ast.BoolOp object at 0x7da1b0245a20> begin[:] return[constant[True]] return[constant[False]]
keyword[def] identifier[redefined_by_decorator] ( identifier[node] ): literal[string] keyword[if] identifier[node] . identifier[decorators] : keyword[for] identifier[decorator] keyword[in] identifier[node] . identifier[decorators] . identifier[nodes] : keyword[if] ( identifier[isinstance] ( identifier[decorator] , identifier[astroid] . identifier[Attribute] ) keyword[and] identifier[getattr] ( identifier[decorator] . identifier[expr] , literal[string] , keyword[None] )== identifier[node] . identifier[name] ): keyword[return] keyword[True] keyword[return] keyword[False]
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: if isinstance(decorator, astroid.Attribute) and getattr(decorator.expr, 'name', None) == node.name: return True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['decorator']] # depends on [control=['if'], data=[]] return False
def train(args): """Training helper.""" vocab, row, col, counts = get_train_data(args) model = GloVe(token_to_idx=vocab.token_to_idx, output_dim=args.emsize, dropout=args.dropout, x_max=args.x_max, alpha=args.alpha, weight_initializer=mx.init.Uniform(scale=1 / args.emsize)) context = get_context(args) model.initialize(ctx=context) if not args.no_hybridize: model.hybridize(static_alloc=not args.no_static_alloc) optimizer_kwargs = dict(learning_rate=args.lr, eps=args.adagrad_eps) params = list(model.collect_params().values()) try: trainer = mx.gluon.Trainer(params, 'groupadagrad', optimizer_kwargs) except ValueError: logging.warning('MXNet <= v1.3 does not contain ' 'GroupAdaGrad support. Falling back to AdaGrad') trainer = mx.gluon.Trainer(params, 'adagrad', optimizer_kwargs) index_dtype = 'int32' if counts.shape[0] >= np.iinfo(np.int32).max: index_dtype = 'int64' logging.info('Co-occurrence matrix is large. ' 'Using int64 to represent sample indices.') indices = mx.nd.arange(counts.shape[0], dtype=index_dtype) for epoch in range(args.epochs): # Logging variables log_wc = 0 log_start_time = time.time() log_avg_loss = 0 mx.nd.shuffle(indices, indices) # inplace shuffle bs = args.batch_size num_batches = indices.shape[0] // bs for i in range(num_batches): batch_indices = indices[bs * i:bs * (i + 1)] ctx = context[i % len(context)] batch_row = row[batch_indices].as_in_context(ctx) batch_col = col[batch_indices].as_in_context(ctx) batch_counts = counts[batch_indices].as_in_context(ctx) with mx.autograd.record(): loss = model(batch_row, batch_col, batch_counts) loss.backward() if len(context) == 1 or (i + 1) % len(context) == 0: trainer.step(batch_size=1) # Logging log_wc += loss.shape[0] log_avg_loss += loss.mean().as_in_context(context[0]) if (i + 1) % args.log_interval == 0: # Forces waiting for computation by computing loss value log_avg_loss = log_avg_loss.asscalar() / args.log_interval wps = log_wc / (time.time() - log_start_time) logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, ' 'throughput={:.2f}K wps, wc={:.2f}K'.format( epoch, i + 1, num_batches, log_avg_loss, wps / 1000, log_wc / 1000)) log_dict = dict( global_step=epoch * len(indices) + i * args.batch_size, epoch=epoch, batch=i + 1, loss=log_avg_loss, wps=wps / 1000) log(args, log_dict) log_start_time = time.time() log_avg_loss = 0 log_wc = 0 if args.eval_interval and (i + 1) % args.eval_interval == 0: with print_time('mx.nd.waitall()'): mx.nd.waitall() with print_time('evaluate'): evaluate(args, model, vocab, i + num_batches * epoch) # Evaluate with print_time('mx.nd.waitall()'): mx.nd.waitall() with print_time('evaluate'): evaluate(args, model, vocab, num_batches * args.epochs, eval_analogy=not args.no_eval_analogy) # Save params with print_time('save parameters'): model.save_parameters(os.path.join(args.logdir, 'glove.params'))
def function[train, parameter[args]]: constant[Training helper.] <ast.Tuple object at 0x7da1b21ea8f0> assign[=] call[name[get_train_data], parameter[name[args]]] variable[model] assign[=] call[name[GloVe], parameter[]] variable[context] assign[=] call[name[get_context], parameter[name[args]]] call[name[model].initialize, parameter[]] if <ast.UnaryOp object at 0x7da1b21eb490> begin[:] call[name[model].hybridize, parameter[]] variable[optimizer_kwargs] assign[=] call[name[dict], parameter[]] variable[params] assign[=] call[name[list], parameter[call[call[name[model].collect_params, parameter[]].values, parameter[]]]] <ast.Try object at 0x7da1b21eb7c0> variable[index_dtype] assign[=] constant[int32] if compare[call[name[counts].shape][constant[0]] greater_or_equal[>=] call[name[np].iinfo, parameter[name[np].int32]].max] begin[:] variable[index_dtype] assign[=] constant[int64] call[name[logging].info, parameter[constant[Co-occurrence matrix is large. Using int64 to represent sample indices.]]] variable[indices] assign[=] call[name[mx].nd.arange, parameter[call[name[counts].shape][constant[0]]]] for taget[name[epoch]] in starred[call[name[range], parameter[name[args].epochs]]] begin[:] variable[log_wc] assign[=] constant[0] variable[log_start_time] assign[=] call[name[time].time, parameter[]] variable[log_avg_loss] assign[=] constant[0] call[name[mx].nd.shuffle, parameter[name[indices], name[indices]]] variable[bs] assign[=] name[args].batch_size variable[num_batches] assign[=] binary_operation[call[name[indices].shape][constant[0]] <ast.FloorDiv object at 0x7da2590d6bc0> name[bs]] for taget[name[i]] in starred[call[name[range], parameter[name[num_batches]]]] begin[:] variable[batch_indices] assign[=] call[name[indices]][<ast.Slice object at 0x7da1b21ea020>] variable[ctx] assign[=] call[name[context]][binary_operation[name[i] <ast.Mod object at 0x7da2590d6920> call[name[len], parameter[name[context]]]]] variable[batch_row] assign[=] call[call[name[row]][name[batch_indices]].as_in_context, parameter[name[ctx]]] variable[batch_col] assign[=] call[call[name[col]][name[batch_indices]].as_in_context, parameter[name[ctx]]] variable[batch_counts] assign[=] call[call[name[counts]][name[batch_indices]].as_in_context, parameter[name[ctx]]] with call[name[mx].autograd.record, parameter[]] begin[:] variable[loss] assign[=] call[name[model], parameter[name[batch_row], name[batch_col], name[batch_counts]]] call[name[loss].backward, parameter[]] if <ast.BoolOp object at 0x7da1b21e9270> begin[:] call[name[trainer].step, parameter[]] <ast.AugAssign object at 0x7da1b21e9b10> <ast.AugAssign object at 0x7da1b21e9540> if compare[binary_operation[binary_operation[name[i] + constant[1]] <ast.Mod object at 0x7da2590d6920> name[args].log_interval] equal[==] constant[0]] begin[:] variable[log_avg_loss] assign[=] binary_operation[call[name[log_avg_loss].asscalar, parameter[]] / name[args].log_interval] variable[wps] assign[=] binary_operation[name[log_wc] / binary_operation[call[name[time].time, parameter[]] - name[log_start_time]]] call[name[logging].info, parameter[call[constant[[Epoch {} Batch {}/{}] loss={:.4f}, throughput={:.2f}K wps, wc={:.2f}K].format, parameter[name[epoch], binary_operation[name[i] + constant[1]], name[num_batches], name[log_avg_loss], binary_operation[name[wps] / constant[1000]], binary_operation[name[log_wc] / constant[1000]]]]]] variable[log_dict] assign[=] call[name[dict], parameter[]] call[name[log], parameter[name[args], name[log_dict]]] variable[log_start_time] assign[=] call[name[time].time, parameter[]] variable[log_avg_loss] assign[=] constant[0] variable[log_wc] assign[=] constant[0] if <ast.BoolOp object at 0x7da18c4cddb0> begin[:] with call[name[print_time], parameter[constant[mx.nd.waitall()]]] begin[:] call[name[mx].nd.waitall, parameter[]] with call[name[print_time], parameter[constant[evaluate]]] begin[:] call[name[evaluate], parameter[name[args], name[model], name[vocab], binary_operation[name[i] + binary_operation[name[num_batches] * name[epoch]]]]] with call[name[print_time], parameter[constant[mx.nd.waitall()]]] begin[:] call[name[mx].nd.waitall, parameter[]] with call[name[print_time], parameter[constant[evaluate]]] begin[:] call[name[evaluate], parameter[name[args], name[model], name[vocab], binary_operation[name[num_batches] * name[args].epochs]]] with call[name[print_time], parameter[constant[save parameters]]] begin[:] call[name[model].save_parameters, parameter[call[name[os].path.join, parameter[name[args].logdir, constant[glove.params]]]]]
keyword[def] identifier[train] ( identifier[args] ): literal[string] identifier[vocab] , identifier[row] , identifier[col] , identifier[counts] = identifier[get_train_data] ( identifier[args] ) identifier[model] = identifier[GloVe] ( identifier[token_to_idx] = identifier[vocab] . identifier[token_to_idx] , identifier[output_dim] = identifier[args] . identifier[emsize] , identifier[dropout] = identifier[args] . identifier[dropout] , identifier[x_max] = identifier[args] . identifier[x_max] , identifier[alpha] = identifier[args] . identifier[alpha] , identifier[weight_initializer] = identifier[mx] . identifier[init] . identifier[Uniform] ( identifier[scale] = literal[int] / identifier[args] . identifier[emsize] )) identifier[context] = identifier[get_context] ( identifier[args] ) identifier[model] . identifier[initialize] ( identifier[ctx] = identifier[context] ) keyword[if] keyword[not] identifier[args] . identifier[no_hybridize] : identifier[model] . identifier[hybridize] ( identifier[static_alloc] = keyword[not] identifier[args] . identifier[no_static_alloc] ) identifier[optimizer_kwargs] = identifier[dict] ( identifier[learning_rate] = identifier[args] . identifier[lr] , identifier[eps] = identifier[args] . identifier[adagrad_eps] ) identifier[params] = identifier[list] ( identifier[model] . identifier[collect_params] (). identifier[values] ()) keyword[try] : identifier[trainer] = identifier[mx] . identifier[gluon] . identifier[Trainer] ( identifier[params] , literal[string] , identifier[optimizer_kwargs] ) keyword[except] identifier[ValueError] : identifier[logging] . identifier[warning] ( literal[string] literal[string] ) identifier[trainer] = identifier[mx] . identifier[gluon] . identifier[Trainer] ( identifier[params] , literal[string] , identifier[optimizer_kwargs] ) identifier[index_dtype] = literal[string] keyword[if] identifier[counts] . identifier[shape] [ literal[int] ]>= identifier[np] . identifier[iinfo] ( identifier[np] . identifier[int32] ). identifier[max] : identifier[index_dtype] = literal[string] identifier[logging] . identifier[info] ( literal[string] literal[string] ) identifier[indices] = identifier[mx] . identifier[nd] . identifier[arange] ( identifier[counts] . identifier[shape] [ literal[int] ], identifier[dtype] = identifier[index_dtype] ) keyword[for] identifier[epoch] keyword[in] identifier[range] ( identifier[args] . identifier[epochs] ): identifier[log_wc] = literal[int] identifier[log_start_time] = identifier[time] . identifier[time] () identifier[log_avg_loss] = literal[int] identifier[mx] . identifier[nd] . identifier[shuffle] ( identifier[indices] , identifier[indices] ) identifier[bs] = identifier[args] . identifier[batch_size] identifier[num_batches] = identifier[indices] . identifier[shape] [ literal[int] ]// identifier[bs] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[num_batches] ): identifier[batch_indices] = identifier[indices] [ identifier[bs] * identifier[i] : identifier[bs] *( identifier[i] + literal[int] )] identifier[ctx] = identifier[context] [ identifier[i] % identifier[len] ( identifier[context] )] identifier[batch_row] = identifier[row] [ identifier[batch_indices] ]. identifier[as_in_context] ( identifier[ctx] ) identifier[batch_col] = identifier[col] [ identifier[batch_indices] ]. identifier[as_in_context] ( identifier[ctx] ) identifier[batch_counts] = identifier[counts] [ identifier[batch_indices] ]. identifier[as_in_context] ( identifier[ctx] ) keyword[with] identifier[mx] . identifier[autograd] . identifier[record] (): identifier[loss] = identifier[model] ( identifier[batch_row] , identifier[batch_col] , identifier[batch_counts] ) identifier[loss] . identifier[backward] () keyword[if] identifier[len] ( identifier[context] )== literal[int] keyword[or] ( identifier[i] + literal[int] )% identifier[len] ( identifier[context] )== literal[int] : identifier[trainer] . identifier[step] ( identifier[batch_size] = literal[int] ) identifier[log_wc] += identifier[loss] . identifier[shape] [ literal[int] ] identifier[log_avg_loss] += identifier[loss] . identifier[mean] (). identifier[as_in_context] ( identifier[context] [ literal[int] ]) keyword[if] ( identifier[i] + literal[int] )% identifier[args] . identifier[log_interval] == literal[int] : identifier[log_avg_loss] = identifier[log_avg_loss] . identifier[asscalar] ()/ identifier[args] . identifier[log_interval] identifier[wps] = identifier[log_wc] /( identifier[time] . identifier[time] ()- identifier[log_start_time] ) identifier[logging] . identifier[info] ( literal[string] literal[string] . identifier[format] ( identifier[epoch] , identifier[i] + literal[int] , identifier[num_batches] , identifier[log_avg_loss] , identifier[wps] / literal[int] , identifier[log_wc] / literal[int] )) identifier[log_dict] = identifier[dict] ( identifier[global_step] = identifier[epoch] * identifier[len] ( identifier[indices] )+ identifier[i] * identifier[args] . identifier[batch_size] , identifier[epoch] = identifier[epoch] , identifier[batch] = identifier[i] + literal[int] , identifier[loss] = identifier[log_avg_loss] , identifier[wps] = identifier[wps] / literal[int] ) identifier[log] ( identifier[args] , identifier[log_dict] ) identifier[log_start_time] = identifier[time] . identifier[time] () identifier[log_avg_loss] = literal[int] identifier[log_wc] = literal[int] keyword[if] identifier[args] . identifier[eval_interval] keyword[and] ( identifier[i] + literal[int] )% identifier[args] . identifier[eval_interval] == literal[int] : keyword[with] identifier[print_time] ( literal[string] ): identifier[mx] . identifier[nd] . identifier[waitall] () keyword[with] identifier[print_time] ( literal[string] ): identifier[evaluate] ( identifier[args] , identifier[model] , identifier[vocab] , identifier[i] + identifier[num_batches] * identifier[epoch] ) keyword[with] identifier[print_time] ( literal[string] ): identifier[mx] . identifier[nd] . identifier[waitall] () keyword[with] identifier[print_time] ( literal[string] ): identifier[evaluate] ( identifier[args] , identifier[model] , identifier[vocab] , identifier[num_batches] * identifier[args] . identifier[epochs] , identifier[eval_analogy] = keyword[not] identifier[args] . identifier[no_eval_analogy] ) keyword[with] identifier[print_time] ( literal[string] ): identifier[model] . identifier[save_parameters] ( identifier[os] . identifier[path] . identifier[join] ( identifier[args] . identifier[logdir] , literal[string] ))
def train(args): """Training helper.""" (vocab, row, col, counts) = get_train_data(args) model = GloVe(token_to_idx=vocab.token_to_idx, output_dim=args.emsize, dropout=args.dropout, x_max=args.x_max, alpha=args.alpha, weight_initializer=mx.init.Uniform(scale=1 / args.emsize)) context = get_context(args) model.initialize(ctx=context) if not args.no_hybridize: model.hybridize(static_alloc=not args.no_static_alloc) # depends on [control=['if'], data=[]] optimizer_kwargs = dict(learning_rate=args.lr, eps=args.adagrad_eps) params = list(model.collect_params().values()) try: trainer = mx.gluon.Trainer(params, 'groupadagrad', optimizer_kwargs) # depends on [control=['try'], data=[]] except ValueError: logging.warning('MXNet <= v1.3 does not contain GroupAdaGrad support. Falling back to AdaGrad') trainer = mx.gluon.Trainer(params, 'adagrad', optimizer_kwargs) # depends on [control=['except'], data=[]] index_dtype = 'int32' if counts.shape[0] >= np.iinfo(np.int32).max: index_dtype = 'int64' logging.info('Co-occurrence matrix is large. Using int64 to represent sample indices.') # depends on [control=['if'], data=[]] indices = mx.nd.arange(counts.shape[0], dtype=index_dtype) for epoch in range(args.epochs): # Logging variables log_wc = 0 log_start_time = time.time() log_avg_loss = 0 mx.nd.shuffle(indices, indices) # inplace shuffle bs = args.batch_size num_batches = indices.shape[0] // bs for i in range(num_batches): batch_indices = indices[bs * i:bs * (i + 1)] ctx = context[i % len(context)] batch_row = row[batch_indices].as_in_context(ctx) batch_col = col[batch_indices].as_in_context(ctx) batch_counts = counts[batch_indices].as_in_context(ctx) with mx.autograd.record(): loss = model(batch_row, batch_col, batch_counts) loss.backward() # depends on [control=['with'], data=[]] if len(context) == 1 or (i + 1) % len(context) == 0: trainer.step(batch_size=1) # depends on [control=['if'], data=[]] # Logging log_wc += loss.shape[0] log_avg_loss += loss.mean().as_in_context(context[0]) if (i + 1) % args.log_interval == 0: # Forces waiting for computation by computing loss value log_avg_loss = log_avg_loss.asscalar() / args.log_interval wps = log_wc / (time.time() - log_start_time) logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, throughput={:.2f}K wps, wc={:.2f}K'.format(epoch, i + 1, num_batches, log_avg_loss, wps / 1000, log_wc / 1000)) log_dict = dict(global_step=epoch * len(indices) + i * args.batch_size, epoch=epoch, batch=i + 1, loss=log_avg_loss, wps=wps / 1000) log(args, log_dict) log_start_time = time.time() log_avg_loss = 0 log_wc = 0 # depends on [control=['if'], data=[]] if args.eval_interval and (i + 1) % args.eval_interval == 0: with print_time('mx.nd.waitall()'): mx.nd.waitall() # depends on [control=['with'], data=[]] with print_time('evaluate'): evaluate(args, model, vocab, i + num_batches * epoch) # depends on [control=['with'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['i']] # depends on [control=['for'], data=['epoch']] # Evaluate with print_time('mx.nd.waitall()'): mx.nd.waitall() # depends on [control=['with'], data=[]] with print_time('evaluate'): evaluate(args, model, vocab, num_batches * args.epochs, eval_analogy=not args.no_eval_analogy) # depends on [control=['with'], data=[]] # Save params with print_time('save parameters'): model.save_parameters(os.path.join(args.logdir, 'glove.params')) # depends on [control=['with'], data=[]]
def get_url(width, height, color=True): """ Craft the URL for a placekitten image. By default they are in color. To retrieve a grayscale image, set the color kwarg to False. """ d = dict(width=width, height=height) return URL % d
def function[get_url, parameter[width, height, color]]: constant[ Craft the URL for a placekitten image. By default they are in color. To retrieve a grayscale image, set the color kwarg to False. ] variable[d] assign[=] call[name[dict], parameter[]] return[binary_operation[name[URL] <ast.Mod object at 0x7da2590d6920> name[d]]]
keyword[def] identifier[get_url] ( identifier[width] , identifier[height] , identifier[color] = keyword[True] ): literal[string] identifier[d] = identifier[dict] ( identifier[width] = identifier[width] , identifier[height] = identifier[height] ) keyword[return] identifier[URL] % identifier[d]
def get_url(width, height, color=True): """ Craft the URL for a placekitten image. By default they are in color. To retrieve a grayscale image, set the color kwarg to False. """ d = dict(width=width, height=height) return URL % d
def call_sync(self, name, args, timeout=None): """ Blocking version of :meth:`call`. :type name: str :arg name: Remote function name to call. :type args: list :arg args: Arguments passed to the remote function. :type timeout: int or None :arg timeout: Timeout in second. None means no timeout. If the called remote function raise an exception, this method raise an exception. If you give `timeout`, this method may raise an `Empty` exception. """ return self._blocking_request(self.call, timeout, name, args)
def function[call_sync, parameter[self, name, args, timeout]]: constant[ Blocking version of :meth:`call`. :type name: str :arg name: Remote function name to call. :type args: list :arg args: Arguments passed to the remote function. :type timeout: int or None :arg timeout: Timeout in second. None means no timeout. If the called remote function raise an exception, this method raise an exception. If you give `timeout`, this method may raise an `Empty` exception. ] return[call[name[self]._blocking_request, parameter[name[self].call, name[timeout], name[name], name[args]]]]
keyword[def] identifier[call_sync] ( identifier[self] , identifier[name] , identifier[args] , identifier[timeout] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[_blocking_request] ( identifier[self] . identifier[call] , identifier[timeout] , identifier[name] , identifier[args] )
def call_sync(self, name, args, timeout=None): """ Blocking version of :meth:`call`. :type name: str :arg name: Remote function name to call. :type args: list :arg args: Arguments passed to the remote function. :type timeout: int or None :arg timeout: Timeout in second. None means no timeout. If the called remote function raise an exception, this method raise an exception. If you give `timeout`, this method may raise an `Empty` exception. """ return self._blocking_request(self.call, timeout, name, args)
def get_go2obj(self, goids): """Return GO Terms for each user-specified GO ID. Note missing GO IDs.""" goids = goids.intersection(self.go2obj.keys()) if len(goids) != len(goids): goids_missing = goids.difference(goids) print(" {N} MISSING GO IDs: {GOs}".format(N=len(goids_missing), GOs=goids_missing)) return {go:self.go2obj[go] for go in goids}
def function[get_go2obj, parameter[self, goids]]: constant[Return GO Terms for each user-specified GO ID. Note missing GO IDs.] variable[goids] assign[=] call[name[goids].intersection, parameter[call[name[self].go2obj.keys, parameter[]]]] if compare[call[name[len], parameter[name[goids]]] not_equal[!=] call[name[len], parameter[name[goids]]]] begin[:] variable[goids_missing] assign[=] call[name[goids].difference, parameter[name[goids]]] call[name[print], parameter[call[constant[ {N} MISSING GO IDs: {GOs}].format, parameter[]]]] return[<ast.DictComp object at 0x7da20c6abb20>]
keyword[def] identifier[get_go2obj] ( identifier[self] , identifier[goids] ): literal[string] identifier[goids] = identifier[goids] . identifier[intersection] ( identifier[self] . identifier[go2obj] . identifier[keys] ()) keyword[if] identifier[len] ( identifier[goids] )!= identifier[len] ( identifier[goids] ): identifier[goids_missing] = identifier[goids] . identifier[difference] ( identifier[goids] ) identifier[print] ( literal[string] . identifier[format] ( identifier[N] = identifier[len] ( identifier[goids_missing] ), identifier[GOs] = identifier[goids_missing] )) keyword[return] { identifier[go] : identifier[self] . identifier[go2obj] [ identifier[go] ] keyword[for] identifier[go] keyword[in] identifier[goids] }
def get_go2obj(self, goids): """Return GO Terms for each user-specified GO ID. Note missing GO IDs.""" goids = goids.intersection(self.go2obj.keys()) if len(goids) != len(goids): goids_missing = goids.difference(goids) print(' {N} MISSING GO IDs: {GOs}'.format(N=len(goids_missing), GOs=goids_missing)) # depends on [control=['if'], data=[]] return {go: self.go2obj[go] for go in goids}
def _prep_inputs(vrn_info, cnv_info, somatic_info, work_dir, config): """Prepare inputs for running PhyloWGS from variant and CNV calls. """ exe = os.path.join(os.path.dirname(sys.executable), "create_phylowgs_inputs.py") assert os.path.exists(exe), "Could not find input prep script for PhyloWGS runs." ssm_file = os.path.join(work_dir, "ssm_data.txt") cnv_file = os.path.join(work_dir, "cnv_data.txt") if not utils.file_exists(ssm_file) or not utils.file_exists(cnv_file): with file_transaction(somatic_info.tumor_data, ssm_file, cnv_file) as (tx_ssm_file, tx_cnv_file): variant_type, input_vcf_file = _prep_vrn_file(vrn_info["vrn_file"], vrn_info["variantcaller"], work_dir, somatic_info, cnv_info["ignore"], config) input_cnv_file = _prep_cnv_file(cnv_info["subclones"], work_dir, somatic_info) cmd = [sys.executable, exe, "--sample-size", str(config["sample_size"]), "--tumor-sample", somatic_info.tumor_name, "--battenberg", input_cnv_file, "--cellularity", _read_contam(cnv_info["contamination"]), "--output-cnvs", tx_cnv_file, "--output-variants", tx_ssm_file, "--variant-type", variant_type, input_vcf_file] do.run(cmd, "Prepare PhyloWGS inputs.") return ssm_file, cnv_file
def function[_prep_inputs, parameter[vrn_info, cnv_info, somatic_info, work_dir, config]]: constant[Prepare inputs for running PhyloWGS from variant and CNV calls. ] variable[exe] assign[=] call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[sys].executable]], constant[create_phylowgs_inputs.py]]] assert[call[name[os].path.exists, parameter[name[exe]]]] variable[ssm_file] assign[=] call[name[os].path.join, parameter[name[work_dir], constant[ssm_data.txt]]] variable[cnv_file] assign[=] call[name[os].path.join, parameter[name[work_dir], constant[cnv_data.txt]]] if <ast.BoolOp object at 0x7da1b17a6b60> begin[:] with call[name[file_transaction], parameter[name[somatic_info].tumor_data, name[ssm_file], name[cnv_file]]] begin[:] <ast.Tuple object at 0x7da1b18858a0> assign[=] call[name[_prep_vrn_file], parameter[call[name[vrn_info]][constant[vrn_file]], call[name[vrn_info]][constant[variantcaller]], name[work_dir], name[somatic_info], call[name[cnv_info]][constant[ignore]], name[config]]] variable[input_cnv_file] assign[=] call[name[_prep_cnv_file], parameter[call[name[cnv_info]][constant[subclones]], name[work_dir], name[somatic_info]]] variable[cmd] assign[=] list[[<ast.Attribute object at 0x7da1b18877c0>, <ast.Name object at 0x7da1b1884ee0>, <ast.Constant object at 0x7da1b1885690>, <ast.Call object at 0x7da1b1885c00>, <ast.Constant object at 0x7da1b1884fd0>, <ast.Attribute object at 0x7da1b1884640>, <ast.Constant object at 0x7da1b1886200>, <ast.Name object at 0x7da1b1884be0>, <ast.Constant object at 0x7da1b1885f30>, <ast.Call object at 0x7da1b1884c70>, <ast.Constant object at 0x7da1b1884fa0>, <ast.Name object at 0x7da1b1887640>, <ast.Constant object at 0x7da1b1886260>, <ast.Name object at 0x7da1b18860b0>, <ast.Constant object at 0x7da1b1887dc0>, <ast.Name object at 0x7da1b18856f0>, <ast.Name object at 0x7da1b1885b70>]] call[name[do].run, parameter[name[cmd], constant[Prepare PhyloWGS inputs.]]] return[tuple[[<ast.Name object at 0x7da1b18858d0>, <ast.Name object at 0x7da1b18845b0>]]]
keyword[def] identifier[_prep_inputs] ( identifier[vrn_info] , identifier[cnv_info] , identifier[somatic_info] , identifier[work_dir] , identifier[config] ): literal[string] identifier[exe] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[sys] . identifier[executable] ), literal[string] ) keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[exe] ), literal[string] identifier[ssm_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[work_dir] , literal[string] ) identifier[cnv_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[work_dir] , literal[string] ) keyword[if] keyword[not] identifier[utils] . identifier[file_exists] ( identifier[ssm_file] ) keyword[or] keyword[not] identifier[utils] . identifier[file_exists] ( identifier[cnv_file] ): keyword[with] identifier[file_transaction] ( identifier[somatic_info] . identifier[tumor_data] , identifier[ssm_file] , identifier[cnv_file] ) keyword[as] ( identifier[tx_ssm_file] , identifier[tx_cnv_file] ): identifier[variant_type] , identifier[input_vcf_file] = identifier[_prep_vrn_file] ( identifier[vrn_info] [ literal[string] ], identifier[vrn_info] [ literal[string] ], identifier[work_dir] , identifier[somatic_info] , identifier[cnv_info] [ literal[string] ], identifier[config] ) identifier[input_cnv_file] = identifier[_prep_cnv_file] ( identifier[cnv_info] [ literal[string] ], identifier[work_dir] , identifier[somatic_info] ) identifier[cmd] =[ identifier[sys] . identifier[executable] , identifier[exe] , literal[string] , identifier[str] ( identifier[config] [ literal[string] ]), literal[string] , identifier[somatic_info] . identifier[tumor_name] , literal[string] , identifier[input_cnv_file] , literal[string] , identifier[_read_contam] ( identifier[cnv_info] [ literal[string] ]), literal[string] , identifier[tx_cnv_file] , literal[string] , identifier[tx_ssm_file] , literal[string] , identifier[variant_type] , identifier[input_vcf_file] ] identifier[do] . identifier[run] ( identifier[cmd] , literal[string] ) keyword[return] identifier[ssm_file] , identifier[cnv_file]
def _prep_inputs(vrn_info, cnv_info, somatic_info, work_dir, config): """Prepare inputs for running PhyloWGS from variant and CNV calls. """ exe = os.path.join(os.path.dirname(sys.executable), 'create_phylowgs_inputs.py') assert os.path.exists(exe), 'Could not find input prep script for PhyloWGS runs.' ssm_file = os.path.join(work_dir, 'ssm_data.txt') cnv_file = os.path.join(work_dir, 'cnv_data.txt') if not utils.file_exists(ssm_file) or not utils.file_exists(cnv_file): with file_transaction(somatic_info.tumor_data, ssm_file, cnv_file) as (tx_ssm_file, tx_cnv_file): (variant_type, input_vcf_file) = _prep_vrn_file(vrn_info['vrn_file'], vrn_info['variantcaller'], work_dir, somatic_info, cnv_info['ignore'], config) input_cnv_file = _prep_cnv_file(cnv_info['subclones'], work_dir, somatic_info) cmd = [sys.executable, exe, '--sample-size', str(config['sample_size']), '--tumor-sample', somatic_info.tumor_name, '--battenberg', input_cnv_file, '--cellularity', _read_contam(cnv_info['contamination']), '--output-cnvs', tx_cnv_file, '--output-variants', tx_ssm_file, '--variant-type', variant_type, input_vcf_file] do.run(cmd, 'Prepare PhyloWGS inputs.') # depends on [control=['with'], data=[]] # depends on [control=['if'], data=[]] return (ssm_file, cnv_file)
def vote_witness(self, witness, account=None): ''' Uses the steem_instance method to vote on a witness. ''' if not account: account = self.mainaccount try: self.steem_instance().approve_witness(witness, account=account) except Exception as e: self.msg.error_message("COULD NOT VOTE " + witness + " AS WITNESS: " + e) return False else: return True
def function[vote_witness, parameter[self, witness, account]]: constant[ Uses the steem_instance method to vote on a witness. ] if <ast.UnaryOp object at 0x7da1b16e2530> begin[:] variable[account] assign[=] name[self].mainaccount <ast.Try object at 0x7da1b16e3eb0>
keyword[def] identifier[vote_witness] ( identifier[self] , identifier[witness] , identifier[account] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[account] : identifier[account] = identifier[self] . identifier[mainaccount] keyword[try] : identifier[self] . identifier[steem_instance] (). identifier[approve_witness] ( identifier[witness] , identifier[account] = identifier[account] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[msg] . identifier[error_message] ( literal[string] + identifier[witness] + literal[string] + identifier[e] ) keyword[return] keyword[False] keyword[else] : keyword[return] keyword[True]
def vote_witness(self, witness, account=None): """ Uses the steem_instance method to vote on a witness. """ if not account: account = self.mainaccount # depends on [control=['if'], data=[]] try: self.steem_instance().approve_witness(witness, account=account) # depends on [control=['try'], data=[]] except Exception as e: self.msg.error_message('COULD NOT VOTE ' + witness + ' AS WITNESS: ' + e) return False # depends on [control=['except'], data=['e']] else: return True
def main(): """Start persister.""" config.parse_args() # Add processors for metrics topic if cfg.CONF.kafka_metrics.enabled: prepare_processes(cfg.CONF.kafka_metrics, cfg.CONF.repositories.metrics_driver) # Add processors for alarm history topic if cfg.CONF.kafka_alarm_history.enabled: prepare_processes(cfg.CONF.kafka_alarm_history, cfg.CONF.repositories.alarm_state_history_driver) # Add processors for events topic if cfg.CONF.kafka_events.enabled: prepare_processes(cfg.CONF.kafka_events, cfg.CONF.repositories.events_driver) # Start try: LOG.info(''' _____ / \ ____ ____ _____ ______ ____ _____ / \ / \ / _ \ / \\\__ \ / ___// ___\\\__ \\ / Y ( <_> ) | \/ __ \_\___ \\ \___ / __ \\_ \____|__ /\____/|___| (____ /____ >\___ >____ / \/ \/ \/ \/ \/ \/ __________ .__ __ \______ \ ___________ _____|__| _______/ |_ ___________ | ___// __ \_ __ \/ ___/ |/ ___/\ __\/ __ \_ __ \\ | | \ ___/| | \/\___ \| |\___ \ | | \ ___/| | \/ |____| \___ >__| /____ >__/____ > |__| \___ >__| \/ \/ \/ \/ ''') for process in processors: process.start() # The signal handlers must be added after the processes start otherwise # they run on all processes signal.signal(signal.SIGCHLD, clean_exit) signal.signal(signal.SIGINT, clean_exit) signal.signal(signal.SIGTERM, clean_exit) while True: time.sleep(10) except Exception: LOG.exception('Error! Exiting.') clean_exit(signal.SIGKILL)
def function[main, parameter[]]: constant[Start persister.] call[name[config].parse_args, parameter[]] if name[cfg].CONF.kafka_metrics.enabled begin[:] call[name[prepare_processes], parameter[name[cfg].CONF.kafka_metrics, name[cfg].CONF.repositories.metrics_driver]] if name[cfg].CONF.kafka_alarm_history.enabled begin[:] call[name[prepare_processes], parameter[name[cfg].CONF.kafka_alarm_history, name[cfg].CONF.repositories.alarm_state_history_driver]] if name[cfg].CONF.kafka_events.enabled begin[:] call[name[prepare_processes], parameter[name[cfg].CONF.kafka_events, name[cfg].CONF.repositories.events_driver]] <ast.Try object at 0x7da1b0b5bd00>
keyword[def] identifier[main] (): literal[string] identifier[config] . identifier[parse_args] () keyword[if] identifier[cfg] . identifier[CONF] . identifier[kafka_metrics] . identifier[enabled] : identifier[prepare_processes] ( identifier[cfg] . identifier[CONF] . identifier[kafka_metrics] , identifier[cfg] . identifier[CONF] . identifier[repositories] . identifier[metrics_driver] ) keyword[if] identifier[cfg] . identifier[CONF] . identifier[kafka_alarm_history] . identifier[enabled] : identifier[prepare_processes] ( identifier[cfg] . identifier[CONF] . identifier[kafka_alarm_history] , identifier[cfg] . identifier[CONF] . identifier[repositories] . identifier[alarm_state_history_driver] ) keyword[if] identifier[cfg] . identifier[CONF] . identifier[kafka_events] . identifier[enabled] : identifier[prepare_processes] ( identifier[cfg] . identifier[CONF] . identifier[kafka_events] , identifier[cfg] . identifier[CONF] . identifier[repositories] . identifier[events_driver] ) keyword[try] : identifier[LOG] . identifier[info] ( literal[string] ) keyword[for] identifier[process] keyword[in] identifier[processors] : identifier[process] . identifier[start] () identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIGCHLD] , identifier[clean_exit] ) identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIGINT] , identifier[clean_exit] ) identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIGTERM] , identifier[clean_exit] ) keyword[while] keyword[True] : identifier[time] . identifier[sleep] ( literal[int] ) keyword[except] identifier[Exception] : identifier[LOG] . identifier[exception] ( literal[string] ) identifier[clean_exit] ( identifier[signal] . identifier[SIGKILL] )
def main(): """Start persister.""" config.parse_args() # Add processors for metrics topic if cfg.CONF.kafka_metrics.enabled: prepare_processes(cfg.CONF.kafka_metrics, cfg.CONF.repositories.metrics_driver) # depends on [control=['if'], data=[]] # Add processors for alarm history topic if cfg.CONF.kafka_alarm_history.enabled: prepare_processes(cfg.CONF.kafka_alarm_history, cfg.CONF.repositories.alarm_state_history_driver) # depends on [control=['if'], data=[]] # Add processors for events topic if cfg.CONF.kafka_events.enabled: prepare_processes(cfg.CONF.kafka_events, cfg.CONF.repositories.events_driver) # depends on [control=['if'], data=[]] # Start try: LOG.info('\n\n _____\n / \\ ____ ____ _____ ______ ____ _____\n / \\ / \\ / _ \\ / \\\\__ \\ / ___// ___\\\\__ \\\n / Y ( <_> ) | \\/ __ \\_\\___ \\ \\___ / __ \\_\n \\____|__ /\\____/|___| (____ /____ >\\___ >____ /\n \\/ \\/ \\/ \\/ \\/ \\/\n __________ .__ __\n \\______ \\ ___________ _____|__| _______/ |_ ___________\n | ___// __ \\_ __ \\/ ___/ |/ ___/\\ __\\/ __ \\_ __ \\\n | | \\ ___/| | \\/\\___ \\| |\\___ \\ | | \\ ___/| | \\/\n |____| \\___ >__| /____ >__/____ > |__| \\___ >__|\n \\/ \\/ \\/ \\/\n\n ') for process in processors: process.start() # depends on [control=['for'], data=['process']] # The signal handlers must be added after the processes start otherwise # they run on all processes signal.signal(signal.SIGCHLD, clean_exit) signal.signal(signal.SIGINT, clean_exit) signal.signal(signal.SIGTERM, clean_exit) while True: time.sleep(10) # depends on [control=['while'], data=[]] # depends on [control=['try'], data=[]] except Exception: LOG.exception('Error! Exiting.') clean_exit(signal.SIGKILL) # depends on [control=['except'], data=[]]
def is_hash_in_index(self, filehash): """ Check if there is a document using this file hash """ filehash = (u"%X" % filehash) results = self.__searcher.search( whoosh.query.Term('docfilehash', filehash)) return bool(results)
def function[is_hash_in_index, parameter[self, filehash]]: constant[ Check if there is a document using this file hash ] variable[filehash] assign[=] binary_operation[constant[%X] <ast.Mod object at 0x7da2590d6920> name[filehash]] variable[results] assign[=] call[name[self].__searcher.search, parameter[call[name[whoosh].query.Term, parameter[constant[docfilehash], name[filehash]]]]] return[call[name[bool], parameter[name[results]]]]
keyword[def] identifier[is_hash_in_index] ( identifier[self] , identifier[filehash] ): literal[string] identifier[filehash] =( literal[string] % identifier[filehash] ) identifier[results] = identifier[self] . identifier[__searcher] . identifier[search] ( identifier[whoosh] . identifier[query] . identifier[Term] ( literal[string] , identifier[filehash] )) keyword[return] identifier[bool] ( identifier[results] )
def is_hash_in_index(self, filehash): """ Check if there is a document using this file hash """ filehash = u'%X' % filehash results = self.__searcher.search(whoosh.query.Term('docfilehash', filehash)) return bool(results)
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) return value
def function[coerce, parameter[self, value]]: constant[Coerce a cleaned value.] if compare[name[self]._coerce is_not constant[None]] begin[:] variable[value] assign[=] call[name[self]._coerce, parameter[name[value]]] return[name[value]]
keyword[def] identifier[coerce] ( identifier[self] , identifier[value] ): literal[string] keyword[if] identifier[self] . identifier[_coerce] keyword[is] keyword[not] keyword[None] : identifier[value] = identifier[self] . identifier[_coerce] ( identifier[value] ) keyword[return] identifier[value]
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) # depends on [control=['if'], data=[]] return value