code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _get_stmt_matching_groups(stmts):
"""Use the matches_key method to get sets of matching statements."""
def match_func(x): return x.matches_key()
# Remove exact duplicates using a set() call, then make copies:
logger.debug('%d statements before removing object duplicates.' %
... | def function[_get_stmt_matching_groups, parameter[stmts]]:
constant[Use the matches_key method to get sets of matching statements.]
def function[match_func, parameter[x]]:
return[call[name[x].matches_key, parameter[]]]
call[name[logger].debug, parameter[binary_operation[constant[%d state... | keyword[def] identifier[_get_stmt_matching_groups] ( identifier[stmts] ):
literal[string]
keyword[def] identifier[match_func] ( identifier[x] ): keyword[return] identifier[x] . identifier[matches_key] ()
identifier[logger] . identifier[debug] ( literal[string] %
identi... | def _get_stmt_matching_groups(stmts):
"""Use the matches_key method to get sets of matching statements."""
def match_func(x):
return x.matches_key()
# Remove exact duplicates using a set() call, then make copies:
logger.debug('%d statements before removing object duplicates.' % len(stmts))
... |
def get_stats_str(list_=None, newlines=False, keys=None, exclude_keys=[], lbl=None,
precision=None, axis=0, stat_dict=None, use_nan=False,
align=False, use_median=False, **kwargs):
"""
Returns the string version of get_stats
DEPRICATE in favor of ut.repr3(ut.get_stats(..... | def function[get_stats_str, parameter[list_, newlines, keys, exclude_keys, lbl, precision, axis, stat_dict, use_nan, align, use_median]]:
constant[
Returns the string version of get_stats
DEPRICATE in favor of ut.repr3(ut.get_stats(...))
if keys is not None then it only displays chosen keys
ex... | keyword[def] identifier[get_stats_str] ( identifier[list_] = keyword[None] , identifier[newlines] = keyword[False] , identifier[keys] = keyword[None] , identifier[exclude_keys] =[], identifier[lbl] = keyword[None] ,
identifier[precision] = keyword[None] , identifier[axis] = literal[int] , identifier[stat_dict] = key... | def get_stats_str(list_=None, newlines=False, keys=None, exclude_keys=[], lbl=None, precision=None, axis=0, stat_dict=None, use_nan=False, align=False, use_median=False, **kwargs):
"""
Returns the string version of get_stats
DEPRICATE in favor of ut.repr3(ut.get_stats(...))
if keys is not None then it... |
def gpp(V,E):
"""gpp -- model for the graph partitioning problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
"""
model = Model("gpp")
x = {}
y = {}
for i in V:
x[i] = model.addVar(vtype=... | def function[gpp, parameter[V, E]]:
constant[gpp -- model for the graph partitioning problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
]
variable[model] assign[=] call[name[Model], parameter[consta... | keyword[def] identifier[gpp] ( identifier[V] , identifier[E] ):
literal[string]
identifier[model] = identifier[Model] ( literal[string] )
identifier[x] ={}
identifier[y] ={}
keyword[for] identifier[i] keyword[in] identifier[V] :
identifier[x] [ identifier[i] ]= identifier[model]... | def gpp(V, E):
"""gpp -- model for the graph partitioning problem
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns a model, ready to be solved.
"""
model = Model('gpp')
x = {}
y = {}
for i in V:
x[i] = model.addVar(vtype=... |
def sort(self, by=None, reverse=False):
"""
Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset
"""
if by is None:
... | def function[sort, parameter[self, by, reverse]]:
constant[
Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset
]
if compar... | keyword[def] identifier[sort] ( identifier[self] , identifier[by] = keyword[None] , identifier[reverse] = keyword[False] ):
literal[string]
keyword[if] identifier[by] keyword[is] keyword[None] :
identifier[by] = identifier[self] . identifier[kdims]
keyword[elif] keyword[n... | def sort(self, by=None, reverse=False):
"""
Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset
"""
if by is None:
by = sel... |
def invalidate(self):
" Invalidate the UI for all clients. "
logger.info('Invalidating %s applications', len(self.apps))
for app in self.apps:
app.invalidate() | def function[invalidate, parameter[self]]:
constant[ Invalidate the UI for all clients. ]
call[name[logger].info, parameter[constant[Invalidating %s applications], call[name[len], parameter[name[self].apps]]]]
for taget[name[app]] in starred[name[self].apps] begin[:]
call[name[ap... | keyword[def] identifier[invalidate] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[len] ( identifier[self] . identifier[apps] ))
keyword[for] identifier[app] keyword[in] identifier[self] . identifier[apps] :
ident... | def invalidate(self):
""" Invalidate the UI for all clients. """
logger.info('Invalidating %s applications', len(self.apps))
for app in self.apps:
app.invalidate() # depends on [control=['for'], data=['app']] |
def unload(module):
'''
Unload specified fault manager module
module: string
module to unload
CLI Example:
.. code-block:: bash
salt '*' fmadm.unload software-response
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} unload {module}'.format(
cmd=fmadm,
... | def function[unload, parameter[module]]:
constant[
Unload specified fault manager module
module: string
module to unload
CLI Example:
.. code-block:: bash
salt '*' fmadm.unload software-response
]
variable[ret] assign[=] dictionary[[], []]
variable[fmadm] ... | keyword[def] identifier[unload] ( identifier[module] ):
literal[string]
identifier[ret] ={}
identifier[fmadm] = identifier[_check_fmadm] ()
identifier[cmd] = literal[string] . identifier[format] (
identifier[cmd] = identifier[fmadm] ,
identifier[module] = identifier[module]
)
... | def unload(module):
"""
Unload specified fault manager module
module: string
module to unload
CLI Example:
.. code-block:: bash
salt '*' fmadm.unload software-response
"""
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} unload {module}'.format(cmd=fmadm, module=modul... |
def remove_entry(self, entry):
"""!
@brief Remove clustering feature from the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature -= entry;
self.entries.remove(entry); | def function[remove_entry, parameter[self, entry]]:
constant[!
@brief Remove clustering feature from the leaf node.
@param[in] entry (cfentry): Clustering feature.
]
<ast.AugAssign object at 0x7da1b01fc4f0>
call[name[self].entries.remove, parameter[name[entr... | keyword[def] identifier[remove_entry] ( identifier[self] , identifier[entry] ):
literal[string]
identifier[self] . identifier[feature] -= identifier[entry] ;
identifier[self] . identifier[entries] . identifier[remove] ( identifier[entry] ); | def remove_entry(self, entry):
"""!
@brief Remove clustering feature from the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature -= entry
self.entries.remove(entry) |
def enum_to_yaml(cls: Type[T_EnumToYAML], representer: Representer, data: T_EnumToYAML) -> ruamel.yaml.nodes.ScalarNode:
""" Encodes YAML representation.
This is a mixin method for writing enum values to YAML. It needs to be added to the enum
as a classmethod. See the module docstring for further informati... | def function[enum_to_yaml, parameter[cls, representer, data]]:
constant[ Encodes YAML representation.
This is a mixin method for writing enum values to YAML. It needs to be added to the enum
as a classmethod. See the module docstring for further information on this approach and how
to implement it.... | keyword[def] identifier[enum_to_yaml] ( identifier[cls] : identifier[Type] [ identifier[T_EnumToYAML] ], identifier[representer] : identifier[Representer] , identifier[data] : identifier[T_EnumToYAML] )-> identifier[ruamel] . identifier[yaml] . identifier[nodes] . identifier[ScalarNode] :
literal[string]
k... | def enum_to_yaml(cls: Type[T_EnumToYAML], representer: Representer, data: T_EnumToYAML) -> ruamel.yaml.nodes.ScalarNode:
""" Encodes YAML representation.
This is a mixin method for writing enum values to YAML. It needs to be added to the enum
as a classmethod. See the module docstring for further informati... |
def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
"""
app.cache_db_path = ":memory:"
if app.config["uqbar_book_use_cache"]:
logger.info(bold("[uqbar-book]"), nonl=True)
logger.info(" initializing cache db")
app.connection = uqbar.book.sphinx.create... | def function[on_builder_inited, parameter[app]]:
constant[
Hooks into Sphinx's ``builder-inited`` event.
]
name[app].cache_db_path assign[=] constant[:memory:]
if call[name[app].config][constant[uqbar_book_use_cache]] begin[:]
call[name[logger].info, parameter[call[name[b... | keyword[def] identifier[on_builder_inited] ( identifier[app] ):
literal[string]
identifier[app] . identifier[cache_db_path] = literal[string]
keyword[if] identifier[app] . identifier[config] [ literal[string] ]:
identifier[logger] . identifier[info] ( identifier[bold] ( literal[string] ), i... | def on_builder_inited(app):
"""
Hooks into Sphinx's ``builder-inited`` event.
"""
app.cache_db_path = ':memory:'
if app.config['uqbar_book_use_cache']:
logger.info(bold('[uqbar-book]'), nonl=True)
logger.info(' initializing cache db')
app.connection = uqbar.book.sphinx.create... |
def move(self):
"""
Advance game by single move, if possible.
@return: logical indicator if move was performed.
"""
if len(self.moves) == MAX_MOVES:
return False
elif len(self.moves) % 2:
active_engine = self.black_engine
active_engine... | def function[move, parameter[self]]:
constant[
Advance game by single move, if possible.
@return: logical indicator if move was performed.
]
if compare[call[name[len], parameter[name[self].moves]] equal[==] name[MAX_MOVES]] begin[:]
return[constant[False]]
call[n... | keyword[def] identifier[move] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[moves] )== identifier[MAX_MOVES] :
keyword[return] keyword[False]
keyword[elif] identifier[len] ( identifier[self] . identifier[moves] )% literal... | def move(self):
"""
Advance game by single move, if possible.
@return: logical indicator if move was performed.
"""
if len(self.moves) == MAX_MOVES:
return False # depends on [control=['if'], data=[]]
elif len(self.moves) % 2:
active_engine = self.black_engine
... |
def format_results(self, raw_data, options):
'''
Returns a python structure that later gets serialized.
raw_data
full list of objects matching the search term
options
a dictionary of the given options
'''
page_data = self.paginate_results(raw_data,... | def function[format_results, parameter[self, raw_data, options]]:
constant[
Returns a python structure that later gets serialized.
raw_data
full list of objects matching the search term
options
a dictionary of the given options
]
variable[page_data... | keyword[def] identifier[format_results] ( identifier[self] , identifier[raw_data] , identifier[options] ):
literal[string]
identifier[page_data] = identifier[self] . identifier[paginate_results] ( identifier[raw_data] , identifier[options] )
identifier[results] ={}
identifier[meta... | def format_results(self, raw_data, options):
"""
Returns a python structure that later gets serialized.
raw_data
full list of objects matching the search term
options
a dictionary of the given options
"""
page_data = self.paginate_results(raw_data, options... |
def translate_reaction(reaction, metabolite_mapping):
"""
Return a mapping from KEGG compound identifiers to coefficients.
Parameters
----------
reaction : cobra.Reaction
The reaction whose metabolites are to be translated.
metabolite_mapping : dict
An existing mapping from cobr... | def function[translate_reaction, parameter[reaction, metabolite_mapping]]:
constant[
Return a mapping from KEGG compound identifiers to coefficients.
Parameters
----------
reaction : cobra.Reaction
The reaction whose metabolites are to be translated.
metabolite_mapping : dict
... | keyword[def] identifier[translate_reaction] ( identifier[reaction] , identifier[metabolite_mapping] ):
literal[string]
identifier[stoichiometry] = identifier[defaultdict] ( identifier[float] )
keyword[for] identifier[met] , identifier[coef] keyword[in] identifier[iteritems] ( identif... | def translate_reaction(reaction, metabolite_mapping):
"""
Return a mapping from KEGG compound identifiers to coefficients.
Parameters
----------
reaction : cobra.Reaction
The reaction whose metabolites are to be translated.
metabolite_mapping : dict
An existing mapping from cobr... |
def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello ... | def function[_record2card, parameter[self, record]]:
constant[
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
... | keyword[def] identifier[_record2card] ( identifier[self] , identifier[record] ):
literal[string]
identifier[name] = identifier[record] [ literal[string] ]
identifier[value] = identifier[record] [ literal[string] ]
identifier[v_isstring] = identifier[isstring] ( identifier[value] ... | def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello '
... |
def dump_links(self, o):
"""Dump links."""
return {
'self': url_for('.bucket_api', bucket_id=o.id, _external=True),
'versions': url_for(
'.bucket_api', bucket_id=o.id, _external=True) + '?versions',
'uploads': url_for(
'.bucket_api', bu... | def function[dump_links, parameter[self, o]]:
constant[Dump links.]
return[dictionary[[<ast.Constant object at 0x7da1b19c3850>, <ast.Constant object at 0x7da1b19c2c20>, <ast.Constant object at 0x7da1b19c36d0>], [<ast.Call object at 0x7da1b19c3880>, <ast.BinOp object at 0x7da1b19c0550>, <ast.BinOp object at ... | keyword[def] identifier[dump_links] ( identifier[self] , identifier[o] ):
literal[string]
keyword[return] {
literal[string] : identifier[url_for] ( literal[string] , identifier[bucket_id] = identifier[o] . identifier[id] , identifier[_external] = keyword[True] ),
literal[string] :... | def dump_links(self, o):
"""Dump links."""
return {'self': url_for('.bucket_api', bucket_id=o.id, _external=True), 'versions': url_for('.bucket_api', bucket_id=o.id, _external=True) + '?versions', 'uploads': url_for('.bucket_api', bucket_id=o.id, _external=True) + '?uploads'} |
def have_all_block_data(self):
"""
Have we received all block data?
"""
if not (self.num_blocks_received == self.num_blocks_requested):
log.debug("num blocks received = %s, num requested = %s" % (self.num_blocks_received, self.num_blocks_requested))
return False
... | def function[have_all_block_data, parameter[self]]:
constant[
Have we received all block data?
]
if <ast.UnaryOp object at 0x7da1b26c91e0> begin[:]
call[name[log].debug, parameter[binary_operation[constant[num blocks received = %s, num requested = %s] <ast.Mod object at 0... | keyword[def] identifier[have_all_block_data] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] ( identifier[self] . identifier[num_blocks_received] == identifier[self] . identifier[num_blocks_requested] ):
identifier[log] . identifier[debug] ( literal[string] %( identifie... | def have_all_block_data(self):
"""
Have we received all block data?
"""
if not self.num_blocks_received == self.num_blocks_requested:
log.debug('num blocks received = %s, num requested = %s' % (self.num_blocks_received, self.num_blocks_requested))
return False # depends on [cont... |
def _is_api_key_correct(request):
"""Return whether the Geckoboard API key on the request is correct."""
api_key = getattr(settings, 'GECKOBOARD_API_KEY', None)
if api_key is None:
return True
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
if len(auth) == 2:
if auth[0].low... | def function[_is_api_key_correct, parameter[request]]:
constant[Return whether the Geckoboard API key on the request is correct.]
variable[api_key] assign[=] call[name[getattr], parameter[name[settings], constant[GECKOBOARD_API_KEY], constant[None]]]
if compare[name[api_key] is constant[None]] b... | keyword[def] identifier[_is_api_key_correct] ( identifier[request] ):
literal[string]
identifier[api_key] = identifier[getattr] ( identifier[settings] , literal[string] , keyword[None] )
keyword[if] identifier[api_key] keyword[is] keyword[None] :
keyword[return] keyword[True]
identi... | def _is_api_key_correct(request):
"""Return whether the Geckoboard API key on the request is correct."""
api_key = getattr(settings, 'GECKOBOARD_API_KEY', None)
if api_key is None:
return True # depends on [control=['if'], data=[]]
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
i... |
def _get_boundary(self, var):
"""Get the position of exon-intron boundary for current variant
"""
if var.type == "r" or var.type == "n":
if self.cross_boundaries:
return 0, float("inf")
else:
# Get genomic sequence access number for this tr... | def function[_get_boundary, parameter[self, var]]:
constant[Get the position of exon-intron boundary for current variant
]
if <ast.BoolOp object at 0x7da1b20b4250> begin[:]
if name[self].cross_boundaries begin[:]
return[tuple[[<ast.Constant object at 0x7da1b20b4ee0>, ... | keyword[def] identifier[_get_boundary] ( identifier[self] , identifier[var] ):
literal[string]
keyword[if] identifier[var] . identifier[type] == literal[string] keyword[or] identifier[var] . identifier[type] == literal[string] :
keyword[if] identifier[self] . identifier[cross_bound... | def _get_boundary(self, var):
"""Get the position of exon-intron boundary for current variant
"""
if var.type == 'r' or var.type == 'n':
if self.cross_boundaries:
return (0, float('inf')) # depends on [control=['if'], data=[]]
else:
# Get genomic sequence access ... |
def save(self):
"""
save or update this entity on Ariane server
:return:
"""
LOGGER.debug("InjectorUITreeEntity.save")
if self.id and self.value and self.type:
ok = True
if InjectorUITreeService.find_ui_tree_entity(self.id) is None: # SAVE
... | def function[save, parameter[self]]:
constant[
save or update this entity on Ariane server
:return:
]
call[name[LOGGER].debug, parameter[constant[InjectorUITreeEntity.save]]]
if <ast.BoolOp object at 0x7da20c6e40a0> begin[:]
variable[ok] assign[=] constant... | keyword[def] identifier[save] ( identifier[self] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[if] identifier[self] . identifier[id] keyword[and] identifier[self] . identifier[value] keyword[and] identifier[self] . identifier[type] :
... | def save(self):
"""
save or update this entity on Ariane server
:return:
"""
LOGGER.debug('InjectorUITreeEntity.save')
if self.id and self.value and self.type:
ok = True
if InjectorUITreeService.find_ui_tree_entity(self.id) is None: # SAVE
self_string = s... |
def _deepcopy(self, x, memo=None):
"""Deepcopy helper for the data dictionary or list.
Regular expressions cannot be deep copied but as they are immutable we
don't have to copy them when cloning.
"""
if not hasattr(x, 'items'):
y, is_list, iterator = [], True, enumer... | def function[_deepcopy, parameter[self, x, memo]]:
constant[Deepcopy helper for the data dictionary or list.
Regular expressions cannot be deep copied but as they are immutable we
don't have to copy them when cloning.
]
if <ast.UnaryOp object at 0x7da20c7c9c00> begin[:]
... | keyword[def] identifier[_deepcopy] ( identifier[self] , identifier[x] , identifier[memo] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[x] , literal[string] ):
identifier[y] , identifier[is_list] , identifier[iterator] =[], keyword[True] ... | def _deepcopy(self, x, memo=None):
"""Deepcopy helper for the data dictionary or list.
Regular expressions cannot be deep copied but as they are immutable we
don't have to copy them when cloning.
"""
if not hasattr(x, 'items'):
(y, is_list, iterator) = ([], True, enumerate(x)) ... |
def scrub_dict(d):
""" Recursively inspect a dictionary and remove all empty values, including
empty strings, lists, and dictionaries.
"""
if type(d) is dict:
return dict(
(k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v)
)
elif type(d) is list:
... | def function[scrub_dict, parameter[d]]:
constant[ Recursively inspect a dictionary and remove all empty values, including
empty strings, lists, and dictionaries.
]
if compare[call[name[type], parameter[name[d]]] is name[dict]] begin[:]
return[call[name[dict], parameter[<ast.Generator... | keyword[def] identifier[scrub_dict] ( identifier[d] ):
literal[string]
keyword[if] identifier[type] ( identifier[d] ) keyword[is] identifier[dict] :
keyword[return] identifier[dict] (
( identifier[k] , identifier[scrub_dict] ( identifier[v] )) keyword[for] identifier[k] , identifier[v]... | def scrub_dict(d):
""" Recursively inspect a dictionary and remove all empty values, including
empty strings, lists, and dictionaries.
"""
if type(d) is dict:
return dict(((k, scrub_dict(v)) for (k, v) in d.iteritems() if v and scrub_dict(v))) # depends on [control=['if'], data=['dict']]
... |
def _invoke_hook(hook_name, target):
"""
Generic hook invocation.
"""
try:
for value in getattr(target, hook_name):
func, args, kwargs = value
func(target, *args, **kwargs)
except AttributeError:
# no hook defined
pass
except (TypeError, ValueErro... | def function[_invoke_hook, parameter[hook_name, target]]:
constant[
Generic hook invocation.
]
<ast.Try object at 0x7da1b0c92350> | keyword[def] identifier[_invoke_hook] ( identifier[hook_name] , identifier[target] ):
literal[string]
keyword[try] :
keyword[for] identifier[value] keyword[in] identifier[getattr] ( identifier[target] , identifier[hook_name] ):
identifier[func] , identifier[args] , identifier[kwarg... | def _invoke_hook(hook_name, target):
"""
Generic hook invocation.
"""
try:
for value in getattr(target, hook_name):
(func, args, kwargs) = value
func(target, *args, **kwargs) # depends on [control=['for'], data=['value']] # depends on [control=['try'], data=[]]
exc... |
def append(self, child):
"""
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
if self.element == child.parent:
self... | def function[append, parameter[self, child]]:
constant[
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
]
if call[name[self]._can_add_child, parameter[name[child]]] begin[:]
... | keyword[def] identifier[append] ( identifier[self] , identifier[child] ):
literal[string]
keyword[if] identifier[self] . identifier[_can_add_child] ( identifier[child] ):
keyword[if] identifier[self] . identifier[element] == identifier[child] . identifier[parent] :
i... | def append(self, child):
"""
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
if self.element == child.parent:
self._remove_from_tr... |
def _get_success(self, stanza):
"""Handle successful response to the roster request.
"""
payload = stanza.get_payload(RosterPayload)
if payload is None:
if "versioning" in self.server_features and self.roster:
logger.debug("Server will send roster delta in pus... | def function[_get_success, parameter[self, stanza]]:
constant[Handle successful response to the roster request.
]
variable[payload] assign[=] call[name[stanza].get_payload, parameter[name[RosterPayload]]]
if compare[name[payload] is constant[None]] begin[:]
if <ast.BoolOp... | keyword[def] identifier[_get_success] ( identifier[self] , identifier[stanza] ):
literal[string]
identifier[payload] = identifier[stanza] . identifier[get_payload] ( identifier[RosterPayload] )
keyword[if] identifier[payload] keyword[is] keyword[None] :
keyword[if] literal... | def _get_success(self, stanza):
"""Handle successful response to the roster request.
"""
payload = stanza.get_payload(RosterPayload)
if payload is None:
if 'versioning' in self.server_features and self.roster:
logger.debug('Server will send roster delta in pushes') # depends on ... |
def _file_dict(self, fn_):
'''
Take a path and return the contents of the file as a string
'''
if not os.path.isfile(fn_):
err = 'The referenced file, {0} is not available.'.format(fn_)
sys.stderr.write(err + '\n')
sys.exit(42)
with salt.utils.... | def function[_file_dict, parameter[self, fn_]]:
constant[
Take a path and return the contents of the file as a string
]
if <ast.UnaryOp object at 0x7da1b1c47670> begin[:]
variable[err] assign[=] call[constant[The referenced file, {0} is not available.].format, parameter[n... | keyword[def] identifier[_file_dict] ( identifier[self] , identifier[fn_] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[fn_] ):
identifier[err] = literal[string] . identifier[format] ( identifier[fn_] )
ide... | def _file_dict(self, fn_):
"""
Take a path and return the contents of the file as a string
"""
if not os.path.isfile(fn_):
err = 'The referenced file, {0} is not available.'.format(fn_)
sys.stderr.write(err + '\n')
sys.exit(42) # depends on [control=['if'], data=[]]
... |
def delete_states_geo_zone_by_id(cls, states_geo_zone_id, **kwargs):
"""Delete StatesGeoZone
Delete an instance of StatesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.dele... | def function[delete_states_geo_zone_by_id, parameter[cls, states_geo_zone_id]]:
constant[Delete StatesGeoZone
Delete an instance of StatesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> ... | keyword[def] identifier[delete_states_geo_zone_by_id] ( identifier[cls] , identifier[states_geo_zone_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyw... | def delete_states_geo_zone_by_id(cls, states_geo_zone_id, **kwargs):
"""Delete StatesGeoZone
Delete an instance of StatesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_s... |
def on_get(resc, req, resp, rid):
""" Find the model by id & serialize it back """
signals.pre_req.send(resc.model)
signals.pre_req_find.send(resc.model)
model = find(resc.model, rid)
props = to_rest_model(model, includes=req.includes)
resp.last_modified = model.updated
resp.serialize(pro... | def function[on_get, parameter[resc, req, resp, rid]]:
constant[ Find the model by id & serialize it back ]
call[name[signals].pre_req.send, parameter[name[resc].model]]
call[name[signals].pre_req_find.send, parameter[name[resc].model]]
variable[model] assign[=] call[name[find], paramete... | keyword[def] identifier[on_get] ( identifier[resc] , identifier[req] , identifier[resp] , identifier[rid] ):
literal[string]
identifier[signals] . identifier[pre_req] . identifier[send] ( identifier[resc] . identifier[model] )
identifier[signals] . identifier[pre_req_find] . identifier[send] ( identi... | def on_get(resc, req, resp, rid):
""" Find the model by id & serialize it back """
signals.pre_req.send(resc.model)
signals.pre_req_find.send(resc.model)
model = find(resc.model, rid)
props = to_rest_model(model, includes=req.includes)
resp.last_modified = model.updated
resp.serialize(props)... |
def read_txt_file(filepath):
"""read text from `filepath` and remove linebreaks
"""
if sys.version > '3':
with open(filepath,'r',encoding='utf-8') as txt_file:
return txt_file.readlines()
else:
with open(filepath) as txt_file:
return txt_file.readlines() | def function[read_txt_file, parameter[filepath]]:
constant[read text from `filepath` and remove linebreaks
]
if compare[name[sys].version greater[>] constant[3]] begin[:]
with call[name[open], parameter[name[filepath], constant[r]]] begin[:]
return[call[name[txt_file].rea... | keyword[def] identifier[read_txt_file] ( identifier[filepath] ):
literal[string]
keyword[if] identifier[sys] . identifier[version] > literal[string] :
keyword[with] identifier[open] ( identifier[filepath] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[txt_fi... | def read_txt_file(filepath):
"""read text from `filepath` and remove linebreaks
"""
if sys.version > '3':
with open(filepath, 'r', encoding='utf-8') as txt_file:
return txt_file.readlines() # depends on [control=['with'], data=['txt_file']] # depends on [control=['if'], data=[]]
el... |
def _on_arc(self, speed, radius_mm, distance_mm, brake, block, arc_right):
"""
Drive in a circle with 'radius' for 'distance'
"""
if radius_mm < self.min_circle_radius_mm:
raise ValueError("{}: radius_mm {} is less than min_circle_radius_mm {}" .format(
s... | def function[_on_arc, parameter[self, speed, radius_mm, distance_mm, brake, block, arc_right]]:
constant[
Drive in a circle with 'radius' for 'distance'
]
if compare[name[radius_mm] less[<] name[self].min_circle_radius_mm] begin[:]
<ast.Raise object at 0x7da1b16e8940>
var... | keyword[def] identifier[_on_arc] ( identifier[self] , identifier[speed] , identifier[radius_mm] , identifier[distance_mm] , identifier[brake] , identifier[block] , identifier[arc_right] ):
literal[string]
keyword[if] identifier[radius_mm] < identifier[self] . identifier[min_circle_radius_mm] :
... | def _on_arc(self, speed, radius_mm, distance_mm, brake, block, arc_right):
"""
Drive in a circle with 'radius' for 'distance'
"""
if radius_mm < self.min_circle_radius_mm:
raise ValueError('{}: radius_mm {} is less than min_circle_radius_mm {}'.format(self, radius_mm, self.min_circle_rad... |
def _get_args(self, executable, *args):
"""compile all the executable and the arguments, combining with common arguments
to create a full batch of command args"""
args = list(args)
args.insert(0, executable)
if self.username:
args.append("--username={}".format(self.us... | def function[_get_args, parameter[self, executable]]:
constant[compile all the executable and the arguments, combining with common arguments
to create a full batch of command args]
variable[args] assign[=] call[name[list], parameter[name[args]]]
call[name[args].insert, parameter[constant... | keyword[def] identifier[_get_args] ( identifier[self] , identifier[executable] ,* identifier[args] ):
literal[string]
identifier[args] = identifier[list] ( identifier[args] )
identifier[args] . identifier[insert] ( literal[int] , identifier[executable] )
keyword[if] identifier[se... | def _get_args(self, executable, *args):
"""compile all the executable and the arguments, combining with common arguments
to create a full batch of command args"""
args = list(args)
args.insert(0, executable)
if self.username:
args.append('--username={}'.format(self.username)) # depends ... |
def rdl_decomposition(T, k=None, reversible=False, norm='standard', mu=None):
r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard', '... | def function[rdl_decomposition, parameter[T, k, reversible, norm, mu]]:
constant[Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard'... | keyword[def] identifier[rdl_decomposition] ( identifier[T] , identifier[k] = keyword[None] , identifier[reversible] = keyword[False] , identifier[norm] = literal[string] , identifier[mu] = keyword[None] ):
literal[string]
keyword[if] identifier[norm] == literal[string] :
keyword[if] identif... | def rdl_decomposition(T, k=None, reversible=False, norm='standard', mu=None):
"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard', 'r... |
def get_members(pkg_name, module_filter = None, member_filter = None):
"""
返回包中所有符合条件的模块成员。
参数:
pkg_name 包名称
module_filter 模块名过滤器 def (module_name)
member_filter 成员过滤器 def member_filter(module_member_object)
"""
modules = get_modules(p... | def function[get_members, parameter[pkg_name, module_filter, member_filter]]:
constant[
返回包中所有符合条件的模块成员。
参数:
pkg_name 包名称
module_filter 模块名过滤器 def (module_name)
member_filter 成员过滤器 def member_filter(module_member_object)
]
variable[modu... | keyword[def] identifier[get_members] ( identifier[pkg_name] , identifier[module_filter] = keyword[None] , identifier[member_filter] = keyword[None] ):
literal[string]
identifier[modules] = identifier[get_modules] ( identifier[pkg_name] , identifier[module_filter] )
identifier[ret] ={}
keywo... | def get_members(pkg_name, module_filter=None, member_filter=None):
"""
返回包中所有符合条件的模块成员。
参数:
pkg_name 包名称
module_filter 模块名过滤器 def (module_name)
member_filter 成员过滤器 def member_filter(module_member_object)
"""
modules = get_modules(pkg_name, modu... |
def discover(name, timeout=None, minimum_providers=1):
"""
discovers a service. If timeout is specified, waits for at least minimum_providers service instance to be available.
Note : we do not want to make the discovery block undefinitely since we never know for sure if a service is running or n... | def function[discover, parameter[name, timeout, minimum_providers]]:
constant[
discovers a service. If timeout is specified, waits for at least minimum_providers service instance to be available.
Note : we do not want to make the discovery block undefinitely since we never know for sure if a ser... | keyword[def] identifier[discover] ( identifier[name] , identifier[timeout] = keyword[None] , identifier[minimum_providers] = literal[int] ):
literal[string]
identifier[start] = identifier[time] . identifier[time] ()
identifier[endtime] = identifier[timeout] keyword[if] identifier[timeout... | def discover(name, timeout=None, minimum_providers=1):
"""
discovers a service. If timeout is specified, waits for at least minimum_providers service instance to be available.
Note : we do not want to make the discovery block undefinitely since we never know for sure if a service is running or not
... |
def GetHostMemUsedMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | def function[GetHostMemUsedMB, parameter[self]]:
constant[Undocumented.]
variable[counter] assign[=] call[name[c_uint], parameter[]]
variable[ret] assign[=] call[name[vmGuestLib].VMGuestLib_GetHostMemUsedMB, parameter[name[self].handle.value, call[name[byref], parameter[name[counter]]]]]
... | keyword[def] identifier[GetHostMemUsedMB] ( identifier[self] ):
literal[string]
identifier[counter] = identifier[c_uint] ()
identifier[ret] = identifier[vmGuestLib] . identifier[VMGuestLib_GetHostMemUsedMB] ( identifier[self] . identifier[handle] . identifier[value] , identifier[byref] ( i... | def GetHostMemUsedMB(self):
"""Undocumented."""
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS:
raise VMGuestLibException(ret) # depends on [control=['if'], data=['ret']]
return counter.value |
def check_row(state, index, missing_msg=None, expand_msg=None):
"""Zoom in on a particular row in the query result, by index.
After zooming in on a row, which is represented as a single-row query result,
you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution
query res... | def function[check_row, parameter[state, index, missing_msg, expand_msg]]:
constant[Zoom in on a particular row in the query result, by index.
After zooming in on a row, which is represented as a single-row query result,
you can use ``has_equal_value()`` to verify whether all columns in the zoomed in s... | keyword[def] identifier[check_row] ( identifier[state] , identifier[index] , identifier[missing_msg] = keyword[None] , identifier[expand_msg] = keyword[None] ):
literal[string]
keyword[if] identifier[missing_msg] keyword[is] keyword[None] :
identifier[missing_msg] = literal[string]
keywo... | def check_row(state, index, missing_msg=None, expand_msg=None):
"""Zoom in on a particular row in the query result, by index.
After zooming in on a row, which is represented as a single-row query result,
you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution
query res... |
def teach_students(self):
"""
Train each model (student) with the labeled data using bootstrap
aggregating (bagging).
"""
dataset = self.dataset
for student in self.students:
bag = self._labeled_uniform_sample(int(dataset.len_labeled()))
while bag.... | def function[teach_students, parameter[self]]:
constant[
Train each model (student) with the labeled data using bootstrap
aggregating (bagging).
]
variable[dataset] assign[=] name[self].dataset
for taget[name[student]] in starred[name[self].students] begin[:]
... | keyword[def] identifier[teach_students] ( identifier[self] ):
literal[string]
identifier[dataset] = identifier[self] . identifier[dataset]
keyword[for] identifier[student] keyword[in] identifier[self] . identifier[students] :
identifier[bag] = identifier[self] . identifier... | def teach_students(self):
"""
Train each model (student) with the labeled data using bootstrap
aggregating (bagging).
"""
dataset = self.dataset
for student in self.students:
bag = self._labeled_uniform_sample(int(dataset.len_labeled()))
while bag.get_num_of_labels() ... |
def push_repository(self,
repository,
docker_executable='docker',
shutit_pexpect_child=None,
expect=None,
note=None,
loglevel=logging.INFO):
"""Pushes the repository.
@param repository: ... | def function[push_repository, parameter[self, repository, docker_executable, shutit_pexpect_child, expect, note, loglevel]]:
constant[Pushes the repository.
@param repository: Repository to push.
@param docker_executable: Defaults to 'docker'
@param expect: See send()
@param shu... | keyword[def] identifier[push_repository] ( identifier[self] ,
identifier[repository] ,
identifier[docker_executable] = literal[string] ,
identifier[shutit_pexpect_child] = keyword[None] ,
identifier[expect] = keyword[None] ,
identifier[note] = keyword[None] ,
identifier[loglevel] = identifier[logging] . identif... | def push_repository(self, repository, docker_executable='docker', shutit_pexpect_child=None, expect=None, note=None, loglevel=logging.INFO):
"""Pushes the repository.
@param repository: Repository to push.
@param docker_executable: Defaults to 'docker'
@param expect: See send()
@par... |
def read_data(self,variable_instance):
"""
read values from the device
"""
if self.inst is None:
return
vp_func = variable_instance.variableproperty_set.filter(name=':FUNC').first()
measure_function = ''
if vp_func:
if vp_func.value():
... | def function[read_data, parameter[self, variable_instance]]:
constant[
read values from the device
]
if compare[name[self].inst is constant[None]] begin[:]
return[None]
variable[vp_func] assign[=] call[call[name[variable_instance].variableproperty_set.filter, parameter[]]... | keyword[def] identifier[read_data] ( identifier[self] , identifier[variable_instance] ):
literal[string]
keyword[if] identifier[self] . identifier[inst] keyword[is] keyword[None] :
keyword[return]
identifier[vp_func] = identifier[variable_instance] . identifier[variablepr... | def read_data(self, variable_instance):
"""
read values from the device
"""
if self.inst is None:
return # depends on [control=['if'], data=[]]
vp_func = variable_instance.variableproperty_set.filter(name=':FUNC').first()
measure_function = ''
if vp_func:
if vp_func.... |
def _get_policies(self, resource_properties):
"""
Returns a list of policies from the resource properties. This method knows how to interpret and handle
polymorphic nature of the policies property.
Policies can be one of the following:
* Managed policy name: string
... | def function[_get_policies, parameter[self, resource_properties]]:
constant[
Returns a list of policies from the resource properties. This method knows how to interpret and handle
polymorphic nature of the policies property.
Policies can be one of the following:
* Managed p... | keyword[def] identifier[_get_policies] ( identifier[self] , identifier[resource_properties] ):
literal[string]
identifier[policies] = keyword[None]
keyword[if] identifier[self] . identifier[_contains_policies] ( identifier[resource_properties] ):
identifier[policies] = ide... | def _get_policies(self, resource_properties):
"""
Returns a list of policies from the resource properties. This method knows how to interpret and handle
polymorphic nature of the policies property.
Policies can be one of the following:
* Managed policy name: string
... |
def dft_task(cls, mol, xc="b3lyp", **kwargs):
"""
A class method for quickly creating DFT tasks with optional
cosmo parameter .
Args:
mol: Input molecule
xc: Exchange correlation to use.
\\*\\*kwargs: Any of the other kwargs supported by NwTask. Note ... | def function[dft_task, parameter[cls, mol, xc]]:
constant[
A class method for quickly creating DFT tasks with optional
cosmo parameter .
Args:
mol: Input molecule
xc: Exchange correlation to use.
\*\*kwargs: Any of the other kwargs supported by NwTask... | keyword[def] identifier[dft_task] ( identifier[cls] , identifier[mol] , identifier[xc] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[t] = identifier[NwTask] . identifier[from_molecule] ( identifier[mol] , identifier[theory] = literal[string] ,** identifier[kwargs] )
... | def dft_task(cls, mol, xc='b3lyp', **kwargs):
"""
A class method for quickly creating DFT tasks with optional
cosmo parameter .
Args:
mol: Input molecule
xc: Exchange correlation to use.
\\*\\*kwargs: Any of the other kwargs supported by NwTask. Note the
... |
def remove_col(self, col_num):
"""
update table dataframe, and remove a column.
resize grid to display correctly
"""
label_value = self.GetColLabelValue(col_num).strip('**').strip('^^')
self.col_labels.remove(label_value)
del self.table.dataframe[label_value]
... | def function[remove_col, parameter[self, col_num]]:
constant[
update table dataframe, and remove a column.
resize grid to display correctly
]
variable[label_value] assign[=] call[call[call[name[self].GetColLabelValue, parameter[name[col_num]]].strip, parameter[constant[**]]].stri... | keyword[def] identifier[remove_col] ( identifier[self] , identifier[col_num] ):
literal[string]
identifier[label_value] = identifier[self] . identifier[GetColLabelValue] ( identifier[col_num] ). identifier[strip] ( literal[string] ). identifier[strip] ( literal[string] )
identifier[self] .... | def remove_col(self, col_num):
"""
update table dataframe, and remove a column.
resize grid to display correctly
"""
label_value = self.GetColLabelValue(col_num).strip('**').strip('^^')
self.col_labels.remove(label_value)
del self.table.dataframe[label_value]
result = self.De... |
def escape(pathname):
"""Escape all special characters.
"""
# Escaping is done by wrapping any of "*?[" between square brackets.
# Metacharacters do not work in the drive part and shouldn't be escaped.
drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
pathnam... | def function[escape, parameter[pathname]]:
constant[Escape all special characters.
]
<ast.Tuple object at 0x7da1b1cd6fb0> assign[=] call[name[os].path.splitdrive, parameter[name[pathname]]]
if call[name[isinstance], parameter[name[pathname], name[bytes]]] begin[:]
variable[pa... | keyword[def] identifier[escape] ( identifier[pathname] ):
literal[string]
identifier[drive] , identifier[pathname] = identifier[os] . identifier[path] . identifier[splitdrive] ( identifier[pathname] )
keyword[if] identifier[isinstance] ( identifier[pathname] , identifier[bytes] ):
... | def escape(pathname):
"""Escape all special characters.
"""
# Escaping is done by wrapping any of "*?[" between square brackets.
# Metacharacters do not work in the drive part and shouldn't be escaped.
(drive, pathname) = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
pathn... |
def reserve_file(self, relative_path):
"""reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
"""
if os.path.isabs(relative_path):
raise ValueError('%s must be a relative ... | def function[reserve_file, parameter[self, relative_path]]:
constant[reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
]
if call[name[os].path.isabs, parameter[name[relative_path]]]... | keyword[def] identifier[reserve_file] ( identifier[self] , identifier[relative_path] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isabs] ( identifier[relative_path] ):
keyword[raise] identifier[ValueError] ( literal[string] % identifier[relative_path]... | def reserve_file(self, relative_path):
"""reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
"""
if os.path.isabs(relative_path):
raise ValueError('%s must be a relative path' % rela... |
def list_nodes(**kwargs):
'''
Return basic data on nodes
'''
ret = {}
nodes = list_nodes_full()
for node in nodes:
ret[node] = {}
for prop in 'id', 'image', 'size', 'state', 'private_ips', 'public_ips':
ret[node][prop] = nodes[node][prop]
return ret | def function[list_nodes, parameter[]]:
constant[
Return basic data on nodes
]
variable[ret] assign[=] dictionary[[], []]
variable[nodes] assign[=] call[name[list_nodes_full], parameter[]]
for taget[name[node]] in starred[name[nodes]] begin[:]
call[name[ret]][name[... | keyword[def] identifier[list_nodes] (** identifier[kwargs] ):
literal[string]
identifier[ret] ={}
identifier[nodes] = identifier[list_nodes_full] ()
keyword[for] identifier[node] keyword[in] identifier[nodes] :
identifier[ret] [ identifier[node] ]={}
keyword[for] identifier... | def list_nodes(**kwargs):
"""
Return basic data on nodes
"""
ret = {}
nodes = list_nodes_full()
for node in nodes:
ret[node] = {}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node][prop] # depends on [control=['fo... |
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None:
"""
rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
"""
raise NotImplementedError() | def function[rename, parameter[self, dn, new_rdn, new_base_dn]]:
constant[
rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
]
<ast.Raise object at 0x7da20c6a90c0> | keyword[def] identifier[rename] ( identifier[self] , identifier[dn] : identifier[str] , identifier[new_rdn] : identifier[str] , identifier[new_base_dn] : identifier[Optional] [ identifier[str] ]= keyword[None] )-> keyword[None] :
literal[string]
keyword[raise] identifier[NotImplementedError] () | def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str]=None) -> None:
"""
rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled.
"""
raise NotImplementedError() |
def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data):
""" Create a bit for bit plot """
plot_title = ""
plot_name = case + "_" + var_name + ".png"
plot_path = os.path.join(os.path.join(livvkit.output_dir, "verification", "imgs"))
functions.mkdir_p(plot_path)
m_ndim = np.ndim(m... | def function[plot_bit_for_bit, parameter[case, var_name, model_data, bench_data, diff_data]]:
constant[ Create a bit for bit plot ]
variable[plot_title] assign[=] constant[]
variable[plot_name] assign[=] binary_operation[binary_operation[binary_operation[name[case] + constant[_]] + name[var_name... | keyword[def] identifier[plot_bit_for_bit] ( identifier[case] , identifier[var_name] , identifier[model_data] , identifier[bench_data] , identifier[diff_data] ):
literal[string]
identifier[plot_title] = literal[string]
identifier[plot_name] = identifier[case] + literal[string] + identifier[var_name] +... | def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data):
""" Create a bit for bit plot """
plot_title = ''
plot_name = case + '_' + var_name + '.png'
plot_path = os.path.join(os.path.join(livvkit.output_dir, 'verification', 'imgs'))
functions.mkdir_p(plot_path)
m_ndim = np.ndim(m... |
def _get_api_urls(self, api_urls=None):
"""
Completes a dict with the CRUD urls of the API.
:param api_urls: A dict with the urls {'<FUNCTION>':'<URL>',...}
:return: A dict with the CRUD urls of the base API.
"""
view_name = self.__class__.__name__
api_urls =... | def function[_get_api_urls, parameter[self, api_urls]]:
constant[
Completes a dict with the CRUD urls of the API.
:param api_urls: A dict with the urls {'<FUNCTION>':'<URL>',...}
:return: A dict with the CRUD urls of the base API.
]
variable[view_name] assign[=] name... | keyword[def] identifier[_get_api_urls] ( identifier[self] , identifier[api_urls] = keyword[None] ):
literal[string]
identifier[view_name] = identifier[self] . identifier[__class__] . identifier[__name__]
identifier[api_urls] = identifier[api_urls] keyword[or] {}
identifier[api_u... | def _get_api_urls(self, api_urls=None):
"""
Completes a dict with the CRUD urls of the API.
:param api_urls: A dict with the urls {'<FUNCTION>':'<URL>',...}
:return: A dict with the CRUD urls of the base API.
"""
view_name = self.__class__.__name__
api_urls = api_urls or... |
def on_step_end(self, step, logs):
""" Update statistics of episode after each step """
episode = logs['episode']
self.observations[episode].append(logs['observation'])
self.rewards[episode].append(logs['reward'])
self.actions[episode].append(logs['action'])
self.metrics[... | def function[on_step_end, parameter[self, step, logs]]:
constant[ Update statistics of episode after each step ]
variable[episode] assign[=] call[name[logs]][constant[episode]]
call[call[name[self].observations][name[episode]].append, parameter[call[name[logs]][constant[observation]]]]
c... | keyword[def] identifier[on_step_end] ( identifier[self] , identifier[step] , identifier[logs] ):
literal[string]
identifier[episode] = identifier[logs] [ literal[string] ]
identifier[self] . identifier[observations] [ identifier[episode] ]. identifier[append] ( identifier[logs] [ literal[s... | def on_step_end(self, step, logs):
""" Update statistics of episode after each step """
episode = logs['episode']
self.observations[episode].append(logs['observation'])
self.rewards[episode].append(logs['reward'])
self.actions[episode].append(logs['action'])
self.metrics[episode].append(logs['me... |
def themeble(name, themes=None, global_context=None):
""" Decorator for registering objects (i.e. functions, classes) for
different themes.
Params:
* name - type of string. New global name for object
* themes - for this themes ``obj`` will be have alias with given name
* global_con... | def function[themeble, parameter[name, themes, global_context]]:
constant[ Decorator for registering objects (i.e. functions, classes) for
different themes.
Params:
* name - type of string. New global name for object
* themes - for this themes ``obj`` will be have alias with given name... | keyword[def] identifier[themeble] ( identifier[name] , identifier[themes] = keyword[None] , identifier[global_context] = keyword[None] ):
literal[string]
keyword[def] identifier[wrap] ( identifier[obj] ):
identifier[context] = identifier[global_context] keyword[or] identifier[inspect] . identif... | def themeble(name, themes=None, global_context=None):
""" Decorator for registering objects (i.e. functions, classes) for
different themes.
Params:
* name - type of string. New global name for object
* themes - for this themes ``obj`` will be have alias with given name
* global_con... |
def md2pypi(filename):
'''
Load .md (markdown) file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badges
'''
content = io.open(filename).read()
for match in RE_MD_CODE_BLOCK.finditer(content):
rst_block = '\n'.join(
... | def function[md2pypi, parameter[filename]]:
constant[
Load .md (markdown) file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badges
]
variable[content] assign[=] call[call[name[io].open, parameter[name[filename]]].read, parameter... | keyword[def] identifier[md2pypi] ( identifier[filename] ):
literal[string]
identifier[content] = identifier[io] . identifier[open] ( identifier[filename] ). identifier[read] ()
keyword[for] identifier[match] keyword[in] identifier[RE_MD_CODE_BLOCK] . identifier[finditer] ( identifier[content] ):
... | def md2pypi(filename):
"""
Load .md (markdown) file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badges
"""
content = io.open(filename).read()
for match in RE_MD_CODE_BLOCK.finditer(content):
rst_block = '\n'.join(['.. code-... |
def export(self):
"""
Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object.
"""
return {'id' : self.id, 'name' : self.name, 'artist' : self._artist_name, 'artist_id' : self._artist_id, 'cover' : self._co... | def function[export, parameter[self]]:
constant[
Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object.
]
return[dictionary[[<ast.Constant object at 0x7da1b28be740>, <ast.Constant object at 0x7da1b28be7d0>, <... | keyword[def] identifier[export] ( identifier[self] ):
literal[string]
keyword[return] { literal[string] : identifier[self] . identifier[id] , literal[string] : identifier[self] . identifier[name] , literal[string] : identifier[self] . identifier[_artist_name] , literal[string] : identifier[self] . ... | def export(self):
"""
Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object.
"""
return {'id': self.id, 'name': self.name, 'artist': self._artist_name, 'artist_id': self._artist_id, 'cover': self._cover_url} |
def post_task(task_data, task_uri='/tasks'):
"""Create Spinnaker Task.
Args:
task_data (str): Task JSON definition.
Returns:
str: Spinnaker Task ID.
Raises:
AssertionError: Error response from Spinnaker.
"""
url = '{}/{}'.format(API_URL, task_uri.lstrip('/'))
if ... | def function[post_task, parameter[task_data, task_uri]]:
constant[Create Spinnaker Task.
Args:
task_data (str): Task JSON definition.
Returns:
str: Spinnaker Task ID.
Raises:
AssertionError: Error response from Spinnaker.
]
variable[url] assign[=] call[constan... | keyword[def] identifier[post_task] ( identifier[task_data] , identifier[task_uri] = literal[string] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[API_URL] , identifier[task_uri] . identifier[lstrip] ( literal[string] ))
keyword[if] identifier[isinstance] ( id... | def post_task(task_data, task_uri='/tasks'):
"""Create Spinnaker Task.
Args:
task_data (str): Task JSON definition.
Returns:
str: Spinnaker Task ID.
Raises:
AssertionError: Error response from Spinnaker.
"""
url = '{}/{}'.format(API_URL, task_uri.lstrip('/'))
if i... |
def confirm_email(self, confirmation_key):
"""
Confirm an email address by checking a ``confirmation_key``.
A valid ``confirmation_key`` will set the newly wanted e-mail
address as the current e-mail address. Returns the user after
success or ``False`` when the confirmation key ... | def function[confirm_email, parameter[self, confirmation_key]]:
constant[
Confirm an email address by checking a ``confirmation_key``.
A valid ``confirmation_key`` will set the newly wanted e-mail
address as the current e-mail address. Returns the user after
success or ``False``... | keyword[def] identifier[confirm_email] ( identifier[self] , identifier[confirmation_key] ):
literal[string]
keyword[if] identifier[SHA1_RE] . identifier[search] ( identifier[confirmation_key] ):
keyword[try] :
identifier[userena] = identifier[self] . identifier[get] (... | def confirm_email(self, confirmation_key):
"""
Confirm an email address by checking a ``confirmation_key``.
A valid ``confirmation_key`` will set the newly wanted e-mail
address as the current e-mail address. Returns the user after
success or ``False`` when the confirmation key is
... |
def module_path(self, filepath):
"""given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported"""
possible_modbits = re.split('[\\/]', filepath.strip('\\/'))
basename = possible_modbits[-1]
prefixes = possible_modbits[0:-1]
... | def function[module_path, parameter[self, filepath]]:
constant[given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported]
variable[possible_modbits] assign[=] call[name[re].split, parameter[constant[[\/]], call[name[filepath].strip, parameter[cons... | keyword[def] identifier[module_path] ( identifier[self] , identifier[filepath] ):
literal[string]
identifier[possible_modbits] = identifier[re] . identifier[split] ( literal[string] , identifier[filepath] . identifier[strip] ( literal[string] ))
identifier[basename] = identifier[possible_m... | def module_path(self, filepath):
"""given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported"""
possible_modbits = re.split('[\\/]', filepath.strip('\\/'))
basename = possible_modbits[-1]
prefixes = possible_modbits[0:-1]
modpath = []
dis... |
def delete(method, hmc, uri, uri_parms, logon_required):
"""Operation: Delete <resource>."""
try:
resource = hmc.lookup_by_uri(uri)
except KeyError:
raise InvalidResourceError(method, uri)
resource.manager.remove(resource.oid) | def function[delete, parameter[method, hmc, uri, uri_parms, logon_required]]:
constant[Operation: Delete <resource>.]
<ast.Try object at 0x7da1b0592b30>
call[name[resource].manager.remove, parameter[name[resource].oid]] | keyword[def] identifier[delete] ( identifier[method] , identifier[hmc] , identifier[uri] , identifier[uri_parms] , identifier[logon_required] ):
literal[string]
keyword[try] :
identifier[resource] = identifier[hmc] . identifier[lookup_by_uri] ( identifier[uri] )
keyword[except... | def delete(method, hmc, uri, uri_parms, logon_required):
"""Operation: Delete <resource>."""
try:
resource = hmc.lookup_by_uri(uri) # depends on [control=['try'], data=[]]
except KeyError:
raise InvalidResourceError(method, uri) # depends on [control=['except'], data=[]]
resource.manag... |
def Write(self, grr_message):
"""Write the message into the transaction log."""
grr_message = grr_message.SerializeToString()
try:
with io.open(self.logfile, "wb") as fd:
fd.write(grr_message)
except (IOError, OSError):
# Check if we're missing directories and try to create them.
... | def function[Write, parameter[self, grr_message]]:
constant[Write the message into the transaction log.]
variable[grr_message] assign[=] call[name[grr_message].SerializeToString, parameter[]]
<ast.Try object at 0x7da1b1c0f310> | keyword[def] identifier[Write] ( identifier[self] , identifier[grr_message] ):
literal[string]
identifier[grr_message] = identifier[grr_message] . identifier[SerializeToString] ()
keyword[try] :
keyword[with] identifier[io] . identifier[open] ( identifier[self] . identifier[logfile] , literal... | def Write(self, grr_message):
"""Write the message into the transaction log."""
grr_message = grr_message.SerializeToString()
try:
with io.open(self.logfile, 'wb') as fd:
fd.write(grr_message) # depends on [control=['with'], data=['fd']] # depends on [control=['try'], data=[]]
exce... |
def _dist(self, x, y):
"""Return ``self.dist(x, y)``."""
if self.is_uniform and not self.is_uniformly_weighted:
bdry_fracs = self.partition.boundary_cell_fractions
func_list = _scaling_func_list(bdry_fracs, exponent=self.exponent)
arrs = [apply_on_boundary(vec, func=f... | def function[_dist, parameter[self, x, y]]:
constant[Return ``self.dist(x, y)``.]
if <ast.BoolOp object at 0x7da1b20b6e00> begin[:]
variable[bdry_fracs] assign[=] name[self].partition.boundary_cell_fractions
variable[func_list] assign[=] call[name[_scaling_func_list], par... | keyword[def] identifier[_dist] ( identifier[self] , identifier[x] , identifier[y] ):
literal[string]
keyword[if] identifier[self] . identifier[is_uniform] keyword[and] keyword[not] identifier[self] . identifier[is_uniformly_weighted] :
identifier[bdry_fracs] = identifier[self] . id... | def _dist(self, x, y):
"""Return ``self.dist(x, y)``."""
if self.is_uniform and (not self.is_uniformly_weighted):
bdry_fracs = self.partition.boundary_cell_fractions
func_list = _scaling_func_list(bdry_fracs, exponent=self.exponent)
arrs = [apply_on_boundary(vec, func=func_list, only_onc... |
def xpartial(func, *xargs, **xkwargs):
"""
Like :func:`functools.partial`, but can take an :class:`XObject`
placeholder that will be replaced with the first positional argument
when the partially applied function is called.
Useful when the function's positional arguments' order doesn't fit your
... | def function[xpartial, parameter[func]]:
constant[
Like :func:`functools.partial`, but can take an :class:`XObject`
placeholder that will be replaced with the first positional argument
when the partially applied function is called.
Useful when the function's positional arguments' order doesn't ... | keyword[def] identifier[xpartial] ( identifier[func] ,* identifier[xargs] ,** identifier[xkwargs] ):
literal[string]
identifier[any_x] = identifier[any] ( identifier[isinstance] ( identifier[a] , identifier[XObject] ) keyword[for] identifier[a] keyword[in] identifier[xargs] + identifier[tuple] ( identif... | def xpartial(func, *xargs, **xkwargs):
"""
Like :func:`functools.partial`, but can take an :class:`XObject`
placeholder that will be replaced with the first positional argument
when the partially applied function is called.
Useful when the function's positional arguments' order doesn't fit your
... |
def generic_adjust(colors, light):
"""Generic color adjustment for themers."""
if light:
for color in colors:
color = util.saturate_color(color, 0.60)
color = util.darken_color(color, 0.5)
colors[0] = util.lighten_color(colors[0], 0.95)
colors[7] = util.darken_co... | def function[generic_adjust, parameter[colors, light]]:
constant[Generic color adjustment for themers.]
if name[light] begin[:]
for taget[name[color]] in starred[name[colors]] begin[:]
variable[color] assign[=] call[name[util].saturate_color, parameter[name[color]... | keyword[def] identifier[generic_adjust] ( identifier[colors] , identifier[light] ):
literal[string]
keyword[if] identifier[light] :
keyword[for] identifier[color] keyword[in] identifier[colors] :
identifier[color] = identifier[util] . identifier[saturate_color] ( identifier[color]... | def generic_adjust(colors, light):
"""Generic color adjustment for themers."""
if light:
for color in colors:
color = util.saturate_color(color, 0.6)
color = util.darken_color(color, 0.5) # depends on [control=['for'], data=['color']]
colors[0] = util.lighten_color(color... |
def parse_hh_mm_ss(self):
"""Parses raw time
:return: Time parsed
"""
split_count = self.raw.count(":")
if split_count == 2: # hh:mm:ss
return datetime.strptime(str(self.raw).strip(), "%H:%M:%S").time()
elif split_count == 1: # mm:ss
return dat... | def function[parse_hh_mm_ss, parameter[self]]:
constant[Parses raw time
:return: Time parsed
]
variable[split_count] assign[=] call[name[self].raw.count, parameter[constant[:]]]
if compare[name[split_count] equal[==] constant[2]] begin[:]
return[call[call[name[datetime].... | keyword[def] identifier[parse_hh_mm_ss] ( identifier[self] ):
literal[string]
identifier[split_count] = identifier[self] . identifier[raw] . identifier[count] ( literal[string] )
keyword[if] identifier[split_count] == literal[int] :
keyword[return] identifier[datetime] . id... | def parse_hh_mm_ss(self):
"""Parses raw time
:return: Time parsed
"""
split_count = self.raw.count(':')
if split_count == 2: # hh:mm:ss
return datetime.strptime(str(self.raw).strip(), '%H:%M:%S').time() # depends on [control=['if'], data=[]]
elif split_count == 1: # mm:ss
... |
def document_fromstring(html, guess_charset=True, parser=None):
"""Parse a whole document into a string."""
if not isinstance(html, _strings):
raise TypeError('string required')
if parser is None:
parser = html_parser
return parser.parse(html, useChardet=guess_charset).getroot() | def function[document_fromstring, parameter[html, guess_charset, parser]]:
constant[Parse a whole document into a string.]
if <ast.UnaryOp object at 0x7da18f8116c0> begin[:]
<ast.Raise object at 0x7da18f8132b0>
if compare[name[parser] is constant[None]] begin[:]
variable[... | keyword[def] identifier[document_fromstring] ( identifier[html] , identifier[guess_charset] = keyword[True] , identifier[parser] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[html] , identifier[_strings] ):
keyword[raise] identifier[TypeError] (... | def document_fromstring(html, guess_charset=True, parser=None):
"""Parse a whole document into a string."""
if not isinstance(html, _strings):
raise TypeError('string required') # depends on [control=['if'], data=[]]
if parser is None:
parser = html_parser # depends on [control=['if'], dat... |
def login(request, template_name=None, extra_context=None, **kwargs):
"""Logs a user in using the :class:`~openstack_auth.forms.Login` form."""
# If the user enabled websso and the default redirect
# redirect to the default websso url
if (request.method == 'GET' and utils.is_websso_enabled and
... | def function[login, parameter[request, template_name, extra_context]]:
constant[Logs a user in using the :class:`~openstack_auth.forms.Login` form.]
if <ast.BoolOp object at 0x7da1b1916950> begin[:]
variable[protocol] assign[=] call[name[utils].get_websso_default_redirect_protocol, param... | keyword[def] identifier[login] ( identifier[request] , identifier[template_name] = keyword[None] , identifier[extra_context] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] ( identifier[request] . identifier[method] == literal[string] keyword[and] identifier[utils] . iden... | def login(request, template_name=None, extra_context=None, **kwargs):
"""Logs a user in using the :class:`~openstack_auth.forms.Login` form."""
# If the user enabled websso and the default redirect
# redirect to the default websso url
if request.method == 'GET' and utils.is_websso_enabled and utils.is_w... |
def SetValue(self, row, col, value, refresh=True):
"""Set the value of a cell, merge line breaks"""
# Join code that has been split because of long line issue
value = "".join(value.split("\n"))
key = row, col, self.grid.current_table
old_code = self.grid.code_array(key)
... | def function[SetValue, parameter[self, row, col, value, refresh]]:
constant[Set the value of a cell, merge line breaks]
variable[value] assign[=] call[constant[].join, parameter[call[name[value].split, parameter[constant[
]]]]]
variable[key] assign[=] tuple[[<ast.Name object at 0x7da1b1518220>, ... | keyword[def] identifier[SetValue] ( identifier[self] , identifier[row] , identifier[col] , identifier[value] , identifier[refresh] = keyword[True] ):
literal[string]
identifier[value] = literal[string] . identifier[join] ( identifier[value] . identifier[split] ( literal[string] ))
... | def SetValue(self, row, col, value, refresh=True):
"""Set the value of a cell, merge line breaks"""
# Join code that has been split because of long line issue
value = ''.join(value.split('\n'))
key = (row, col, self.grid.current_table)
old_code = self.grid.code_array(key)
if old_code is None:
... |
def pkg_data_filename(resource_name, filename=None):
"""Returns the path of a file installed along the package
"""
resource_filename = pkg_resources.resource_filename(
tripleohelper.__name__,
resource_name
)
if filename is not None:
resource_filename = os.path.join(resource_f... | def function[pkg_data_filename, parameter[resource_name, filename]]:
constant[Returns the path of a file installed along the package
]
variable[resource_filename] assign[=] call[name[pkg_resources].resource_filename, parameter[name[tripleohelper].__name__, name[resource_name]]]
if compare[na... | keyword[def] identifier[pkg_data_filename] ( identifier[resource_name] , identifier[filename] = keyword[None] ):
literal[string]
identifier[resource_filename] = identifier[pkg_resources] . identifier[resource_filename] (
identifier[tripleohelper] . identifier[__name__] ,
identifier[resource_name]... | def pkg_data_filename(resource_name, filename=None):
"""Returns the path of a file installed along the package
"""
resource_filename = pkg_resources.resource_filename(tripleohelper.__name__, resource_name)
if filename is not None:
resource_filename = os.path.join(resource_filename, filename) # ... |
def search_modeltypes(self, *models: ModelTypesArg,
name: str = 'modeltypes') -> 'Selection':
"""Return a |Selection| object containing only the elements
currently handling models of the given types.
>>> from hydpy.core.examples import prepare_full_example_2
>>... | def function[search_modeltypes, parameter[self]]:
constant[Return a |Selection| object containing only the elements
currently handling models of the given types.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, _ = prepare_full_example_2()
You can pass bo... | keyword[def] identifier[search_modeltypes] ( identifier[self] ,* identifier[models] : identifier[ModelTypesArg] ,
identifier[name] : identifier[str] = literal[string] )-> literal[string] :
literal[string]
keyword[try] :
identifier[typelist] =[]
keyword[for] identifier[mo... | def search_modeltypes(self, *models: ModelTypesArg, name: str='modeltypes') -> 'Selection':
"""Return a |Selection| object containing only the elements
currently handling models of the given types.
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, _ = prepare_full_exam... |
def find_and_apply_best_mask(matrix, version, is_micro, proposed_mask=None):
"""\
Applies all mask patterns against the provided QR Code matrix and returns
the best matrix and best pattern.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data... | def function[find_and_apply_best_mask, parameter[matrix, version, is_micro, proposed_mask]]:
constant[ Applies all mask patterns against the provided QR Code matrix and returns
the best matrix and best pattern.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
ISO/IEC 18004:2015(E) -- ... | keyword[def] identifier[find_and_apply_best_mask] ( identifier[matrix] , identifier[version] , identifier[is_micro] , identifier[proposed_mask] = keyword[None] ):
literal[string]
identifier[matrix_size] = identifier[len] ( identifier[matrix] )
identifier[is_better] = identifier[lt]
... | def find_and_apply_best_mask(matrix, version, is_micro, proposed_mask=None):
""" Applies all mask patterns against the provided QR Code matrix and returns
the best matrix and best pattern.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data m... |
def stop(self):
""" Stop logging with this logger.
"""
if not self.active:
return
self.removeHandler(self.handlers[-1])
self.active = False
return | def function[stop, parameter[self]]:
constant[ Stop logging with this logger.
]
if <ast.UnaryOp object at 0x7da1b1435ba0> begin[:]
return[None]
call[name[self].removeHandler, parameter[call[name[self].handlers][<ast.UnaryOp object at 0x7da1b1437b80>]]]
name[self].active ... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[active] :
keyword[return]
identifier[self] . identifier[removeHandler] ( identifier[self] . identifier[handlers] [- literal[int] ])
identifier... | def stop(self):
""" Stop logging with this logger.
"""
if not self.active:
return # depends on [control=['if'], data=[]]
self.removeHandler(self.handlers[-1])
self.active = False
return |
def plot_contour_matrix(arrays,
fields,
filename,
weights=None,
sample_names=None,
sample_lines=None,
sample_colors=None,
color_map=None,
... | def function[plot_contour_matrix, parameter[arrays, fields, filename, weights, sample_names, sample_lines, sample_colors, color_map, num_bins, num_contours, cell_width, cell_height, cell_margin_x, cell_margin_y, dpi, padding, animate_field, animate_steps, animate_delay, animate_loop]]:
constant[
Create a ma... | keyword[def] identifier[plot_contour_matrix] ( identifier[arrays] ,
identifier[fields] ,
identifier[filename] ,
identifier[weights] = keyword[None] ,
identifier[sample_names] = keyword[None] ,
identifier[sample_lines] = keyword[None] ,
identifier[sample_colors] = keyword[None] ,
identifier[color_map] = keyword... | def plot_contour_matrix(arrays, fields, filename, weights=None, sample_names=None, sample_lines=None, sample_colors=None, color_map=None, num_bins=20, num_contours=3, cell_width=2, cell_height=2, cell_margin_x=0.05, cell_margin_y=0.05, dpi=100, padding=0, animate_field=None, animate_steps=10, animate_delay=20, animate_... |
def redirect_stdout(self):
"""Redirect stdout to file so that it can be tailed and aggregated with the other logs."""
self.hijacked_stdout = sys.stdout
self.hijacked_stderr = sys.stderr
# 0 must be set as the buffer, otherwise lines won't get logged in time.
sys.stdout = open(sel... | def function[redirect_stdout, parameter[self]]:
constant[Redirect stdout to file so that it can be tailed and aggregated with the other logs.]
name[self].hijacked_stdout assign[=] name[sys].stdout
name[self].hijacked_stderr assign[=] name[sys].stderr
name[sys].stdout assign[=] call[name[... | keyword[def] identifier[redirect_stdout] ( identifier[self] ):
literal[string]
identifier[self] . identifier[hijacked_stdout] = identifier[sys] . identifier[stdout]
identifier[self] . identifier[hijacked_stderr] = identifier[sys] . identifier[stderr]
identifier[sys] . i... | def redirect_stdout(self):
"""Redirect stdout to file so that it can be tailed and aggregated with the other logs."""
self.hijacked_stdout = sys.stdout
self.hijacked_stderr = sys.stderr
# 0 must be set as the buffer, otherwise lines won't get logged in time.
sys.stdout = open(self.hitch_dir.driverou... |
def eeg_create_mne_events(onsets, conditions=None):
"""
Create MNE compatible events.
Parameters
----------
onsets : list or array
Events onsets.
conditions : list
A list of equal length containing the stimuli types/conditions.
Returns
----------
(events, event_id)... | def function[eeg_create_mne_events, parameter[onsets, conditions]]:
constant[
Create MNE compatible events.
Parameters
----------
onsets : list or array
Events onsets.
conditions : list
A list of equal length containing the stimuli types/conditions.
Returns
-------... | keyword[def] identifier[eeg_create_mne_events] ( identifier[onsets] , identifier[conditions] = keyword[None] ):
literal[string]
identifier[event_id] ={}
keyword[if] identifier[conditions] keyword[is] keyword[None] :
identifier[conditions] =[ literal[string] ]* identifier[len] ( identifier... | def eeg_create_mne_events(onsets, conditions=None):
"""
Create MNE compatible events.
Parameters
----------
onsets : list or array
Events onsets.
conditions : list
A list of equal length containing the stimuli types/conditions.
Returns
----------
(events, event_id)... |
def _to_add_with_category(self, catid):
'''
Used for info2.
:param catid: the uid of category
'''
catinfo = MCategory.get_by_uid(catid)
kwd = {
'uid': self._gen_uid(),
'userid': self.userinfo.user_name if self.userinfo else '',
'gcat0'... | def function[_to_add_with_category, parameter[self, catid]]:
constant[
Used for info2.
:param catid: the uid of category
]
variable[catinfo] assign[=] call[name[MCategory].get_by_uid, parameter[name[catid]]]
variable[kwd] assign[=] dictionary[[<ast.Constant object at 0x7d... | keyword[def] identifier[_to_add_with_category] ( identifier[self] , identifier[catid] ):
literal[string]
identifier[catinfo] = identifier[MCategory] . identifier[get_by_uid] ( identifier[catid] )
identifier[kwd] ={
literal[string] : identifier[self] . identifier[_gen_uid] (),
... | def _to_add_with_category(self, catid):
"""
Used for info2.
:param catid: the uid of category
"""
catinfo = MCategory.get_by_uid(catid)
kwd = {'uid': self._gen_uid(), 'userid': self.userinfo.user_name if self.userinfo else '', 'gcat0': catid, 'parentname': MCategory.get_by_uid(catinf... |
def sample_f(self, f, *args, **kwargs):
r"""Evaluated method f for all samples
Calls f(\*args, \*\*kwargs) on all samples.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
... | def function[sample_f, parameter[self, f]]:
constant[Evaluated method f for all samples
Calls f(\*args, \*\*kwargs) on all samples.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
... | keyword[def] identifier[sample_f] ( identifier[self] , identifier[f] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_check_samples_available] ()
keyword[return] [ identifier[call_member] ( identifier[M] , identifier[f] ,* identifier[arg... | def sample_f(self, f, *args, **kwargs):
"""Evaluated method f for all samples
Calls f(\\*args, \\*\\*kwargs) on all samples.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
... |
def _find_read_pos(self) -> Optional[int]:
"""Attempts to find a position in the read buffer that satisfies
the currently-pending read.
Returns a position in the buffer if the current read can be satisfied,
or None if it cannot.
"""
if self._read_bytes is not None and (
... | def function[_find_read_pos, parameter[self]]:
constant[Attempts to find a position in the read buffer that satisfies
the currently-pending read.
Returns a position in the buffer if the current read can be satisfied,
or None if it cannot.
]
if <ast.BoolOp object at 0x7da... | keyword[def] identifier[_find_read_pos] ( identifier[self] )-> identifier[Optional] [ identifier[int] ]:
literal[string]
keyword[if] identifier[self] . identifier[_read_bytes] keyword[is] keyword[not] keyword[None] keyword[and] (
identifier[self] . identifier[_read_buffer_size] >= ide... | def _find_read_pos(self) -> Optional[int]:
"""Attempts to find a position in the read buffer that satisfies
the currently-pending read.
Returns a position in the buffer if the current read can be satisfied,
or None if it cannot.
"""
if self._read_bytes is not None and (self._rea... |
def _set_axis_limits(self, axis, view, subplots, ranges):
"""
Compute extents for current view and apply as axis limits
"""
# Extents
extents = self.get_extents(view, ranges)
if not extents or self.overlaid:
axis.autoscale_view(scalex=True, scaley=True)
... | def function[_set_axis_limits, parameter[self, axis, view, subplots, ranges]]:
constant[
Compute extents for current view and apply as axis limits
]
variable[extents] assign[=] call[name[self].get_extents, parameter[name[view], name[ranges]]]
if <ast.BoolOp object at 0x7da1b1acfe... | keyword[def] identifier[_set_axis_limits] ( identifier[self] , identifier[axis] , identifier[view] , identifier[subplots] , identifier[ranges] ):
literal[string]
identifier[extents] = identifier[self] . identifier[get_extents] ( identifier[view] , identifier[ranges] )
keyword[if] ... | def _set_axis_limits(self, axis, view, subplots, ranges):
"""
Compute extents for current view and apply as axis limits
"""
# Extents
extents = self.get_extents(view, ranges)
if not extents or self.overlaid:
axis.autoscale_view(scalex=True, scaley=True)
return # depends ... |
def run(self):
"""Run GapFill command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Calculate penalty if penalty file exists
... | def function[run, parameter[self]]:
constant[Run GapFill command]
def function[compound_name, parameter[id]]:
if compare[name[id] <ast.NotIn object at 0x7da2590d7190> name[self]._model.compounds] begin[:]
return[name[id]]
return[call[call[name[self]._model.compounds][... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[def] identifier[compound_name] ( identifier[id] ):
keyword[if] identifier[id] keyword[not] keyword[in] identifier[self] . identifier[_model] . identifier[compounds] :
keyword[retu... | def run(self):
"""Run GapFill command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id # depends on [control=['if'], data=['id']]
return self._model.compounds[id].properties.get('name', id)
# Calculate penalty if penalty fi... |
def read_xdg_config_home(name, extension):
"""
Read from file found in XDG-specified configuration home directory,
expanding to ``${HOME}/.config/name.extension`` by default. Depends on
``XDG_CONFIG_HOME`` or ``HOME`` environment variables.
:param name: application or configuration set name
:pa... | def function[read_xdg_config_home, parameter[name, extension]]:
constant[
Read from file found in XDG-specified configuration home directory,
expanding to ``${HOME}/.config/name.extension`` by default. Depends on
``XDG_CONFIG_HOME`` or ``HOME`` environment variables.
:param name: application or... | keyword[def] identifier[read_xdg_config_home] ( identifier[name] , identifier[extension] ):
literal[string]
identifier[config_home] = identifier[environ] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[config_home] :
identifier[config_home] = identif... | def read_xdg_config_home(name, extension):
"""
Read from file found in XDG-specified configuration home directory,
expanding to ``${HOME}/.config/name.extension`` by default. Depends on
``XDG_CONFIG_HOME`` or ``HOME`` environment variables.
:param name: application or configuration set name
:pa... |
def categorymembers(
self,
page: 'WikipediaPage',
**kwargs
) -> PagesDict:
"""
Returns pages in given category with respect to parameters
API Calls for parameters:
- https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bcategorymembers
... | def function[categorymembers, parameter[self, page]]:
constant[
Returns pages in given category with respect to parameters
API Calls for parameters:
- https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bcategorymembers
- https://www.mediawiki.org/wiki/API:Categoryme... | keyword[def] identifier[categorymembers] (
identifier[self] ,
identifier[page] : literal[string] ,
** identifier[kwargs]
)-> identifier[PagesDict] :
literal[string]
identifier[params] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[s... | def categorymembers(self, page: 'WikipediaPage', **kwargs) -> PagesDict:
"""
Returns pages in given category with respect to parameters
API Calls for parameters:
- https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bcategorymembers
- https://www.mediawiki.org/wiki/API:C... |
def construct_covariance_matrix(cvec, parallax, radial_velocity, radial_velocity_error):
"""
Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in
the Gaia catalogue and construct the covariance matrix.
Parameters
----------
cvec : array_like
... | def function[construct_covariance_matrix, parameter[cvec, parallax, radial_velocity, radial_velocity_error]]:
constant[
Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in
the Gaia catalogue and construct the covariance matrix.
Parameters
--------... | keyword[def] identifier[construct_covariance_matrix] ( identifier[cvec] , identifier[parallax] , identifier[radial_velocity] , identifier[radial_velocity_error] ):
literal[string]
keyword[if] identifier[np] . identifier[ndim] ( identifier[cvec] )== literal[int] :
identifier[cmat] = identifier[np... | def construct_covariance_matrix(cvec, parallax, radial_velocity, radial_velocity_error):
"""
Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in
the Gaia catalogue and construct the covariance matrix.
Parameters
----------
cvec : array_like
... |
def apply_theme(self, property_values):
''' Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so neither the caller nor the
... | def function[apply_theme, parameter[self, property_values]]:
constant[ Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so ... | keyword[def] identifier[apply_theme] ( identifier[self] , identifier[property_values] ):
literal[string]
identifier[old_dict] = identifier[self] . identifier[themed_values] ()
keyword[if] identifier[old_dict] keyword[is] identifier[property_values] :
keyword[retur... | def apply_theme(self, property_values):
""" Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so neither the caller nor the
... |
def validate_pin(pin):
""" Validate the given pin against the schema.
:param dict pin: The pin to validate:
:raises pypebbleapi.schemas.DocumentError: If the pin is not valid.
"""
v = _Validator(schemas.pin)
if v.validate(pin):
return
else:
raise schemas.DocumentError(errors... | def function[validate_pin, parameter[pin]]:
constant[ Validate the given pin against the schema.
:param dict pin: The pin to validate:
:raises pypebbleapi.schemas.DocumentError: If the pin is not valid.
]
variable[v] assign[=] call[name[_Validator], parameter[name[schemas].pin]]
if ... | keyword[def] identifier[validate_pin] ( identifier[pin] ):
literal[string]
identifier[v] = identifier[_Validator] ( identifier[schemas] . identifier[pin] )
keyword[if] identifier[v] . identifier[validate] ( identifier[pin] ):
keyword[return]
keyword[else] :
keyword[raise] ide... | def validate_pin(pin):
""" Validate the given pin against the schema.
:param dict pin: The pin to validate:
:raises pypebbleapi.schemas.DocumentError: If the pin is not valid.
"""
v = _Validator(schemas.pin)
if v.validate(pin):
return # depends on [control=['if'], data=[]]
else:
... |
def dictToH5(h5, d, link_copy=False):
""" Save a dictionary into an hdf5 file
h5py is not capable of handling dictionaries natively"""
global _array_cache
_array_cache = dict()
h5 = h5py.File(h5, mode="w")
dictToH5Group(d, h5["/"], link_copy=link_copy)
h5.close()
_array_cache = dict(... | def function[dictToH5, parameter[h5, d, link_copy]]:
constant[ Save a dictionary into an hdf5 file
h5py is not capable of handling dictionaries natively]
<ast.Global object at 0x7da1b0a22ad0>
variable[_array_cache] assign[=] call[name[dict], parameter[]]
variable[h5] assign[=] call[n... | keyword[def] identifier[dictToH5] ( identifier[h5] , identifier[d] , identifier[link_copy] = keyword[False] ):
literal[string]
keyword[global] identifier[_array_cache]
identifier[_array_cache] = identifier[dict] ()
identifier[h5] = identifier[h5py] . identifier[File] ( identifier[h5] , identifi... | def dictToH5(h5, d, link_copy=False):
""" Save a dictionary into an hdf5 file
h5py is not capable of handling dictionaries natively"""
global _array_cache
_array_cache = dict()
h5 = h5py.File(h5, mode='w')
dictToH5Group(d, h5['/'], link_copy=link_copy)
h5.close()
_array_cache = dict(... |
def render(self):
""" Returns generated html code.
"""
with codecs.open(self.template_file, encoding=self.encoding) as template_src:
template = jinja2.Template(template_src.read())
slides = self.fetch_contents(self.source)
context = self.get_template_vars(slides)
... | def function[render, parameter[self]]:
constant[ Returns generated html code.
]
with call[name[codecs].open, parameter[name[self].template_file]] begin[:]
variable[template] assign[=] call[name[jinja2].Template, parameter[call[name[template_src].read, parameter[]]]]
varia... | keyword[def] identifier[render] ( identifier[self] ):
literal[string]
keyword[with] identifier[codecs] . identifier[open] ( identifier[self] . identifier[template_file] , identifier[encoding] = identifier[self] . identifier[encoding] ) keyword[as] identifier[template_src] :
identifie... | def render(self):
""" Returns generated html code.
"""
with codecs.open(self.template_file, encoding=self.encoding) as template_src:
template = jinja2.Template(template_src.read()) # depends on [control=['with'], data=['template_src']]
slides = self.fetch_contents(self.source)
context =... |
def local_timezone(value):
"""Add the local timezone to `value` to make it aware."""
if hasattr(value, "tzinfo") and value.tzinfo is None:
return value.replace(tzinfo=dateutil.tz.tzlocal())
return value | def function[local_timezone, parameter[value]]:
constant[Add the local timezone to `value` to make it aware.]
if <ast.BoolOp object at 0x7da1b23b3a00> begin[:]
return[call[name[value].replace, parameter[]]]
return[name[value]] | keyword[def] identifier[local_timezone] ( identifier[value] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[value] , literal[string] ) keyword[and] identifier[value] . identifier[tzinfo] keyword[is] keyword[None] :
keyword[return] identifier[value] . identifier[replace] ( iden... | def local_timezone(value):
"""Add the local timezone to `value` to make it aware."""
if hasattr(value, 'tzinfo') and value.tzinfo is None:
return value.replace(tzinfo=dateutil.tz.tzlocal()) # depends on [control=['if'], data=[]]
return value |
async def Set(self, annotations):
'''
annotations : typing.Sequence[~EntityAnnotations]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Annotations',
request='Set',
v... | <ast.AsyncFunctionDef object at 0x7da1b0dbeec0> | keyword[async] keyword[def] identifier[Set] ( identifier[self] , identifier[annotations] ):
literal[string]
identifier[_params] = identifier[dict] ()
identifier[msg] = identifier[dict] ( identifier[type] = literal[string] ,
identifier[request] = literal[string] ,
... | async def Set(self, annotations):
"""
annotations : typing.Sequence[~EntityAnnotations]
Returns -> typing.Sequence[~ErrorResult]
"""
# map input types to rpc msg
_params = dict()
msg = dict(type='Annotations', request='Set', version=2, params=_params)
_params['annotations'] =... |
def mirror_pull(self, **kwargs):
"""Start the pull mirroring process for the project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed ... | def function[mirror_pull, parameter[self]]:
constant[Start the pull mirroring process for the project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If t... | keyword[def] identifier[mirror_pull] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[path] = literal[string] % identifier[self] . identifier[get_id] ()
identifier[self] . identifier[manager] . identifier[gitlab] . identifier[http_post] ( identifier[path] ,** identif... | def mirror_pull(self, **kwargs):
"""Start the pull mirroring process for the project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to p... |
def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field) | def function[varchar, parameter[anon, obj, field, val]]:
constant[
Returns random data for a varchar field.
]
return[call[name[anon].faker.varchar, parameter[]]] | keyword[def] identifier[varchar] ( identifier[anon] , identifier[obj] , identifier[field] , identifier[val] ):
literal[string]
keyword[return] identifier[anon] . identifier[faker] . identifier[varchar] ( identifier[field] = identifier[field] ) | def varchar(anon, obj, field, val):
"""
Returns random data for a varchar field.
"""
return anon.faker.varchar(field=field) |
def write_txt(refs):
'''Converts references to plain text format
'''
full_str = '\n'
lib_citation_desc, lib_citations = get_library_citation()
# Add the refs for the libarary at the top
full_str += '*' * 80 + '\n'
full_str += lib_citation_desc
full_str += '*' * 80 + '\n'
for r in l... | def function[write_txt, parameter[refs]]:
constant[Converts references to plain text format
]
variable[full_str] assign[=] constant[
]
<ast.Tuple object at 0x7da2041db9d0> assign[=] call[name[get_library_citation], parameter[]]
<ast.AugAssign object at 0x7da2041d8a60>
<ast.AugAssign ... | keyword[def] identifier[write_txt] ( identifier[refs] ):
literal[string]
identifier[full_str] = literal[string]
identifier[lib_citation_desc] , identifier[lib_citations] = identifier[get_library_citation] ()
identifier[full_str] += literal[string] * literal[int] + literal[string]
id... | def write_txt(refs):
"""Converts references to plain text format
"""
full_str = '\n'
(lib_citation_desc, lib_citations) = get_library_citation()
# Add the refs for the libarary at the top
full_str += '*' * 80 + '\n'
full_str += lib_citation_desc
full_str += '*' * 80 + '\n'
for r in l... |
def L(self):
r"""Cholesky decomposition of :math:`\mathrm B`.
.. math::
\mathrm B = \mathrm Q^{\intercal}\tilde{\mathrm{T}}\mathrm Q
+ \mathrm{S}^{-1}
"""
from numpy_sugar.linalg import ddot, sum2diag
if self._L_cache is not None:
return... | def function[L, parameter[self]]:
constant[Cholesky decomposition of :math:`\mathrm B`.
.. math::
\mathrm B = \mathrm Q^{\intercal}\tilde{\mathrm{T}}\mathrm Q
+ \mathrm{S}^{-1}
]
from relative_module[numpy_sugar.linalg] import module[ddot], module[sum2diag]
... | keyword[def] identifier[L] ( identifier[self] ):
literal[string]
keyword[from] identifier[numpy_sugar] . identifier[linalg] keyword[import] identifier[ddot] , identifier[sum2diag]
keyword[if] identifier[self] . identifier[_L_cache] keyword[is] keyword[not] keyword[None] :
... | def L(self):
"""Cholesky decomposition of :math:`\\mathrm B`.
.. math::
\\mathrm B = \\mathrm Q^{\\intercal}\\tilde{\\mathrm{T}}\\mathrm Q
+ \\mathrm{S}^{-1}
"""
from numpy_sugar.linalg import ddot, sum2diag
if self._L_cache is not None:
return self._L_c... |
def on_trial_remove(self, trial_runner, trial):
"""Notification when trial terminates.
Trial info is removed from bracket. Triggers halving if bracket is
not finished."""
bracket, _ = self._trial_info[trial]
bracket.cleanup_trial(trial)
if not bracket.finished():
... | def function[on_trial_remove, parameter[self, trial_runner, trial]]:
constant[Notification when trial terminates.
Trial info is removed from bracket. Triggers halving if bracket is
not finished.]
<ast.Tuple object at 0x7da18f58eec0> assign[=] call[name[self]._trial_info][name[trial]]
... | keyword[def] identifier[on_trial_remove] ( identifier[self] , identifier[trial_runner] , identifier[trial] ):
literal[string]
identifier[bracket] , identifier[_] = identifier[self] . identifier[_trial_info] [ identifier[trial] ]
identifier[bracket] . identifier[cleanup_trial] ( identifier[... | def on_trial_remove(self, trial_runner, trial):
"""Notification when trial terminates.
Trial info is removed from bracket. Triggers halving if bracket is
not finished."""
(bracket, _) = self._trial_info[trial]
bracket.cleanup_trial(trial)
if not bracket.finished():
self._process... |
def input(input_id, name, value_class=NumberValue):
"""Add input to controller"""
def _init():
return value_class(
name,
input_id=input_id,
is_input=True,
index=-1
)
def _decorator(cls):
setattr(c... | def function[input, parameter[input_id, name, value_class]]:
constant[Add input to controller]
def function[_init, parameter[]]:
return[call[name[value_class], parameter[name[name]]]]
def function[_decorator, parameter[cls]]:
call[name[setattr], parameter[name[cls], name[... | keyword[def] identifier[input] ( identifier[input_id] , identifier[name] , identifier[value_class] = identifier[NumberValue] ):
literal[string]
keyword[def] identifier[_init] ():
keyword[return] identifier[value_class] (
identifier[name] ,
identifier[input_i... | def input(input_id, name, value_class=NumberValue):
"""Add input to controller"""
def _init():
return value_class(name, input_id=input_id, is_input=True, index=-1)
def _decorator(cls):
setattr(cls, input_id, _init())
return cls
return _decorator |
def load_fixture(filename, kind, post_processor=None):
"""
Loads a file into entities of a given class, run the post_processor on each
instance before it's saved
"""
def _load(od, kind, post_processor, parent=None, presets={}):
"""
Loads a single dictionary (od) into an object, over... | def function[load_fixture, parameter[filename, kind, post_processor]]:
constant[
Loads a file into entities of a given class, run the post_processor on each
instance before it's saved
]
def function[_load, parameter[od, kind, post_processor, parent, presets]]:
constant[
... | keyword[def] identifier[load_fixture] ( identifier[filename] , identifier[kind] , identifier[post_processor] = keyword[None] ):
literal[string]
keyword[def] identifier[_load] ( identifier[od] , identifier[kind] , identifier[post_processor] , identifier[parent] = keyword[None] , identifier[presets] ={}):
... | def load_fixture(filename, kind, post_processor=None):
"""
Loads a file into entities of a given class, run the post_processor on each
instance before it's saved
"""
def _load(od, kind, post_processor, parent=None, presets={}):
"""
Loads a single dictionary (od) into an object, over... |
def _merge_array(lhs, rhs, type_):
"""Helper for '_merge_by_type'."""
element_type = type_.array_element_type
if element_type.code in _UNMERGEABLE_TYPES:
# Individual values cannot be merged, just concatenate
lhs.list_value.values.extend(rhs.list_value.values)
return lhs
lhs, rhs... | def function[_merge_array, parameter[lhs, rhs, type_]]:
constant[Helper for '_merge_by_type'.]
variable[element_type] assign[=] name[type_].array_element_type
if compare[name[element_type].code in name[_UNMERGEABLE_TYPES]] begin[:]
call[name[lhs].list_value.values.extend, paramet... | keyword[def] identifier[_merge_array] ( identifier[lhs] , identifier[rhs] , identifier[type_] ):
literal[string]
identifier[element_type] = identifier[type_] . identifier[array_element_type]
keyword[if] identifier[element_type] . identifier[code] keyword[in] identifier[_UNMERGEABLE_TYPES] :
... | def _merge_array(lhs, rhs, type_):
"""Helper for '_merge_by_type'."""
element_type = type_.array_element_type
if element_type.code in _UNMERGEABLE_TYPES:
# Individual values cannot be merged, just concatenate
lhs.list_value.values.extend(rhs.list_value.values)
return lhs # depends o... |
def update_customer(self, customer_id, **kwargs):
"""Update a customer."""
body = self._formdata(kwargs, FastlyCustomer.FIELDS)
content = self._fetch("/customer/%s" % customer_id, method="PUT", body=body)
return FastlyCustomer(self, content) | def function[update_customer, parameter[self, customer_id]]:
constant[Update a customer.]
variable[body] assign[=] call[name[self]._formdata, parameter[name[kwargs], name[FastlyCustomer].FIELDS]]
variable[content] assign[=] call[name[self]._fetch, parameter[binary_operation[constant[/customer/%s... | keyword[def] identifier[update_customer] ( identifier[self] , identifier[customer_id] ,** identifier[kwargs] ):
literal[string]
identifier[body] = identifier[self] . identifier[_formdata] ( identifier[kwargs] , identifier[FastlyCustomer] . identifier[FIELDS] )
identifier[content] = identifier[self] . identi... | def update_customer(self, customer_id, **kwargs):
"""Update a customer."""
body = self._formdata(kwargs, FastlyCustomer.FIELDS)
content = self._fetch('/customer/%s' % customer_id, method='PUT', body=body)
return FastlyCustomer(self, content) |
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
respo... | def function[_volume_get, parameter[self, volume_id]]:
constant[
Organize information about a volume from the volume_id
]
if compare[name[self].volume_conn is constant[None]] begin[:]
<ast.Raise object at 0x7da1b21a04f0>
variable[nt_ks] assign[=] name[self].volume_conn
... | keyword[def] identifier[_volume_get] ( identifier[self] , identifier[volume_id] ):
literal[string]
keyword[if] identifier[self] . identifier[volume_conn] keyword[is] keyword[None] :
keyword[raise] identifier[SaltCloudSystemExit] ( literal[string] )
identifier[nt_ks] = iden... | def _volume_get(self, volume_id):
"""
Organize information about a volume from the volume_id
"""
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available') # depends on [control=['if'], data=[]]
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volu... |
def has_address(self, address):
"""
is the given address on the don't send list?
"""
queryset = self.filter(to_address__iexact=address)
return queryset.exists() | def function[has_address, parameter[self, address]]:
constant[
is the given address on the don't send list?
]
variable[queryset] assign[=] call[name[self].filter, parameter[]]
return[call[name[queryset].exists, parameter[]]] | keyword[def] identifier[has_address] ( identifier[self] , identifier[address] ):
literal[string]
identifier[queryset] = identifier[self] . identifier[filter] ( identifier[to_address__iexact] = identifier[address] )
keyword[return] identifier[queryset] . identifier[exists] () | def has_address(self, address):
"""
is the given address on the don't send list?
"""
queryset = self.filter(to_address__iexact=address)
return queryset.exists() |
def remove_wirevector(self, wirevector):
""" Remove a wirevector object to the block."""
self.wirevector_set.remove(wirevector)
del self.wirevector_by_name[wirevector.name] | def function[remove_wirevector, parameter[self, wirevector]]:
constant[ Remove a wirevector object to the block.]
call[name[self].wirevector_set.remove, parameter[name[wirevector]]]
<ast.Delete object at 0x7da20e962e30> | keyword[def] identifier[remove_wirevector] ( identifier[self] , identifier[wirevector] ):
literal[string]
identifier[self] . identifier[wirevector_set] . identifier[remove] ( identifier[wirevector] )
keyword[del] identifier[self] . identifier[wirevector_by_name] [ identifier[wirevector] .... | def remove_wirevector(self, wirevector):
""" Remove a wirevector object to the block."""
self.wirevector_set.remove(wirevector)
del self.wirevector_by_name[wirevector.name] |
def Execute(self, http):
"""Execute all the requests as a single batched HTTP request.
Args:
http: A httplib2.Http object to be used with the request.
Returns:
None
Raises:
BatchError if the response is the wrong format.
"""
self._Execute... | def function[Execute, parameter[self, http]]:
constant[Execute all the requests as a single batched HTTP request.
Args:
http: A httplib2.Http object to be used with the request.
Returns:
None
Raises:
BatchError if the response is the wrong format.
... | keyword[def] identifier[Execute] ( identifier[self] , identifier[http] ):
literal[string]
identifier[self] . identifier[_Execute] ( identifier[http] )
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[__request_response_handlers] :
identifier[response... | def Execute(self, http):
"""Execute all the requests as a single batched HTTP request.
Args:
http: A httplib2.Http object to be used with the request.
Returns:
None
Raises:
BatchError if the response is the wrong format.
"""
self._Execute(http)
... |
def _getPhrase( self, i, sentence, NPlabels ):
''' Fetches the full length phrase from the position i
based on the existing NP phrase annotations (from
NPlabels);
Returns list of sentence tokens in the phrase, and
indices of the phrase;
'''
... | def function[_getPhrase, parameter[self, i, sentence, NPlabels]]:
constant[ Fetches the full length phrase from the position i
based on the existing NP phrase annotations (from
NPlabels);
Returns list of sentence tokens in the phrase, and
indices of the phrase;
... | keyword[def] identifier[_getPhrase] ( identifier[self] , identifier[i] , identifier[sentence] , identifier[NPlabels] ):
literal[string]
identifier[phrase] =[]
identifier[indices] =[]
keyword[if] literal[int] <= identifier[i] keyword[and] identifier[i] < identifier[len] ( id... | def _getPhrase(self, i, sentence, NPlabels):
""" Fetches the full length phrase from the position i
based on the existing NP phrase annotations (from
NPlabels);
Returns list of sentence tokens in the phrase, and
indices of the phrase;
"""
phrase = []
... |
def _GetMemberForOffset(self, offset):
"""Finds the member whose data includes the provided offset.
Args:
offset (int): offset in the uncompressed data to find the
containing member for.
Returns:
gzipfile.GzipMember: gzip file member or None if not available.
Raises:
Value... | def function[_GetMemberForOffset, parameter[self, offset]]:
constant[Finds the member whose data includes the provided offset.
Args:
offset (int): offset in the uncompressed data to find the
containing member for.
Returns:
gzipfile.GzipMember: gzip file member or None if not avai... | keyword[def] identifier[_GetMemberForOffset] ( identifier[self] , identifier[offset] ):
literal[string]
keyword[if] identifier[offset] < literal[int] keyword[or] identifier[offset] >= identifier[self] . identifier[uncompressed_data_size] :
keyword[raise] identifier[ValueError] ( literal[string] ... | def _GetMemberForOffset(self, offset):
"""Finds the member whose data includes the provided offset.
Args:
offset (int): offset in the uncompressed data to find the
containing member for.
Returns:
gzipfile.GzipMember: gzip file member or None if not available.
Raises:
Value... |
def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'):
"Get the version of the specified program"
args_prog = [program, version_arg]
try:
proc = run(
args_prog,
close_fds=True,
universal_newlines=True,
stdout=PIPE,
st... | def function[get_version, parameter[program]]:
constant[Get the version of the specified program]
variable[args_prog] assign[=] list[[<ast.Name object at 0x7da1b1bc19c0>, <ast.Name object at 0x7da1b1bc1840>]]
<ast.Try object at 0x7da1b1bc0370>
<ast.Try object at 0x7da1b1bc17e0>
return[name[v... | keyword[def] identifier[get_version] ( identifier[program] ,*, identifier[version_arg] = literal[string] , identifier[regex] = literal[string] ):
literal[string]
identifier[args_prog] =[ identifier[program] , identifier[version_arg] ]
keyword[try] :
identifier[proc] = identifier[run] (
... | def get_version(program, *, version_arg='--version', regex='(\\d+(\\.\\d+)*)'):
"""Get the version of the specified program"""
args_prog = [program, version_arg]
try:
proc = run(args_prog, close_fds=True, universal_newlines=True, stdout=PIPE, stderr=STDOUT, check=True)
output = proc.stdout ... |
def connect(self, dialect=None, timeout=60):
"""
Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties th... | def function[connect, parameter[self, dialect, timeout]]:
constant[
Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various conne... | keyword[def] identifier[connect] ( identifier[self] , identifier[dialect] = keyword[None] , identifier[timeout] = literal[int] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] )
identifier[self] . identifier[transport] . identifier[connect] ()
identifier[lo... | def connect(self, dialect=None, timeout=60):
"""
Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties that d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.