code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _adjust_ser_count(self, plotArea, new_ser_count):
"""
Adjust the number of c:ser elements in *plotArea* to *new_ser_count*.
Excess c:ser elements are deleted from the end, along with any xChart
elements that are left empty as a result. Series elements are
considered in xChart... | def function[_adjust_ser_count, parameter[self, plotArea, new_ser_count]]:
constant[
Adjust the number of c:ser elements in *plotArea* to *new_ser_count*.
Excess c:ser elements are deleted from the end, along with any xChart
elements that are left empty as a result. Series elements are
... | keyword[def] identifier[_adjust_ser_count] ( identifier[self] , identifier[plotArea] , identifier[new_ser_count] ):
literal[string]
identifier[ser_count_diff] = identifier[new_ser_count] - identifier[len] ( identifier[plotArea] . identifier[sers] )
keyword[if] identifier[ser_count_diff] >... | def _adjust_ser_count(self, plotArea, new_ser_count):
"""
Adjust the number of c:ser elements in *plotArea* to *new_ser_count*.
Excess c:ser elements are deleted from the end, along with any xChart
elements that are left empty as a result. Series elements are
considered in xChart + s... |
def push_resource_cache(resourceid, info):
"""
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not... | def function[push_resource_cache, parameter[resourceid, info]]:
constant[
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
]
if <ast.UnaryOp object at 0x7da1b0c35780> begin[:]
<ast.Rai... | keyword[def] identifier[push_resource_cache] ( identifier[resourceid] , identifier[info] ):
literal[string]
keyword[if] keyword[not] identifier[resourceid] :
keyword[raise] identifier[ResourceInitError] ( literal[string] )
keyword[if] keyword[not] identifier[DutInformatio... | def push_resource_cache(resourceid, info):
"""
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
"""
if not resourceid:
raise ResourceInitError('Resource id missing') # depends on [control=['i... |
def check_comment_belongs_to_record(comid, recid):
"""
Return True if the comment is indeed part of given record (even if comment or/and record have
been "deleted"). Else return False.
:param comid: the id of the comment to check membership
:param recid: the recid of the record we want to check if ... | def function[check_comment_belongs_to_record, parameter[comid, recid]]:
constant[
Return True if the comment is indeed part of given record (even if comment or/and record have
been "deleted"). Else return False.
:param comid: the id of the comment to check membership
:param recid: the recid of ... | keyword[def] identifier[check_comment_belongs_to_record] ( identifier[comid] , identifier[recid] ):
literal[string]
identifier[query] = literal[string]
identifier[params] =( identifier[comid] ,)
identifier[res] = identifier[run_sql] ( identifier[query] , identifier[params] )
keyword[if] id... | def check_comment_belongs_to_record(comid, recid):
"""
Return True if the comment is indeed part of given record (even if comment or/and record have
been "deleted"). Else return False.
:param comid: the id of the comment to check membership
:param recid: the recid of the record we want to check if ... |
def post_comment(self, sharekey=None, comment=None):
"""
Post a comment on behalf of the current user to the
SharedFile with the given sharekey.
Args:
sharekey (str): Sharekey of the SharedFile to which you'd like
to post a comment.
comment (str):... | def function[post_comment, parameter[self, sharekey, comment]]:
constant[
Post a comment on behalf of the current user to the
SharedFile with the given sharekey.
Args:
sharekey (str): Sharekey of the SharedFile to which you'd like
to post a comment.
... | keyword[def] identifier[post_comment] ( identifier[self] , identifier[sharekey] = keyword[None] , identifier[comment] = keyword[None] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[format] ( identifier[sharekey] )
identifier[post_data] ={ literal[string] : identifi... | def post_comment(self, sharekey=None, comment=None):
"""
Post a comment on behalf of the current user to the
SharedFile with the given sharekey.
Args:
sharekey (str): Sharekey of the SharedFile to which you'd like
to post a comment.
comment (str): Tex... |
def BytesIO(*args, **kwargs):
"""BytesIO constructor shim for the async wrapper."""
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) | def function[BytesIO, parameter[]]:
constant[BytesIO constructor shim for the async wrapper.]
variable[raw] assign[=] call[name[sync_io].BytesIO, parameter[<ast.Starred object at 0x7da204620a30>]]
return[call[name[AsyncBytesIOWrapper], parameter[name[raw]]]] | keyword[def] identifier[BytesIO] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[raw] = identifier[sync_io] . identifier[BytesIO] (* identifier[args] ,** identifier[kwargs] )
keyword[return] identifier[AsyncBytesIOWrapper] ( identifier[raw] ) | def BytesIO(*args, **kwargs):
"""BytesIO constructor shim for the async wrapper."""
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) |
def siblingsId(self) -> Tuple[CtsReference, CtsReference]:
""" Siblings Identifiers of the passage
:rtype: (str, str)
"""
self._raise_depth()
if not self._text:
raise MissingAttribute("CapitainsCtsPassage was initiated without CtsTextMetadata object")
if sel... | def function[siblingsId, parameter[self]]:
constant[ Siblings Identifiers of the passage
:rtype: (str, str)
]
call[name[self]._raise_depth, parameter[]]
if <ast.UnaryOp object at 0x7da18bc72710> begin[:]
<ast.Raise object at 0x7da18bc71840>
if name[self]._prev_ne... | keyword[def] identifier[siblingsId] ( identifier[self] )-> identifier[Tuple] [ identifier[CtsReference] , identifier[CtsReference] ]:
literal[string]
identifier[self] . identifier[_raise_depth] ()
keyword[if] keyword[not] identifier[self] . identifier[_text] :
keyword[raise... | def siblingsId(self) -> Tuple[CtsReference, CtsReference]:
""" Siblings Identifiers of the passage
:rtype: (str, str)
"""
self._raise_depth()
if not self._text:
raise MissingAttribute('CapitainsCtsPassage was initiated without CtsTextMetadata object') # depends on [control=['if'], ... |
def focus_prev(self):
"""focus previous message in depth first order"""
mid = self.get_selected_mid()
localroot = self._sanitize_position((mid,))
if localroot == self.get_focus()[1]:
newpos = self._tree.prev_position(mid)
if newpos is not None:
new... | def function[focus_prev, parameter[self]]:
constant[focus previous message in depth first order]
variable[mid] assign[=] call[name[self].get_selected_mid, parameter[]]
variable[localroot] assign[=] call[name[self]._sanitize_position, parameter[tuple[[<ast.Name object at 0x7da1b07d1cf0>]]]]
... | keyword[def] identifier[focus_prev] ( identifier[self] ):
literal[string]
identifier[mid] = identifier[self] . identifier[get_selected_mid] ()
identifier[localroot] = identifier[self] . identifier[_sanitize_position] (( identifier[mid] ,))
keyword[if] identifier[localroot] == ide... | def focus_prev(self):
"""focus previous message in depth first order"""
mid = self.get_selected_mid()
localroot = self._sanitize_position((mid,))
if localroot == self.get_focus()[1]:
newpos = self._tree.prev_position(mid)
if newpos is not None:
newpos = self._sanitize_positio... |
def _fix_gatk_header(exist_files, out_file, config):
"""Ensure consistent headers for VCF concatenation.
Fixes problems for genomes that start with chrM by reheadering the first file.
These files do haploid variant calling which lack the PID phasing key/value
pair in FORMAT, so initial chrM samples cau... | def function[_fix_gatk_header, parameter[exist_files, out_file, config]]:
constant[Ensure consistent headers for VCF concatenation.
Fixes problems for genomes that start with chrM by reheadering the first file.
These files do haploid variant calling which lack the PID phasing key/value
pair in FORM... | keyword[def] identifier[_fix_gatk_header] ( identifier[exist_files] , identifier[out_file] , identifier[config] ):
literal[string]
keyword[from] identifier[bcbio] . identifier[variation] keyword[import] identifier[ploidy]
identifier[c] , identifier[base_file] = identifier[exist_files] [ literal[in... | def _fix_gatk_header(exist_files, out_file, config):
"""Ensure consistent headers for VCF concatenation.
Fixes problems for genomes that start with chrM by reheadering the first file.
These files do haploid variant calling which lack the PID phasing key/value
pair in FORMAT, so initial chrM samples cau... |
def parse(self):
"""
Parses the CSS contents and returns the cleaned CSS as a string
:returns: The cleaned CSS
:rtype: str
"""
# Build the HTML tree
self.tree = self._build_tree(self.html_contents)
# Parse the CSS contents
self.stylesheet = self.... | def function[parse, parameter[self]]:
constant[
Parses the CSS contents and returns the cleaned CSS as a string
:returns: The cleaned CSS
:rtype: str
]
name[self].tree assign[=] call[name[self]._build_tree, parameter[name[self].html_contents]]
name[self].styleshe... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
identifier[self] . identifier[tree] = identifier[self] . identifier[_build_tree] ( identifier[self] . identifier[html_contents] )
identifier[self] . identifier[stylesheet] = identifier[self] . identifie... | def parse(self):
"""
Parses the CSS contents and returns the cleaned CSS as a string
:returns: The cleaned CSS
:rtype: str
"""
# Build the HTML tree
self.tree = self._build_tree(self.html_contents)
# Parse the CSS contents
self.stylesheet = self.parser.parse_styleshe... |
def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
... | def function[paginate_query, parameter[self, query, paginate_info]]:
constant[Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
]
if compare[call[name[int],... | keyword[def] identifier[paginate_query] ( identifier[self] , identifier[query] , identifier[paginate_info] ):
literal[string]
keyword[if] identifier[int] ( identifier[paginate_info] . identifier[get] ( literal[string] , literal[int] ))== literal[int] :
keyword[return] identifier[quer... | def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
return q... |
def engine(self):
"""Return Render Engine."""
return self.backend({
'APP_DIRS': True,
'DIRS': [str(ROOT / self.backend.app_dirname)],
'NAME': 'djangoforms',
'OPTIONS': {},
}) | def function[engine, parameter[self]]:
constant[Return Render Engine.]
return[call[name[self].backend, parameter[dictionary[[<ast.Constant object at 0x7da1b1ed60b0>, <ast.Constant object at 0x7da1b1ed6770>, <ast.Constant object at 0x7da1b1ed6650>, <ast.Constant object at 0x7da1b1ed73d0>], [<ast.Constant obj... | keyword[def] identifier[engine] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[backend] ({
literal[string] : keyword[True] ,
literal[string] :[ identifier[str] ( identifier[ROOT] / identifier[self] . identifier[backend] . identifier[app_dirnam... | def engine(self):
"""Return Render Engine."""
return self.backend({'APP_DIRS': True, 'DIRS': [str(ROOT / self.backend.app_dirname)], 'NAME': 'djangoforms', 'OPTIONS': {}}) |
def merge_or_link(self, input_args, raw_folder, local_base="sample"):
"""
This function standardizes various input possibilities by converting
either .bam, .fastq, or .fastq.gz files into a local file; merging those
if multiple files given.
:param list input_args: This is a list... | def function[merge_or_link, parameter[self, input_args, raw_folder, local_base]]:
constant[
This function standardizes various input possibilities by converting
either .bam, .fastq, or .fastq.gz files into a local file; merging those
if multiple files given.
:param list input_ar... | keyword[def] identifier[merge_or_link] ( identifier[self] , identifier[input_args] , identifier[raw_folder] , identifier[local_base] = literal[string] ):
literal[string]
identifier[self] . identifier[make_sure_path_exists] ( identifier[raw_folder] )
keyword[if] keyword[not] identifier[i... | def merge_or_link(self, input_args, raw_folder, local_base='sample'):
"""
This function standardizes various input possibilities by converting
either .bam, .fastq, or .fastq.gz files into a local file; merging those
if multiple files given.
:param list input_args: This is a list of ... |
def morphTo(self, region):
""" Change shape of this region to match the given ``Region`` object """
if not region or not isinstance(region, Region):
raise TypeError("morphTo expected a Region object")
self.setROI(region)
return self | def function[morphTo, parameter[self, region]]:
constant[ Change shape of this region to match the given ``Region`` object ]
if <ast.BoolOp object at 0x7da2041db520> begin[:]
<ast.Raise object at 0x7da2041d8460>
call[name[self].setROI, parameter[name[region]]]
return[name[self]] | keyword[def] identifier[morphTo] ( identifier[self] , identifier[region] ):
literal[string]
keyword[if] keyword[not] identifier[region] keyword[or] keyword[not] identifier[isinstance] ( identifier[region] , identifier[Region] ):
keyword[raise] identifier[TypeError] ( literal[stri... | def morphTo(self, region):
""" Change shape of this region to match the given ``Region`` object """
if not region or not isinstance(region, Region):
raise TypeError('morphTo expected a Region object') # depends on [control=['if'], data=[]]
self.setROI(region)
return self |
def find_minimum_spanning_forest_as_subgraphs(graph):
"""Calculates the minimum spanning forest and returns a list of trees as subgraphs."""
forest = find_minimum_spanning_forest(graph)
list_of_subgraphs = [get_subgraph_from_edge_list(graph, edge_list) for edge_list in forest]
return list_of_subgraphs | def function[find_minimum_spanning_forest_as_subgraphs, parameter[graph]]:
constant[Calculates the minimum spanning forest and returns a list of trees as subgraphs.]
variable[forest] assign[=] call[name[find_minimum_spanning_forest], parameter[name[graph]]]
variable[list_of_subgraphs] assign[=] ... | keyword[def] identifier[find_minimum_spanning_forest_as_subgraphs] ( identifier[graph] ):
literal[string]
identifier[forest] = identifier[find_minimum_spanning_forest] ( identifier[graph] )
identifier[list_of_subgraphs] =[ identifier[get_subgraph_from_edge_list] ( identifier[graph] , identifier[edge_l... | def find_minimum_spanning_forest_as_subgraphs(graph):
"""Calculates the minimum spanning forest and returns a list of trees as subgraphs."""
forest = find_minimum_spanning_forest(graph)
list_of_subgraphs = [get_subgraph_from_edge_list(graph, edge_list) for edge_list in forest]
return list_of_subgraphs |
def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_... | def function[extract_fields, parameter[document_data, prefix_path, expand_dots]]:
constant[Do depth-first walk of tree, yielding field_path, value]
if <ast.UnaryOp object at 0x7da204564310> begin[:]
<ast.Yield object at 0x7da2045640a0> | keyword[def] identifier[extract_fields] ( identifier[document_data] , identifier[prefix_path] , identifier[expand_dots] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[document_data] :
keyword[yield] identifier[prefix_path] , identifier[_EmptyDict]
keyword[else] :
... | def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield (prefix_path, _EmptyDict) # depends on [control=['if'], data=[]]
else:
for (key, value) in sorted(six.iteritems(document_data)):
... |
def ProcessSources(
self, source_path_specs, storage_writer, resolver_context,
processing_configuration, filter_find_specs=None,
status_update_callback=None):
"""Processes the sources.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications of
the sources to proces... | def function[ProcessSources, parameter[self, source_path_specs, storage_writer, resolver_context, processing_configuration, filter_find_specs, status_update_callback]]:
constant[Processes the sources.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications of
the sources to proc... | keyword[def] identifier[ProcessSources] (
identifier[self] , identifier[source_path_specs] , identifier[storage_writer] , identifier[resolver_context] ,
identifier[processing_configuration] , identifier[filter_find_specs] = keyword[None] ,
identifier[status_update_callback] = keyword[None] ):
literal[string] ... | def ProcessSources(self, source_path_specs, storage_writer, resolver_context, processing_configuration, filter_find_specs=None, status_update_callback=None):
"""Processes the sources.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications of
the sources to process.
storage_wr... |
def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
**kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://s... | def function[to_yaml, parameter[obj, stream, dumper_cls, default_flow_style]]:
constant[
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.c... | keyword[def] identifier[to_yaml] ( identifier[obj] , identifier[stream] = keyword[None] , identifier[dumper_cls] = identifier[yaml] . identifier[Dumper] , identifier[default_flow_style] = keyword[False] ,
** identifier[kwargs] ):
literal[string]
keyword[class] identifier[OrderedDumper] ( identifier[dumpe... | def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False, **kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow... |
def Overlay(child, parent):
"""Adds hint attributes to a child hint if they are not defined."""
for arg in child, parent:
if not isinstance(arg, collections.Mapping):
raise DefinitionError("Trying to merge badly defined hints. Child: %s, "
"Parent: %s" % (type(child), type(pare... | def function[Overlay, parameter[child, parent]]:
constant[Adds hint attributes to a child hint if they are not defined.]
for taget[name[arg]] in starred[tuple[[<ast.Name object at 0x7da1b1cc13c0>, <ast.Name object at 0x7da1b1cc31c0>]]] begin[:]
if <ast.UnaryOp object at 0x7da1b1cc23b0> b... | keyword[def] identifier[Overlay] ( identifier[child] , identifier[parent] ):
literal[string]
keyword[for] identifier[arg] keyword[in] identifier[child] , identifier[parent] :
keyword[if] keyword[not] identifier[isinstance] ( identifier[arg] , identifier[collections] . identifier[Mapping] ):
ke... | def Overlay(child, parent):
"""Adds hint attributes to a child hint if they are not defined."""
for arg in (child, parent):
if not isinstance(arg, collections.Mapping):
raise DefinitionError('Trying to merge badly defined hints. Child: %s, Parent: %s' % (type(child), type(parent))) # depend... |
def prepare_relationships(db, known_tables):
"""Enrich the registered Models with SQLAlchemy ``relationships``
so that related tables are correctly processed up by the admin.
"""
inspector = reflection.Inspector.from_engine(db.engine)
for cls in set(known_tables.values()):
for foreign_key i... | def function[prepare_relationships, parameter[db, known_tables]]:
constant[Enrich the registered Models with SQLAlchemy ``relationships``
so that related tables are correctly processed up by the admin.
]
variable[inspector] assign[=] call[name[reflection].Inspector.from_engine, parameter[name[d... | keyword[def] identifier[prepare_relationships] ( identifier[db] , identifier[known_tables] ):
literal[string]
identifier[inspector] = identifier[reflection] . identifier[Inspector] . identifier[from_engine] ( identifier[db] . identifier[engine] )
keyword[for] identifier[cls] keyword[in] identifier[... | def prepare_relationships(db, known_tables):
"""Enrich the registered Models with SQLAlchemy ``relationships``
so that related tables are correctly processed up by the admin.
"""
inspector = reflection.Inspector.from_engine(db.engine)
for cls in set(known_tables.values()):
for foreign_key i... |
def run_basic_group():
"""Run the basic phase group example.
In this example, there are no terminal phases; all phases are run.
"""
test = htf.Test(htf.PhaseGroup(
setup=[setup_phase],
main=[main_phase],
teardown=[teardown_phase],
))
test.execute() | def function[run_basic_group, parameter[]]:
constant[Run the basic phase group example.
In this example, there are no terminal phases; all phases are run.
]
variable[test] assign[=] call[name[htf].Test, parameter[call[name[htf].PhaseGroup, parameter[]]]]
call[name[test].execute, parameter[]... | keyword[def] identifier[run_basic_group] ():
literal[string]
identifier[test] = identifier[htf] . identifier[Test] ( identifier[htf] . identifier[PhaseGroup] (
identifier[setup] =[ identifier[setup_phase] ],
identifier[main] =[ identifier[main_phase] ],
identifier[teardown] =[ identifier[teardown_phas... | def run_basic_group():
"""Run the basic phase group example.
In this example, there are no terminal phases; all phases are run.
"""
test = htf.Test(htf.PhaseGroup(setup=[setup_phase], main=[main_phase], teardown=[teardown_phase]))
test.execute() |
def splitname(path):
"""Split a path into a directory, name, and extensions."""
dirpath, filename = os.path.split(path)
# we don't use os.path.splitext here because we want all extensions,
# not just the last, to be put in exts
name, exts = filename.split(os.extsep, 1)
return dirpath, name, ext... | def function[splitname, parameter[path]]:
constant[Split a path into a directory, name, and extensions.]
<ast.Tuple object at 0x7da20c6e7e50> assign[=] call[name[os].path.split, parameter[name[path]]]
<ast.Tuple object at 0x7da20c6e4dc0> assign[=] call[name[filename].split, parameter[name[os].ex... | keyword[def] identifier[splitname] ( identifier[path] ):
literal[string]
identifier[dirpath] , identifier[filename] = identifier[os] . identifier[path] . identifier[split] ( identifier[path] )
identifier[name] , identifier[exts] = identifier[filename] . identifier[split] ( identifier[os] . i... | def splitname(path):
"""Split a path into a directory, name, and extensions."""
(dirpath, filename) = os.path.split(path)
# we don't use os.path.splitext here because we want all extensions,
# not just the last, to be put in exts
(name, exts) = filename.split(os.extsep, 1)
return (dirpath, name... |
def _filter_db_instances_by_status(awsclient, db_instances, status_list):
"""helper to select dbinstances.
:param awsclient:
:param db_instances:
:param status_list:
:return: list of db_instances that match the filter
"""
client_rds = awsclient.get_client('rds')
db_instances_with_status... | def function[_filter_db_instances_by_status, parameter[awsclient, db_instances, status_list]]:
constant[helper to select dbinstances.
:param awsclient:
:param db_instances:
:param status_list:
:return: list of db_instances that match the filter
]
variable[client_rds] assign[=] call[... | keyword[def] identifier[_filter_db_instances_by_status] ( identifier[awsclient] , identifier[db_instances] , identifier[status_list] ):
literal[string]
identifier[client_rds] = identifier[awsclient] . identifier[get_client] ( literal[string] )
identifier[db_instances_with_status] =[]
keyword[for... | def _filter_db_instances_by_status(awsclient, db_instances, status_list):
"""helper to select dbinstances.
:param awsclient:
:param db_instances:
:param status_list:
:return: list of db_instances that match the filter
"""
client_rds = awsclient.get_client('rds')
db_instances_with_status... |
def get_peer_cert_chain(self):
"""
Retrieve the other side's certificate (if any)
:return: A list of X509 instances giving the peer's certificate chain,
or None if it does not have one.
"""
cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
if cert_sta... | def function[get_peer_cert_chain, parameter[self]]:
constant[
Retrieve the other side's certificate (if any)
:return: A list of X509 instances giving the peer's certificate chain,
or None if it does not have one.
]
variable[cert_stack] assign[=] call[name[_lib].... | keyword[def] identifier[get_peer_cert_chain] ( identifier[self] ):
literal[string]
identifier[cert_stack] = identifier[_lib] . identifier[SSL_get_peer_cert_chain] ( identifier[self] . identifier[_ssl] )
keyword[if] identifier[cert_stack] == identifier[_ffi] . identifier[NULL] :
... | def get_peer_cert_chain(self):
"""
Retrieve the other side's certificate (if any)
:return: A list of X509 instances giving the peer's certificate chain,
or None if it does not have one.
"""
cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
if cert_stack == _ffi.N... |
def get_absolute_url(self):
"""Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`.
"""
try:
retur... | def function[get_absolute_url, parameter[self]]:
constant[Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`.
]
<... | keyword[def] identifier[get_absolute_url] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_registered] ( identifier[self] . identifier[default_panel] ). identifier[get_absolute_url] ()
keyword[except] identifier[Exception] :... | def get_absolute_url(self):
"""Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`.
"""
try:
return self._regi... |
def cmd(send, msg, args):
"""Queries WolframAlpha.
Syntax: {command} <expression>
"""
if not msg:
send("Evaluate what?")
return
params = {'format': 'plaintext', 'reinterpret': 'true', 'input': msg, 'appid': args['config']['api']['wolframapikey']}
req = get('http://api.wolframal... | def function[cmd, parameter[send, msg, args]]:
constant[Queries WolframAlpha.
Syntax: {command} <expression>
]
if <ast.UnaryOp object at 0x7da1b20d64a0> begin[:]
call[name[send], parameter[constant[Evaluate what?]]]
return[None]
variable[params] assign[=] dictio... | keyword[def] identifier[cmd] ( identifier[send] , identifier[msg] , identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[msg] :
identifier[send] ( literal[string] )
keyword[return]
identifier[params] ={ literal[string] : literal[string] , literal[string] : liter... | def cmd(send, msg, args):
"""Queries WolframAlpha.
Syntax: {command} <expression>
"""
if not msg:
send('Evaluate what?')
return # depends on [control=['if'], data=[]]
params = {'format': 'plaintext', 'reinterpret': 'true', 'input': msg, 'appid': args['config']['api']['wolframapike... |
def _set_ethernet(self, v, load=False):
"""
Setter method for ethernet, mapped from YANG variable /interface/ethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet is considered as a private
method. Backends looking to populate this variable should
... | def function[_set_ethernet, parameter[self, v, load]]:
constant[
Setter method for ethernet, mapped from YANG variable /interface/ethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet is considered as a private
method. Backends looking to popul... | keyword[def] identifier[_set_ethernet] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
ident... | def _set_ethernet(self, v, load=False):
"""
Setter method for ethernet, mapped from YANG variable /interface/ethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet is considered as a private
method. Backends looking to populate this variable should
... |
def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
... | def function[_handle_lines, parameter[self]]:
constant[Assemble incoming data into per-line packets.]
while compare[constant[b'\xdd'] in name[self]._buffer] begin[:]
<ast.Tuple object at 0x7da1b2780fa0> assign[=] call[name[self]._buffer.rsplit, parameter[constant[b'\xdd'], constant[1]]]
... | keyword[def] identifier[_handle_lines] ( identifier[self] ):
literal[string]
keyword[while] literal[string] keyword[in] identifier[self] . identifier[_buffer] :
identifier[linebuf] , identifier[self] . identifier[_buffer] = identifier[self] . identifier[_buffer] . identifier[rsplit]... | def _handle_lines(self):
"""Assemble incoming data into per-line packets."""
while b'\xdd' in self._buffer:
(linebuf, self._buffer) = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packe... |
def profile(fun, *args, **kwargs):
"""
Profile a function.
"""
timer_name = kwargs.pop("prof_name", None)
if not timer_name:
module = inspect.getmodule(fun)
c = [module.__name__]
parentclass = labtypes.get_class_that_defined_method(fun)
if parentclass:
c.... | def function[profile, parameter[fun]]:
constant[
Profile a function.
]
variable[timer_name] assign[=] call[name[kwargs].pop, parameter[constant[prof_name], constant[None]]]
if <ast.UnaryOp object at 0x7da18c4cf7f0> begin[:]
variable[module] assign[=] call[name[inspect].ge... | keyword[def] identifier[profile] ( identifier[fun] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[timer_name] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
keyword[if] keyword[not] identifier[timer_name] :
identifier[module] = identifi... | def profile(fun, *args, **kwargs):
"""
Profile a function.
"""
timer_name = kwargs.pop('prof_name', None)
if not timer_name:
module = inspect.getmodule(fun)
c = [module.__name__]
parentclass = labtypes.get_class_that_defined_method(fun)
if parentclass:
c.a... |
def duration(
days=0, # type: float
seconds=0, # type: float
microseconds=0, # type: float
milliseconds=0, # type: float
minutes=0, # type: float
hours=0, # type: float
weeks=0, # type: float
years=0, # type: float
months=0, # type: float
): # type: (...) -> Duration
""... | def function[duration, parameter[days, seconds, microseconds, milliseconds, minutes, hours, weeks, years, months]]:
constant[
Create a Duration instance.
]
return[call[name[Duration], parameter[]]] | keyword[def] identifier[duration] (
identifier[days] = literal[int] ,
identifier[seconds] = literal[int] ,
identifier[microseconds] = literal[int] ,
identifier[milliseconds] = literal[int] ,
identifier[minutes] = literal[int] ,
identifier[hours] = literal[int] ,
identifier[weeks] = literal[int] ,
identifier[y... | def duration(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0, years=0, months=0): # type: float
# type: float
# type: float
# type: float
# type: float
# type: float
# type: float
# type: float
# type: float
# type: (...) -> Duration
'\n Create ... |
def ParseDict(js_dict, message, ignore_unknown_fields=False):
"""Parses a JSON dictionary representation into a message.
Args:
js_dict: Dict representation of a JSON message.
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
Ret... | def function[ParseDict, parameter[js_dict, message, ignore_unknown_fields]]:
constant[Parses a JSON dictionary representation into a message.
Args:
js_dict: Dict representation of a JSON message.
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors... | keyword[def] identifier[ParseDict] ( identifier[js_dict] , identifier[message] , identifier[ignore_unknown_fields] = keyword[False] ):
literal[string]
identifier[parser] = identifier[_Parser] ( identifier[ignore_unknown_fields] )
identifier[parser] . identifier[ConvertMessage] ( identifier[js_dict] , identi... | def ParseDict(js_dict, message, ignore_unknown_fields=False):
"""Parses a JSON dictionary representation into a message.
Args:
js_dict: Dict representation of a JSON message.
message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
R... |
def _get_batch_name(sample):
"""Retrieve batch name for use in SV calling outputs.
Handles multiple batches split via SV calling.
"""
batch = dd.get_batch(sample) or dd.get_sample_name(sample)
if isinstance(batch, (list, tuple)) and len(batch) > 1:
batch = dd.get_sample_name(sample)
ret... | def function[_get_batch_name, parameter[sample]]:
constant[Retrieve batch name for use in SV calling outputs.
Handles multiple batches split via SV calling.
]
variable[batch] assign[=] <ast.BoolOp object at 0x7da1b2344670>
if <ast.BoolOp object at 0x7da1b23456f0> begin[:]
... | keyword[def] identifier[_get_batch_name] ( identifier[sample] ):
literal[string]
identifier[batch] = identifier[dd] . identifier[get_batch] ( identifier[sample] ) keyword[or] identifier[dd] . identifier[get_sample_name] ( identifier[sample] )
keyword[if] identifier[isinstance] ( identifier[batch] ,(... | def _get_batch_name(sample):
"""Retrieve batch name for use in SV calling outputs.
Handles multiple batches split via SV calling.
"""
batch = dd.get_batch(sample) or dd.get_sample_name(sample)
if isinstance(batch, (list, tuple)) and len(batch) > 1:
batch = dd.get_sample_name(sample) # depe... |
def get_slow_provider(self, timeout: int):
"""
Get web3 provider for slow queries. Default `HTTPProvider` timeouts after 10 seconds
:param provider: Configured Web3 provider
:param timeout: Timeout to configure for internal requests (default is 10)
:return: A new web3 provider wi... | def function[get_slow_provider, parameter[self, timeout]]:
constant[
Get web3 provider for slow queries. Default `HTTPProvider` timeouts after 10 seconds
:param provider: Configured Web3 provider
:param timeout: Timeout to configure for internal requests (default is 10)
:return: ... | keyword[def] identifier[get_slow_provider] ( identifier[self] , identifier[timeout] : identifier[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[w3_provider] , identifier[AutoProvider] ):
keyword[return] identifier[HTTPProvider] ( identifier... | def get_slow_provider(self, timeout: int):
"""
Get web3 provider for slow queries. Default `HTTPProvider` timeouts after 10 seconds
:param provider: Configured Web3 provider
:param timeout: Timeout to configure for internal requests (default is 10)
:return: A new web3 provider with t... |
def delete_credit_card(self, *, customer_id, credit_card_id):
"""
Delete a credit card (Token) associated with a user.
Args:
customer_id: Identifier of the client of whom you are going to delete the token.
credit_card_id: Identifier of the token to be deleted.
R... | def function[delete_credit_card, parameter[self]]:
constant[
Delete a credit card (Token) associated with a user.
Args:
customer_id: Identifier of the client of whom you are going to delete the token.
credit_card_id: Identifier of the token to be deleted.
Return... | keyword[def] identifier[delete_credit_card] ( identifier[self] ,*, identifier[customer_id] , identifier[credit_card_id] ):
literal[string]
identifier[fmt] = literal[string] . identifier[format] ( identifier[customer_id] , identifier[credit_card_id] )
keyword[return] identifier[self] . ide... | def delete_credit_card(self, *, customer_id, credit_card_id):
"""
Delete a credit card (Token) associated with a user.
Args:
customer_id: Identifier of the client of whom you are going to delete the token.
credit_card_id: Identifier of the token to be deleted.
Retur... |
async def get_timezone(self) -> Optional[tzinfo]:
"""
We can't exactly know the time zone of the user from what Facebook
gives (fucking morons) but we can still give something that'll work
until next DST.
"""
u = await self._get_user()
diff = float(u.get('timezon... | <ast.AsyncFunctionDef object at 0x7da18dc07a60> | keyword[async] keyword[def] identifier[get_timezone] ( identifier[self] )-> identifier[Optional] [ identifier[tzinfo] ]:
literal[string]
identifier[u] = keyword[await] identifier[self] . identifier[_get_user] ()
identifier[diff] = identifier[float] ( identifier[u] . identifier[get] ( li... | async def get_timezone(self) -> Optional[tzinfo]:
"""
We can't exactly know the time zone of the user from what Facebook
gives (fucking morons) but we can still give something that'll work
until next DST.
"""
u = await self._get_user()
diff = float(u.get('timezone', 0)) * 360... |
def add_node(self, node, offset):
"""Add a Node object to nodes dictionary, calculating its coordinates using offset
Parameters
----------
node : a Node object
offset : float
number between 0 and 1 that sets the distance
from the start point ... | def function[add_node, parameter[self, node, offset]]:
constant[Add a Node object to nodes dictionary, calculating its coordinates using offset
Parameters
----------
node : a Node object
offset : float
number between 0 and 1 that sets the distance
... | keyword[def] identifier[add_node] ( identifier[self] , identifier[node] , identifier[offset] ):
literal[string]
identifier[width] = identifier[self] . identifier[end] [ literal[int] ]- identifier[self] . identifier[start] [ literal[int] ]
identifier[height] = identifier[self] . id... | def add_node(self, node, offset):
"""Add a Node object to nodes dictionary, calculating its coordinates using offset
Parameters
----------
node : a Node object
offset : float
number between 0 and 1 that sets the distance
from the start point at w... |
def _pad_zeros(self, bunch_stack):
"""
:type bunch_stack: list of list
"""
min_len = min(map(len, bunch_stack))
for i in range(len(bunch_stack)):
bunch_stack[i] = bunch_stack[i][:min_len] | def function[_pad_zeros, parameter[self, bunch_stack]]:
constant[
:type bunch_stack: list of list
]
variable[min_len] assign[=] call[name[min], parameter[call[name[map], parameter[name[len], name[bunch_stack]]]]]
for taget[name[i]] in starred[call[name[range], parameter[call[name... | keyword[def] identifier[_pad_zeros] ( identifier[self] , identifier[bunch_stack] ):
literal[string]
identifier[min_len] = identifier[min] ( identifier[map] ( identifier[len] , identifier[bunch_stack] ))
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identif... | def _pad_zeros(self, bunch_stack):
"""
:type bunch_stack: list of list
"""
min_len = min(map(len, bunch_stack))
for i in range(len(bunch_stack)):
bunch_stack[i] = bunch_stack[i][:min_len] # depends on [control=['for'], data=['i']] |
def transmit(self, bytes, protocol=None):
'''Gain exclusive access to card during APDU transmission for if this
decorator decorates a PCSCCardConnection.'''
data, sw1, sw2 = CardConnectionDecorator.transmit(
self, bytes, protocol)
return data, sw1, sw2 | def function[transmit, parameter[self, bytes, protocol]]:
constant[Gain exclusive access to card during APDU transmission for if this
decorator decorates a PCSCCardConnection.]
<ast.Tuple object at 0x7da1b23ee6b0> assign[=] call[name[CardConnectionDecorator].transmit, parameter[name[self], name[... | keyword[def] identifier[transmit] ( identifier[self] , identifier[bytes] , identifier[protocol] = keyword[None] ):
literal[string]
identifier[data] , identifier[sw1] , identifier[sw2] = identifier[CardConnectionDecorator] . identifier[transmit] (
identifier[self] , identifier[bytes] , iden... | def transmit(self, bytes, protocol=None):
"""Gain exclusive access to card during APDU transmission for if this
decorator decorates a PCSCCardConnection."""
(data, sw1, sw2) = CardConnectionDecorator.transmit(self, bytes, protocol)
return (data, sw1, sw2) |
def tag(self, tokens):
"""Return a list of ((token, tag), label) tuples for a given list of (token, tag) tuples."""
# Lazy load model first time we tag
if not self._loaded_model:
self.load(self.model)
features = [self._get_features(tokens, i) for i in range(len(tokens))]
... | def function[tag, parameter[self, tokens]]:
constant[Return a list of ((token, tag), label) tuples for a given list of (token, tag) tuples.]
if <ast.UnaryOp object at 0x7da1b12c7fa0> begin[:]
call[name[self].load, parameter[name[self].model]]
variable[features] assign[=] <ast.Lis... | keyword[def] identifier[tag] ( identifier[self] , identifier[tokens] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_loaded_model] :
identifier[self] . identifier[load] ( identifier[self] . identifier[model] )
identifier[features] =[ ident... | def tag(self, tokens):
"""Return a list of ((token, tag), label) tuples for a given list of (token, tag) tuples."""
# Lazy load model first time we tag
if not self._loaded_model:
self.load(self.model) # depends on [control=['if'], data=[]]
features = [self._get_features(tokens, i) for i in rang... |
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True):
"""Find the common intersection with another surface.
Args:
other (Surface): Other surface to intersect with.
strategy (Optional[~bezier.curve.IntersectionStrategy]): The
intersection algorit... | def function[intersect, parameter[self, other, strategy, _verify]]:
constant[Find the common intersection with another surface.
Args:
other (Surface): Other surface to intersect with.
strategy (Optional[~bezier.curve.IntersectionStrategy]): The
intersection algor... | keyword[def] identifier[intersect] ( identifier[self] , identifier[other] , identifier[strategy] = identifier[_STRATEGY] . identifier[GEOMETRIC] , identifier[_verify] = keyword[True] ):
literal[string]
keyword[if] identifier[_verify] :
keyword[if] keyword[not] identifier[isinstance]... | def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True):
"""Find the common intersection with another surface.
Args:
other (Surface): Other surface to intersect with.
strategy (Optional[~bezier.curve.IntersectionStrategy]): The
intersection algorithm t... |
def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionar... | def function[model_fn, parameter[features, labels, mode, params, config]]:
constant[Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: So... | keyword[def] identifier[model_fn] ( identifier[features] , identifier[labels] , identifier[mode] , identifier[params] , identifier[config] ):
literal[string]
keyword[del] identifier[labels] , identifier[config]
identifier[logit_concentration] = identifier[tf] . identifier[compat] . identifier[v1] . id... | def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a diction... |
def set_extent_size(self, length, units):
"""
Sets the volume group extent size in the given units::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
vg.set_extent_size(2, "MiB")
*Args:*
* length (int): The desired ... | def function[set_extent_size, parameter[self, length, units]]:
constant[
Sets the volume group extent size in the given units::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
vg.set_extent_size(2, "MiB")
*Args:*
* l... | keyword[def] identifier[set_extent_size] ( identifier[self] , identifier[length] , identifier[units] ):
literal[string]
identifier[size] = identifier[length] * identifier[size_units] [ identifier[units] ]
identifier[self] . identifier[open] ()
identifier[ext] = identifier[lvm_vg_s... | def set_extent_size(self, length, units):
"""
Sets the volume group extent size in the given units::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
vg.set_extent_size(2, "MiB")
*Args:*
* length (int): The desired leng... |
def allocate(self):
"""Initializes libvirt resources."""
disk_path = self.provider_image
self._hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'vbox:///session'))
self._domain = domain_create(self._hypervisor, self.identifier,
... | def function[allocate, parameter[self]]:
constant[Initializes libvirt resources.]
variable[disk_path] assign[=] name[self].provider_image
name[self]._hypervisor assign[=] call[name[libvirt].open, parameter[call[name[self].configuration.get, parameter[constant[hypervisor], constant[vbox:///sessio... | keyword[def] identifier[allocate] ( identifier[self] ):
literal[string]
identifier[disk_path] = identifier[self] . identifier[provider_image]
identifier[self] . identifier[_hypervisor] = identifier[libvirt] . identifier[open] (
identifier[self] . identifier[configuration] . iden... | def allocate(self):
"""Initializes libvirt resources."""
disk_path = self.provider_image
self._hypervisor = libvirt.open(self.configuration.get('hypervisor', 'vbox:///session'))
self._domain = domain_create(self._hypervisor, self.identifier, self.configuration['domain'], disk_path) |
def as_uninitialized(fn):
"""
Decorator: call fn with the parameterized_instance's
initialization flag set to False, then revert the flag.
(Used to decorate Parameterized methods that must alter
a constant Parameter.)
"""
@wraps(fn)
def override_initialization(self_,*args,**kw):
... | def function[as_uninitialized, parameter[fn]]:
constant[
Decorator: call fn with the parameterized_instance's
initialization flag set to False, then revert the flag.
(Used to decorate Parameterized methods that must alter
a constant Parameter.)
]
def function[override_initialization... | keyword[def] identifier[as_uninitialized] ( identifier[fn] ):
literal[string]
@ identifier[wraps] ( identifier[fn] )
keyword[def] identifier[override_initialization] ( identifier[self_] ,* identifier[args] ,** identifier[kw] ):
identifier[parameterized_instance] = identifier[self_] . identifi... | def as_uninitialized(fn):
"""
Decorator: call fn with the parameterized_instance's
initialization flag set to False, then revert the flag.
(Used to decorate Parameterized methods that must alter
a constant Parameter.)
"""
@wraps(fn)
def override_initialization(self_, *args, **kw):
... |
def cleanall(self,str,cleanslash=0):
"""Deals with things like:
1./ accents with a slashes and converts them to entities.
Example: \', \`,\^
2./ Some 'missed' incomplete entities or ´ ( floating apostroph )
and the like.
Example: Milosˇevic --> Miloševic
Marti�b4;nez --> Mart&... | def function[cleanall, parameter[self, str, cleanslash]]:
constant[Deals with things like:
1./ accents with a slashes and converts them to entities.
Example: ', \`,\^
2./ Some 'missed' incomplete entities or ´ ( floating apostroph )
and the like.
Example: Milosˇevic --> Miloševic
M... | keyword[def] identifier[cleanall] ( identifier[self] , identifier[str] , identifier[cleanslash] = literal[int] ):
literal[string]
identifier[retstr] = identifier[self] . identifier[re_accent] . identifier[sub] ( identifier[self] . identifier[__sub_accent] , identifier[str] )
identifier[ret... | def cleanall(self, str, cleanslash=0):
"""Deals with things like:
1./ accents with a slashes and converts them to entities.
Example: ', \\`,\\^
2./ Some 'missed' incomplete entities or ´ ( floating apostroph )
and the like.
Example: Milosˇevic --> Miloševic
Marti�b4;nez --> Mart&i... |
def visit_default(self, node):
"""check the node line number and check it if not yet done"""
if not node.is_statement:
return
if not node.root().pure_python:
return # XXX block visit of child nodes
prev_sibl = node.previous_sibling()
if prev_sibl is not N... | def function[visit_default, parameter[self, node]]:
constant[check the node line number and check it if not yet done]
if <ast.UnaryOp object at 0x7da1b059db70> begin[:]
return[None]
if <ast.UnaryOp object at 0x7da1b059e830> begin[:]
return[None]
variable[prev_sibl] assign... | keyword[def] identifier[visit_default] ( identifier[self] , identifier[node] ):
literal[string]
keyword[if] keyword[not] identifier[node] . identifier[is_statement] :
keyword[return]
keyword[if] keyword[not] identifier[node] . identifier[root] (). identifier[pure_python] ... | def visit_default(self, node):
"""check the node line number and check it if not yet done"""
if not node.is_statement:
return # depends on [control=['if'], data=[]]
if not node.root().pure_python:
return # XXX block visit of child nodes # depends on [control=['if'], data=[]]
prev_sibl... |
def run_vep(in_file, data):
"""Annotate input VCF file with Ensembl variant effect predictor.
"""
if not vcfutils.vcf_has_variants(in_file):
return None
out_file = utils.append_stem(in_file, "-vepeffects")
assert in_file.endswith(".gz") and out_file.endswith(".gz")
if not utils.file_exis... | def function[run_vep, parameter[in_file, data]]:
constant[Annotate input VCF file with Ensembl variant effect predictor.
]
if <ast.UnaryOp object at 0x7da18f09dc90> begin[:]
return[constant[None]]
variable[out_file] assign[=] call[name[utils].append_stem, parameter[name[in_file], con... | keyword[def] identifier[run_vep] ( identifier[in_file] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[vcfutils] . identifier[vcf_has_variants] ( identifier[in_file] ):
keyword[return] keyword[None]
identifier[out_file] = identifier[utils] . identifier[append_ste... | def run_vep(in_file, data):
"""Annotate input VCF file with Ensembl variant effect predictor.
"""
if not vcfutils.vcf_has_variants(in_file):
return None # depends on [control=['if'], data=[]]
out_file = utils.append_stem(in_file, '-vepeffects')
assert in_file.endswith('.gz') and out_file.en... |
def onCancelButton(self, event):
"""
Quit grid with warning if unsaved changes present
"""
if self.grid.changes:
dlg1 = wx.MessageDialog(self, caption="Message:",
message="Are you sure you want to exit this grid?\nYour changes will not be s... | def function[onCancelButton, parameter[self, event]]:
constant[
Quit grid with warning if unsaved changes present
]
if name[self].grid.changes begin[:]
variable[dlg1] assign[=] call[name[wx].MessageDialog, parameter[name[self]]]
variable[result] assign[=] ... | keyword[def] identifier[onCancelButton] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[self] . identifier[grid] . identifier[changes] :
identifier[dlg1] = identifier[wx] . identifier[MessageDialog] ( identifier[self] , identifier[caption] = literal[st... | def onCancelButton(self, event):
"""
Quit grid with warning if unsaved changes present
"""
if self.grid.changes:
dlg1 = wx.MessageDialog(self, caption='Message:', message='Are you sure you want to exit this grid?\nYour changes will not be saved.\n ', style=wx.OK | wx.CANCEL)
resu... |
def _fill_and_one_pad_stride(stride, n, data_format=DATA_FORMAT_NHWC):
"""Expands the provided stride to size n and pads it with 1s."""
if isinstance(stride, numbers.Integral) or (
isinstance(stride, collections.Iterable) and len(stride) <= n):
if data_format.startswith("NC"):
return (1, 1,) + _fill... | def function[_fill_and_one_pad_stride, parameter[stride, n, data_format]]:
constant[Expands the provided stride to size n and pads it with 1s.]
if <ast.BoolOp object at 0x7da1b1c62650> begin[:]
if call[name[data_format].startswith, parameter[constant[NC]]] begin[:]
return[bin... | keyword[def] identifier[_fill_and_one_pad_stride] ( identifier[stride] , identifier[n] , identifier[data_format] = identifier[DATA_FORMAT_NHWC] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[stride] , identifier[numbers] . identifier[Integral] ) keyword[or] (
identifier[isinstance] ( id... | def _fill_and_one_pad_stride(stride, n, data_format=DATA_FORMAT_NHWC):
"""Expands the provided stride to size n and pads it with 1s."""
if isinstance(stride, numbers.Integral) or (isinstance(stride, collections.Iterable) and len(stride) <= n):
if data_format.startswith('NC'):
return (1, 1) +... |
def _create_listening_stream(self, pull_addr):
"""
Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests.
"""
sock = self._zmq_context.socket(zmq.PULL)
sock.connect(pull_addr)
stream = ZMQStream(sock, io_loop=... | def function[_create_listening_stream, parameter[self, pull_addr]]:
constant[
Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests.
]
variable[sock] assign[=] call[name[self]._zmq_context.socket, parameter[name[zmq].PULL]]
... | keyword[def] identifier[_create_listening_stream] ( identifier[self] , identifier[pull_addr] ):
literal[string]
identifier[sock] = identifier[self] . identifier[_zmq_context] . identifier[socket] ( identifier[zmq] . identifier[PULL] )
identifier[sock] . identifier[connect] ( identifier[pul... | def _create_listening_stream(self, pull_addr):
"""
Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests.
"""
sock = self._zmq_context.socket(zmq.PULL)
sock.connect(pull_addr)
stream = ZMQStream(sock, io_loop=self.io_loop)
... |
def render_to_response(self, context, **response_kwargs):
""" Generates the appropriate response. """
filename = os.path.basename(self.object.file.name)
# Try to guess the content type of the given file
content_type, _ = mimetypes.guess_type(self.object.file.name)
if not content... | def function[render_to_response, parameter[self, context]]:
constant[ Generates the appropriate response. ]
variable[filename] assign[=] call[name[os].path.basename, parameter[name[self].object.file.name]]
<ast.Tuple object at 0x7da20c794fd0> assign[=] call[name[mimetypes].guess_type, parameter[... | keyword[def] identifier[render_to_response] ( identifier[self] , identifier[context] ,** identifier[response_kwargs] ):
literal[string]
identifier[filename] = identifier[os] . identifier[path] . identifier[basename] ( identifier[self] . identifier[object] . identifier[file] . identifier[name] )
... | def render_to_response(self, context, **response_kwargs):
""" Generates the appropriate response. """
filename = os.path.basename(self.object.file.name)
# Try to guess the content type of the given file
(content_type, _) = mimetypes.guess_type(self.object.file.name)
if not content_type:
cont... |
def _prune(self, pop_candidates):
"""Choose a subset of the candidate states to continue on to the next
generation.
:param pop_candidates: The set of candidate states.
"""
return set(
sorted(pop_candidates, key=self._score, reverse=True)
[:self.args.max_p... | def function[_prune, parameter[self, pop_candidates]]:
constant[Choose a subset of the candidate states to continue on to the next
generation.
:param pop_candidates: The set of candidate states.
]
return[call[name[set], parameter[call[call[name[sorted], parameter[name[pop_candidates... | keyword[def] identifier[_prune] ( identifier[self] , identifier[pop_candidates] ):
literal[string]
keyword[return] identifier[set] (
identifier[sorted] ( identifier[pop_candidates] , identifier[key] = identifier[self] . identifier[_score] , identifier[reverse] = keyword[True] )
[:... | def _prune(self, pop_candidates):
"""Choose a subset of the candidate states to continue on to the next
generation.
:param pop_candidates: The set of candidate states.
"""
return set(sorted(pop_candidates, key=self._score, reverse=True)[:self.args.max_pop]) |
def find_country(session, code):
"""Find a country.
Find a country by its ISO-3166 `code` (i.e ES for Spain,
US for United States of America) using the given `session.
When the country does not exist the function will return
`None`.
:param session: database session
:param code: ISO-3166 co... | def function[find_country, parameter[session, code]]:
constant[Find a country.
Find a country by its ISO-3166 `code` (i.e ES for Spain,
US for United States of America) using the given `session.
When the country does not exist the function will return
`None`.
:param session: database sessi... | keyword[def] identifier[find_country] ( identifier[session] , identifier[code] ):
literal[string]
identifier[country] = identifier[session] . identifier[query] ( identifier[Country] ). identifier[filter] ( identifier[Country] . identifier[code] == identifier[code] ). identifier[first] ()
keyword[retu... | def find_country(session, code):
"""Find a country.
Find a country by its ISO-3166 `code` (i.e ES for Spain,
US for United States of America) using the given `session.
When the country does not exist the function will return
`None`.
:param session: database session
:param code: ISO-3166 co... |
def validate_image(image, number_tiles):
"""Basic sanity checks prior to performing a split."""
TILE_LIMIT = 99 * 99
try:
number_tiles = int(number_tiles)
except:
raise ValueError('number_tiles could not be cast to integer.')
if number_tiles > TILE_LIMIT or number_tiles < 2:
... | def function[validate_image, parameter[image, number_tiles]]:
constant[Basic sanity checks prior to performing a split.]
variable[TILE_LIMIT] assign[=] binary_operation[constant[99] * constant[99]]
<ast.Try object at 0x7da1b0657c10>
if <ast.BoolOp object at 0x7da1b0657970> begin[:]
<... | keyword[def] identifier[validate_image] ( identifier[image] , identifier[number_tiles] ):
literal[string]
identifier[TILE_LIMIT] = literal[int] * literal[int]
keyword[try] :
identifier[number_tiles] = identifier[int] ( identifier[number_tiles] )
keyword[except] :
keyword[raise... | def validate_image(image, number_tiles):
"""Basic sanity checks prior to performing a split."""
TILE_LIMIT = 99 * 99
try:
number_tiles = int(number_tiles) # depends on [control=['try'], data=[]]
except:
raise ValueError('number_tiles could not be cast to integer.') # depends on [contro... |
def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls | def function[all_library_calls, parameter[self]]:
constant[ recursive version of library calls
]
if compare[name[self]._all_library_calls is constant[None]] begin[:]
name[self]._all_library_calls assign[=] call[name[self]._explore_functions, parameter[<ast.Lambda object at 0x7da1... | keyword[def] identifier[all_library_calls] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_all_library_calls] keyword[is] keyword[None] :
identifier[self] . identifier[_all_library_calls] = identifier[self] . identifier[_explore_functions] ( keyword[... | def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls) # depends on [control=['if'], data=[]]
return self._all_library_calls |
def constraint(self, n=-1, fid=0):
"""Obtain the set of orthogonal equations that make the solution of
the rank deficient normal equations possible.
:param fid: the id of the sub-fitter (numerical)
"""
c = self._getval("constr", fid)
if n < 0 or n > self.deficiency(fid)... | def function[constraint, parameter[self, n, fid]]:
constant[Obtain the set of orthogonal equations that make the solution of
the rank deficient normal equations possible.
:param fid: the id of the sub-fitter (numerical)
]
variable[c] assign[=] call[name[self]._getval, parameter... | keyword[def] identifier[constraint] ( identifier[self] , identifier[n] =- literal[int] , identifier[fid] = literal[int] ):
literal[string]
identifier[c] = identifier[self] . identifier[_getval] ( literal[string] , identifier[fid] )
keyword[if] identifier[n] < literal[int] keyword[or] id... | def constraint(self, n=-1, fid=0):
"""Obtain the set of orthogonal equations that make the solution of
the rank deficient normal equations possible.
:param fid: the id of the sub-fitter (numerical)
"""
c = self._getval('constr', fid)
if n < 0 or n > self.deficiency(fid):
re... |
def listen(identifier):
"""
Launch a listener and return the compactor context.
"""
context = Context()
process = WebProcess(identifier)
context.spawn(process)
log.info("Launching PID %s", process.pid)
return process, context | def function[listen, parameter[identifier]]:
constant[
Launch a listener and return the compactor context.
]
variable[context] assign[=] call[name[Context], parameter[]]
variable[process] assign[=] call[name[WebProcess], parameter[name[identifier]]]
call[name[context].spawn, paramete... | keyword[def] identifier[listen] ( identifier[identifier] ):
literal[string]
identifier[context] = identifier[Context] ()
identifier[process] = identifier[WebProcess] ( identifier[identifier] )
identifier[context] . identifier[spawn] ( identifier[process] )
identifier[log] . identifier[info] ( liter... | def listen(identifier):
"""
Launch a listener and return the compactor context.
"""
context = Context()
process = WebProcess(identifier)
context.spawn(process)
log.info('Launching PID %s', process.pid)
return (process, context) |
def cos_values(period=360):
"""
Provides an infinite source of values representing a cosine wave (from -1
to +1) which repeats every *period* values. For example, to produce a
"siren" effect with a couple of LEDs that repeats once a second::
from gpiozero import PWMLED
from gpiozero.too... | def function[cos_values, parameter[period]]:
constant[
Provides an infinite source of values representing a cosine wave (from -1
to +1) which repeats every *period* values. For example, to produce a
"siren" effect with a couple of LEDs that repeats once a second::
from gpiozero import PWMLE... | keyword[def] identifier[cos_values] ( identifier[period] = literal[int] ):
literal[string]
identifier[angles] =( literal[int] * identifier[pi] * identifier[i] / identifier[period] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[period] ))
keyword[for] identifier[a] keyword[... | def cos_values(period=360):
"""
Provides an infinite source of values representing a cosine wave (from -1
to +1) which repeats every *period* values. For example, to produce a
"siren" effect with a couple of LEDs that repeats once a second::
from gpiozero import PWMLED
from gpiozero.too... |
def create(output_prefix, grid_flux_filename, wavelength_filenames,
clobber=False, grid_flux_filename_format="csv", **kwargs):
"""
Create a new *sick* model from files describing the parameter names, fluxes,
and wavelengths.
"""
if not clobber:
# Check to make sure the output files won'... | def function[create, parameter[output_prefix, grid_flux_filename, wavelength_filenames, clobber, grid_flux_filename_format]]:
constant[
Create a new *sick* model from files describing the parameter names, fluxes,
and wavelengths.
]
if <ast.UnaryOp object at 0x7da18dc9ba30> begin[:]
... | keyword[def] identifier[create] ( identifier[output_prefix] , identifier[grid_flux_filename] , identifier[wavelength_filenames] ,
identifier[clobber] = keyword[False] , identifier[grid_flux_filename_format] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[... | def create(output_prefix, grid_flux_filename, wavelength_filenames, clobber=False, grid_flux_filename_format='csv', **kwargs):
"""
Create a new *sick* model from files describing the parameter names, fluxes,
and wavelengths.
"""
if not clobber:
# Check to make sure the output files won't exi... |
def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
... | def function[interfaces, parameter[root]]:
constant[
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
... | keyword[def] identifier[interfaces] ( identifier[root] ):
literal[string]
identifier[root] = identifier[target] ( identifier[root] )
keyword[if] identifier[root] keyword[is] keyword[False] keyword[or] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[root] ):
... | def interfaces(root):
"""
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
... |
def read(self) -> None:
"""Call method |NetCDFFile.read| of all handled |NetCDFFile| objects.
"""
for folder in self.folders.values():
for file_ in folder.values():
file_.read() | def function[read, parameter[self]]:
constant[Call method |NetCDFFile.read| of all handled |NetCDFFile| objects.
]
for taget[name[folder]] in starred[call[name[self].folders.values, parameter[]]] begin[:]
for taget[name[file_]] in starred[call[name[folder].values, parameter[]]] b... | keyword[def] identifier[read] ( identifier[self] )-> keyword[None] :
literal[string]
keyword[for] identifier[folder] keyword[in] identifier[self] . identifier[folders] . identifier[values] ():
keyword[for] identifier[file_] keyword[in] identifier[folder] . identifier[values] ():
... | def read(self) -> None:
"""Call method |NetCDFFile.read| of all handled |NetCDFFile| objects.
"""
for folder in self.folders.values():
for file_ in folder.values():
file_.read() # depends on [control=['for'], data=['file_']] # depends on [control=['for'], data=['folder']] |
def tail(self, n=5):
"""Return Series with the last n values.
Parameters
----------
n : int
Number of values.
Returns
-------
Series
Series containing the last n values.
Examples
--------
>>> sr = bl.Series(np.ara... | def function[tail, parameter[self, n]]:
constant[Return Series with the last n values.
Parameters
----------
n : int
Number of values.
Returns
-------
Series
Series containing the last n values.
Examples
--------
... | keyword[def] identifier[tail] ( identifier[self] , identifier[n] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[_length] keyword[is] keyword[not] keyword[None] :
identifier[length] = identifier[self] . identifier[_length]
keyword[else] :
... | def tail(self, n=5):
"""Return Series with the last n values.
Parameters
----------
n : int
Number of values.
Returns
-------
Series
Series containing the last n values.
Examples
--------
>>> sr = bl.Series(np.arange(... |
def validate(filename, verbose=False):
"""
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
"""
# is_css = filename.endswith(".css")... | def function[validate, parameter[filename, verbose]]:
constant[
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
]
variable[... | keyword[def] identifier[validate] ( identifier[filename] , identifier[verbose] = keyword[False] ):
literal[string]
identifier[is_remote] = identifier[filename] . identifier[startswith] ( literal[string] ) keyword[or] identifier[filename] . identifier[startswith] (
literal[string] )
keyword... | def validate(filename, verbose=False):
"""
Validate file and return JSON result as dictionary.
"filename" can be a file name or an HTTP URL.
Return "" if the validator does not return valid JSON.
Raise OSError if curl command returns an error status.
"""
# is_css = filename.endswith(".css")... |
def get_assessment_part_bank_session(self):
"""Gets the ``OsidSession`` to lookup assessment part/bank mappings for assessment parts.
return: (osid.assessment.authoring.AssessmentPartBankSession) -
an ``AssessmentPartBankSession``
raise: OperationFailed - unable to complete req... | def function[get_assessment_part_bank_session, parameter[self]]:
constant[Gets the ``OsidSession`` to lookup assessment part/bank mappings for assessment parts.
return: (osid.assessment.authoring.AssessmentPartBankSession) -
an ``AssessmentPartBankSession``
raise: OperationFail... | keyword[def] identifier[get_assessment_part_bank_session] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_assessment_part_bank] ():
keyword[raise] identifier[errors] . identifier[Unimplemented] ()
keyword[re... | def get_assessment_part_bank_session(self):
"""Gets the ``OsidSession`` to lookup assessment part/bank mappings for assessment parts.
return: (osid.assessment.authoring.AssessmentPartBankSession) -
an ``AssessmentPartBankSession``
raise: OperationFailed - unable to complete request... |
def sort(imports, separate=True, import_before_from=True, **classify_kwargs):
"""Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_... | def function[sort, parameter[imports, separate, import_before_from]]:
constant[Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool impor... | keyword[def] identifier[sort] ( identifier[imports] , identifier[separate] = keyword[True] , identifier[import_before_from] = keyword[True] ,** identifier[classify_kwargs] ):
literal[string]
keyword[if] identifier[separate] :
keyword[def] identifier[classify_func] ( identifier[obj] ):
... | def sort(imports, separate=True, import_before_from=True, **classify_kwargs):
"""Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_... |
def read_int(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.read(8... | def function[read_int, parameter[self]]:
constant[
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
]
if compare[name[self].reader.sysinfo.ProcessorArchitecture equal[==] name[PRO... | keyword[def] identifier[read_int] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[reader] . identifier[sysinfo] . identifier[ProcessorArchitecture] == identifier[PROCESSOR_ARCHITECTURE] . identifier[AMD64] :
keyword[return] identifier[int] . identifier[from_bytes] ( identi... | def read_int(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(se... |
def _write_config_file(batch_id, caller_names, base_dir, data):
"""Write YAML configuration to generate an ensemble set of combined calls.
"""
config_dir = utils.safe_makedir(os.path.join(base_dir, "config"))
config_file = os.path.join(config_dir, "{0}-ensemble.yaml".format(batch_id))
algorithm = da... | def function[_write_config_file, parameter[batch_id, caller_names, base_dir, data]]:
constant[Write YAML configuration to generate an ensemble set of combined calls.
]
variable[config_dir] assign[=] call[name[utils].safe_makedir, parameter[call[name[os].path.join, parameter[name[base_dir], constant[... | keyword[def] identifier[_write_config_file] ( identifier[batch_id] , identifier[caller_names] , identifier[base_dir] , identifier[data] ):
literal[string]
identifier[config_dir] = identifier[utils] . identifier[safe_makedir] ( identifier[os] . identifier[path] . identifier[join] ( identifier[base_dir] , li... | def _write_config_file(batch_id, caller_names, base_dir, data):
"""Write YAML configuration to generate an ensemble set of combined calls.
"""
config_dir = utils.safe_makedir(os.path.join(base_dir, 'config'))
config_file = os.path.join(config_dir, '{0}-ensemble.yaml'.format(batch_id))
algorithm = da... |
def interpret_element(element_type: str, text: str, span: str) -> Element:
"""
Construct an Element instance from regexp
groups.
"""
return Element(element_type,
interpret_span(span),
text) | def function[interpret_element, parameter[element_type, text, span]]:
constant[
Construct an Element instance from regexp
groups.
]
return[call[name[Element], parameter[name[element_type], call[name[interpret_span], parameter[name[span]]], name[text]]]] | keyword[def] identifier[interpret_element] ( identifier[element_type] : identifier[str] , identifier[text] : identifier[str] , identifier[span] : identifier[str] )-> identifier[Element] :
literal[string]
keyword[return] identifier[Element] ( identifier[element_type] ,
identifier[interpret_span] ( ide... | def interpret_element(element_type: str, text: str, span: str) -> Element:
"""
Construct an Element instance from regexp
groups.
"""
return Element(element_type, interpret_span(span), text) |
def _assemble_from_unit_mappings(arg, errors, box, tz):
"""
assemble the unit specified fields from the arg (DataFrame)
Return a Series for actual parsing
Parameters
----------
arg : DataFrame
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsin... | def function[_assemble_from_unit_mappings, parameter[arg, errors, box, tz]]:
constant[
assemble the unit specified fields from the arg (DataFrame)
Return a Series for actual parsing
Parameters
----------
arg : DataFrame
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- ... | keyword[def] identifier[_assemble_from_unit_mappings] ( identifier[arg] , identifier[errors] , identifier[box] , identifier[tz] ):
literal[string]
keyword[from] identifier[pandas] keyword[import] identifier[to_timedelta] , identifier[to_numeric] , identifier[DataFrame]
identifier[arg] = identifier... | def _assemble_from_unit_mappings(arg, errors, box, tz):
"""
assemble the unit specified fields from the arg (DataFrame)
Return a Series for actual parsing
Parameters
----------
arg : DataFrame
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
- If 'raise', then invalid parsin... |
def _get_client_creds_from_request(self, request):
"""Return client credentials based on the current request.
According to the rfc6749, client MAY use the HTTP Basic authentication
scheme as defined in [RFC2617] to authenticate with the authorization
server. The client identifier is enc... | def function[_get_client_creds_from_request, parameter[self, request]]:
constant[Return client credentials based on the current request.
According to the rfc6749, client MAY use the HTTP Basic authentication
scheme as defined in [RFC2617] to authenticate with the authorization
server. T... | keyword[def] identifier[_get_client_creds_from_request] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] identifier[request] . identifier[client_id] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[request] . identifier[client_id] , identi... | def _get_client_creds_from_request(self, request):
"""Return client credentials based on the current request.
According to the rfc6749, client MAY use the HTTP Basic authentication
scheme as defined in [RFC2617] to authenticate with the authorization
server. The client identifier is encoded... |
def get_archives_to_prune(archives, hook_data):
"""Return list of keys to delete."""
files_to_skip = []
for i in ['current_archive_filename', 'old_archive_filename']:
if hook_data.get(i):
files_to_skip.append(hook_data[i])
archives.sort(key=itemgetter('LastModified'),
... | def function[get_archives_to_prune, parameter[archives, hook_data]]:
constant[Return list of keys to delete.]
variable[files_to_skip] assign[=] list[[]]
for taget[name[i]] in starred[list[[<ast.Constant object at 0x7da1b072ec80>, <ast.Constant object at 0x7da1b072e770>]]] begin[:]
... | keyword[def] identifier[get_archives_to_prune] ( identifier[archives] , identifier[hook_data] ):
literal[string]
identifier[files_to_skip] =[]
keyword[for] identifier[i] keyword[in] [ literal[string] , literal[string] ]:
keyword[if] identifier[hook_data] . identifier[get] ( identifier[i] )... | def get_archives_to_prune(archives, hook_data):
"""Return list of keys to delete."""
files_to_skip = []
for i in ['current_archive_filename', 'old_archive_filename']:
if hook_data.get(i):
files_to_skip.append(hook_data[i]) # depends on [control=['if'], data=[]] # depends on [control=['... |
def rgetattr(obj, attr, *args):
"""Get attr that handles dots in attr name."""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split(".")) | def function[rgetattr, parameter[obj, attr]]:
constant[Get attr that handles dots in attr name.]
def function[_getattr, parameter[obj, attr]]:
return[call[name[getattr], parameter[name[obj], name[attr], <ast.Starred object at 0x7da1b20105b0>]]]
return[call[name[functools].reduce, parameter[n... | keyword[def] identifier[rgetattr] ( identifier[obj] , identifier[attr] ,* identifier[args] ):
literal[string]
keyword[def] identifier[_getattr] ( identifier[obj] , identifier[attr] ):
keyword[return] identifier[getattr] ( identifier[obj] , identifier[attr] ,* identifier[args] )
keyword[return] ident... | def rgetattr(obj, attr, *args):
"""Get attr that handles dots in attr name."""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.')) |
def structural_similarity(document_1, document_2):
"""
Computes the structural similarity between two DOM Trees
:param document_1: html string
:param document_2: html string
:return: int
"""
try:
document_1 = lxml.html.parse(StringIO(document_1))
document_2 = lxml.html.parse(... | def function[structural_similarity, parameter[document_1, document_2]]:
constant[
Computes the structural similarity between two DOM Trees
:param document_1: html string
:param document_2: html string
:return: int
]
<ast.Try object at 0x7da1b0ebd6f0>
variable[tags1] assign[=] cal... | keyword[def] identifier[structural_similarity] ( identifier[document_1] , identifier[document_2] ):
literal[string]
keyword[try] :
identifier[document_1] = identifier[lxml] . identifier[html] . identifier[parse] ( identifier[StringIO] ( identifier[document_1] ))
identifier[document_2] = i... | def structural_similarity(document_1, document_2):
"""
Computes the structural similarity between two DOM Trees
:param document_1: html string
:param document_2: html string
:return: int
"""
try:
document_1 = lxml.html.parse(StringIO(document_1))
document_2 = lxml.html.parse(... |
def search(self, Queue=None, order=None, raw_query=None, Format='l', **kwargs):
""" Search arbitrary needles in given fields and queue.
Example::
>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')
>>> tracker.login()
>>> tickets = ... | def function[search, parameter[self, Queue, order, raw_query, Format]]:
constant[ Search arbitrary needles in given fields and queue.
Example::
>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')
>>> tracker.login()
>>> tickets = tr... | keyword[def] identifier[search] ( identifier[self] , identifier[Queue] = keyword[None] , identifier[order] = keyword[None] , identifier[raw_query] = keyword[None] , identifier[Format] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[get_params] ={}
identifier[query] =... | def search(self, Queue=None, order=None, raw_query=None, Format='l', **kwargs):
""" Search arbitrary needles in given fields and queue.
Example::
>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')
>>> tracker.login()
>>> tickets = trac... |
def _addAnomalyClassifierRegion(self, network, params, spEnable, tmEnable):
"""
Attaches an 'AnomalyClassifier' region to the network. Will remove current
'AnomalyClassifier' region if it exists.
Parameters
-----------
network - network to add the AnomalyClassifier region
params - parameter... | def function[_addAnomalyClassifierRegion, parameter[self, network, params, spEnable, tmEnable]]:
constant[
Attaches an 'AnomalyClassifier' region to the network. Will remove current
'AnomalyClassifier' region if it exists.
Parameters
-----------
network - network to add the AnomalyClassifie... | keyword[def] identifier[_addAnomalyClassifierRegion] ( identifier[self] , identifier[network] , identifier[params] , identifier[spEnable] , identifier[tmEnable] ):
literal[string]
identifier[allParams] = identifier[copy] . identifier[deepcopy] ( identifier[params] )
identifier[knnParams] = identifier... | def _addAnomalyClassifierRegion(self, network, params, spEnable, tmEnable):
"""
Attaches an 'AnomalyClassifier' region to the network. Will remove current
'AnomalyClassifier' region if it exists.
Parameters
-----------
network - network to add the AnomalyClassifier region
params - parameter... |
def day_postfix(day):
"""Returns day's correct postfix (2nd, 3rd, 61st, etc)."""
if day != 11 and day % 10 == 1:
postfix = "st"
elif day != 12 and day % 10 == 2:
postfix = "nd"
elif day != 13 and day % 10 == 3:
postfix = "rd"
else:
postfix = "th"
return postfix | def function[day_postfix, parameter[day]]:
constant[Returns day's correct postfix (2nd, 3rd, 61st, etc).]
if <ast.BoolOp object at 0x7da20e954250> begin[:]
variable[postfix] assign[=] constant[st]
return[name[postfix]] | keyword[def] identifier[day_postfix] ( identifier[day] ):
literal[string]
keyword[if] identifier[day] != literal[int] keyword[and] identifier[day] % literal[int] == literal[int] :
identifier[postfix] = literal[string]
keyword[elif] identifier[day] != literal[int] keyword[and] identifi... | def day_postfix(day):
"""Returns day's correct postfix (2nd, 3rd, 61st, etc)."""
if day != 11 and day % 10 == 1:
postfix = 'st' # depends on [control=['if'], data=[]]
elif day != 12 and day % 10 == 2:
postfix = 'nd' # depends on [control=['if'], data=[]]
elif day != 13 and day % 10 == ... |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Replace Val File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into a data structure
... | def function[_read, parameter[self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile]]:
constant[
Replace Val File Read from File Method
]
name[self].fileExtension assign[=] name[extension]
with call[name[open], parameter[name[pat... | keyword[def] identifier[_read] ( identifier[self] , identifier[directory] , identifier[filename] , identifier[session] , identifier[path] , identifier[name] , identifier[extension] , identifier[spatial] , identifier[spatialReferenceID] , identifier[replaceParamFile] ):
literal[string]
iden... | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Replace Val File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into a data structure
with open(path,... |
def get_unicodes(codepoint):
""" Return list of unicodes for <scanning-codepoints> """
result = re.sub('\s', '', codepoint.text)
return Extension.convert_to_list_of_unicodes(result) | def function[get_unicodes, parameter[codepoint]]:
constant[ Return list of unicodes for <scanning-codepoints> ]
variable[result] assign[=] call[name[re].sub, parameter[constant[\s], constant[], name[codepoint].text]]
return[call[name[Extension].convert_to_list_of_unicodes, parameter[name[result]]]] | keyword[def] identifier[get_unicodes] ( identifier[codepoint] ):
literal[string]
identifier[result] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[codepoint] . identifier[text] )
keyword[return] identifier[Extension] . identifier[convert_to_list_of_uni... | def get_unicodes(codepoint):
""" Return list of unicodes for <scanning-codepoints> """
result = re.sub('\\s', '', codepoint.text)
return Extension.convert_to_list_of_unicodes(result) |
def zipsafe(dist):
"""Returns whether or not we determine a distribution is zip-safe."""
# zip-safety is only an attribute of eggs. wheels are considered never
# zip safe per implications of PEP 427.
if hasattr(dist, 'egg_info') and dist.egg_info.endswith('EGG-INFO'):
egg_metadata = dist.metadata... | def function[zipsafe, parameter[dist]]:
constant[Returns whether or not we determine a distribution is zip-safe.]
if <ast.BoolOp object at 0x7da2041d9a50> begin[:]
variable[egg_metadata] assign[=] call[name[dist].metadata_listdir, parameter[constant[]]]
return[<ast.BoolOp object ... | keyword[def] identifier[zipsafe] ( identifier[dist] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[dist] , literal[string] ) keyword[and] identifier[dist] . identifier[egg_info] . identifier[endswith] ( literal[string] ):
identifier[egg_metadata] = identifier[dist] . ide... | def zipsafe(dist):
"""Returns whether or not we determine a distribution is zip-safe."""
# zip-safety is only an attribute of eggs. wheels are considered never
# zip safe per implications of PEP 427.
if hasattr(dist, 'egg_info') and dist.egg_info.endswith('EGG-INFO'):
egg_metadata = dist.metada... |
def fibonacci() -> Iterator[int]:
"""Generate the sequence of Fibonacci.
https://oeis.org/A000045
"""
a, b = 1, 2
while True:
yield a
a, b = b, a + b | def function[fibonacci, parameter[]]:
constant[Generate the sequence of Fibonacci.
https://oeis.org/A000045
]
<ast.Tuple object at 0x7da204620eb0> assign[=] tuple[[<ast.Constant object at 0x7da1b07615a0>, <ast.Constant object at 0x7da1b0762020>]]
while constant[True] begin[:]
... | keyword[def] identifier[fibonacci] ()-> identifier[Iterator] [ identifier[int] ]:
literal[string]
identifier[a] , identifier[b] = literal[int] , literal[int]
keyword[while] keyword[True] :
keyword[yield] identifier[a]
identifier[a] , identifier[b] = identifier[b] , identifier[a] ... | def fibonacci() -> Iterator[int]:
"""Generate the sequence of Fibonacci.
https://oeis.org/A000045
"""
(a, b) = (1, 2)
while True:
yield a
(a, b) = (b, a + b) # depends on [control=['while'], data=[]] |
def get_output_from_input(self):
"""Populate output form with default output path based on input layer.
"""
input_path = self.layer.currentLayer().source()
output_path = (
os.path.splitext(input_path)[0] + '_multi_buffer'
+ os.path.splitext(input_path)[1])
... | def function[get_output_from_input, parameter[self]]:
constant[Populate output form with default output path based on input layer.
]
variable[input_path] assign[=] call[call[name[self].layer.currentLayer, parameter[]].source, parameter[]]
variable[output_path] assign[=] binary_operation[... | keyword[def] identifier[get_output_from_input] ( identifier[self] ):
literal[string]
identifier[input_path] = identifier[self] . identifier[layer] . identifier[currentLayer] (). identifier[source] ()
identifier[output_path] =(
identifier[os] . identifier[path] . identifier[splitex... | def get_output_from_input(self):
"""Populate output form with default output path based on input layer.
"""
input_path = self.layer.currentLayer().source()
output_path = os.path.splitext(input_path)[0] + '_multi_buffer' + os.path.splitext(input_path)[1]
self.output_form.setText(output_path) |
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
job_id = ('preprocess-im... | def function[preprocess, parameter[train_dataset, output_dir, eval_dataset, checkpoint]]:
constant[Preprocess data locally.]
import module[apache_beam] as alias[beam]
from relative_module[google.datalab.utils] import module[LambdaJob]
from relative_module[None] import module[_preprocess]
if ... | keyword[def] identifier[preprocess] ( identifier[train_dataset] , identifier[output_dir] , identifier[eval_dataset] , identifier[checkpoint] ):
literal[string]
keyword[import] identifier[apache_beam] keyword[as] identifier[beam]
keyword[from] identifier[google] . identifier[datalab] . identifier... | def preprocess(train_dataset, output_dir, eval_dataset, checkpoint):
"""Preprocess data locally."""
import apache_beam as beam
from google.datalab.utils import LambdaJob
from . import _preprocess
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL # depends on [control=['if'... |
def agent_from_entity(self, relation, entity_id):
"""Create a (potentially grounded) INDRA Agent object from a given
Medscan entity describing the subject or object.
Uses helper functions to convert a Medscan URN to an INDRA db_refs
grounding dictionary.
If the entity has prope... | def function[agent_from_entity, parameter[self, relation, entity_id]]:
constant[Create a (potentially grounded) INDRA Agent object from a given
Medscan entity describing the subject or object.
Uses helper functions to convert a Medscan URN to an INDRA db_refs
grounding dictionary.
... | keyword[def] identifier[agent_from_entity] ( identifier[self] , identifier[relation] , identifier[entity_id] ):
literal[string]
identifier[tags] = identifier[_extract_sentence_tags] ( identifier[relation] . identifier[tagged_sentence] )
keyword[if] identifier[e... | def agent_from_entity(self, relation, entity_id):
"""Create a (potentially grounded) INDRA Agent object from a given
Medscan entity describing the subject or object.
Uses helper functions to convert a Medscan URN to an INDRA db_refs
grounding dictionary.
If the entity has propertie... |
def from_json(cls, json):
"""Inherit doc."""
obj = cls(property_range.PropertyRange.from_json(json["property_range"]),
namespace_range.NamespaceRange.from_json_object(json["ns_range"]),
model.QuerySpec.from_json(json["query_spec"]))
cursor = json["cursor"]
# lint bug. Class m... | def function[from_json, parameter[cls, json]]:
constant[Inherit doc.]
variable[obj] assign[=] call[name[cls], parameter[call[name[property_range].PropertyRange.from_json, parameter[call[name[json]][constant[property_range]]]], call[name[namespace_range].NamespaceRange.from_json_object, parameter[call[na... | keyword[def] identifier[from_json] ( identifier[cls] , identifier[json] ):
literal[string]
identifier[obj] = identifier[cls] ( identifier[property_range] . identifier[PropertyRange] . identifier[from_json] ( identifier[json] [ literal[string] ]),
identifier[namespace_range] . identifier[NamespaceRange... | def from_json(cls, json):
"""Inherit doc."""
obj = cls(property_range.PropertyRange.from_json(json['property_range']), namespace_range.NamespaceRange.from_json_object(json['ns_range']), model.QuerySpec.from_json(json['query_spec']))
cursor = json['cursor']
# lint bug. Class method can access protected f... |
def get_subdomains_count(self, accepted=True, cur=None):
"""
Fetch subdomain names
"""
if accepted:
accepted_filter = 'WHERE accepted=1'
else:
accepted_filter = ''
get_cmd = "SELECT COUNT(DISTINCT fully_qualified_subdomain) as count FROM {} {};".f... | def function[get_subdomains_count, parameter[self, accepted, cur]]:
constant[
Fetch subdomain names
]
if name[accepted] begin[:]
variable[accepted_filter] assign[=] constant[WHERE accepted=1]
variable[get_cmd] assign[=] call[constant[SELECT COUNT(DISTINCT fully_qu... | keyword[def] identifier[get_subdomains_count] ( identifier[self] , identifier[accepted] = keyword[True] , identifier[cur] = keyword[None] ):
literal[string]
keyword[if] identifier[accepted] :
identifier[accepted_filter] = literal[string]
keyword[else] :
identifi... | def get_subdomains_count(self, accepted=True, cur=None):
"""
Fetch subdomain names
"""
if accepted:
accepted_filter = 'WHERE accepted=1' # depends on [control=['if'], data=[]]
else:
accepted_filter = ''
get_cmd = 'SELECT COUNT(DISTINCT fully_qualified_subdomain) as count... |
def to_message(self, keywords=None, show_header=True):
"""Format keywords as a message object.
.. versionadded:: 3.2
.. versionchanged:: 3.3 - default keywords to None
The message object can then be rendered to html, plain text etc.
:param keywords: Keywords to be converted t... | def function[to_message, parameter[self, keywords, show_header]]:
constant[Format keywords as a message object.
.. versionadded:: 3.2
.. versionchanged:: 3.3 - default keywords to None
The message object can then be rendered to html, plain text etc.
:param keywords: Keywords ... | keyword[def] identifier[to_message] ( identifier[self] , identifier[keywords] = keyword[None] , identifier[show_header] = keyword[True] ):
literal[string]
keyword[if] identifier[keywords] keyword[is] keyword[None] keyword[and] identifier[self] . identifier[layer] keyword[is] keyword[not] ke... | def to_message(self, keywords=None, show_header=True):
"""Format keywords as a message object.
.. versionadded:: 3.2
.. versionchanged:: 3.3 - default keywords to None
The message object can then be rendered to html, plain text etc.
:param keywords: Keywords to be converted to a ... |
def camera_feedback_send(self, time_usec, target_system, cam_idx, img_idx, lat, lng, alt_msl, alt_rel, roll, pitch, yaw, foc_len, flags, force_mavlink1=False):
'''
Camera Capture Feedback
time_usec : Image timestamp (microseconds since UNIX epoch), as pas... | def function[camera_feedback_send, parameter[self, time_usec, target_system, cam_idx, img_idx, lat, lng, alt_msl, alt_rel, roll, pitch, yaw, foc_len, flags, force_mavlink1]]:
constant[
Camera Capture Feedback
time_usec : Image timestamp (microseconds since UNIX e... | keyword[def] identifier[camera_feedback_send] ( identifier[self] , identifier[time_usec] , identifier[target_system] , identifier[cam_idx] , identifier[img_idx] , identifier[lat] , identifier[lng] , identifier[alt_msl] , identifier[alt_rel] , identifier[roll] , identifier[pitch] , identifier[yaw] , identifier[foc_len... | def camera_feedback_send(self, time_usec, target_system, cam_idx, img_idx, lat, lng, alt_msl, alt_rel, roll, pitch, yaw, foc_len, flags, force_mavlink1=False):
"""
Camera Capture Feedback
time_usec : Image timestamp (microseconds since UNIX epoch), as passed in by CA... |
def dumps(data, ac_parser=None, **options):
"""
Return string representation of 'data' in forced type format.
:param data: Config data object to dump
:param ac_parser: Forced parser type or ID or parser object
:param options: see :func:`dump`
:return: Backend-specific string representation for... | def function[dumps, parameter[data, ac_parser]]:
constant[
Return string representation of 'data' in forced type format.
:param data: Config data object to dump
:param ac_parser: Forced parser type or ID or parser object
:param options: see :func:`dump`
:return: Backend-specific string rep... | keyword[def] identifier[dumps] ( identifier[data] , identifier[ac_parser] = keyword[None] ,** identifier[options] ):
literal[string]
identifier[psr] = identifier[find] ( keyword[None] , identifier[forced_type] = identifier[ac_parser] )
keyword[return] identifier[psr] . identifier[dumps] ( identifier[... | def dumps(data, ac_parser=None, **options):
"""
Return string representation of 'data' in forced type format.
:param data: Config data object to dump
:param ac_parser: Forced parser type or ID or parser object
:param options: see :func:`dump`
:return: Backend-specific string representation for... |
def _locateConvergencePoint(stats, minOverlap, maxOverlap):
"""
Walk backwards through stats until you locate the first point that diverges
from target overlap values. We need this to handle cases where it might get
to target values, diverge, and then get back again. We want the last
convergence p... | def function[_locateConvergencePoint, parameter[stats, minOverlap, maxOverlap]]:
constant[
Walk backwards through stats until you locate the first point that diverges
from target overlap values. We need this to handle cases where it might get
to target values, diverge, and then get back again. We ... | keyword[def] identifier[_locateConvergencePoint] ( identifier[stats] , identifier[minOverlap] , identifier[maxOverlap] ):
literal[string]
keyword[for] identifier[i] , identifier[v] keyword[in] identifier[enumerate] ( identifier[stats] [::- literal[int] ]):
keyword[if] keyword[not] ( identifier[v... | def _locateConvergencePoint(stats, minOverlap, maxOverlap):
"""
Walk backwards through stats until you locate the first point that diverges
from target overlap values. We need this to handle cases where it might get
to target values, diverge, and then get back again. We want the last
convergence p... |
def load_snippet(self, name, package):
"""Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Args:
... | def function[load_snippet, parameter[self, name, package]]:
constant[Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activate... | keyword[def] identifier[load_snippet] ( identifier[self] , identifier[name] , identifier[package] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , identifier[name] ):
keyword[raise] identifier[SnippetError] (
identifier[self] ,
... | def load_snippet(self, name, package):
"""Starts the snippet apk with the given package name and connects.
Examples:
.. code-block:: python
ad.load_snippet(
name='maps', package='com.google.maps.snippets')
ad.maps.activateZoom('3')
Args:
... |
def _process_event(self, event, tagged_data):
"""Processes a single tf.Event and records it in tagged_data."""
event_type = event.WhichOneof('what')
# Handle the most common case first.
if event_type == 'summary':
for value in event.summary.value:
value = data_compat.migrate_value(value)
... | def function[_process_event, parameter[self, event, tagged_data]]:
constant[Processes a single tf.Event and records it in tagged_data.]
variable[event_type] assign[=] call[name[event].WhichOneof, parameter[constant[what]]]
if compare[name[event_type] equal[==] constant[summary]] begin[:]
... | keyword[def] identifier[_process_event] ( identifier[self] , identifier[event] , identifier[tagged_data] ):
literal[string]
identifier[event_type] = identifier[event] . identifier[WhichOneof] ( literal[string] )
keyword[if] identifier[event_type] == literal[string] :
keyword[for] identif... | def _process_event(self, event, tagged_data):
"""Processes a single tf.Event and records it in tagged_data."""
event_type = event.WhichOneof('what')
# Handle the most common case first.
if event_type == 'summary':
for value in event.summary.value:
value = data_compat.migrate_value(va... |
def parse_xml_data(self):
"""
Parses `xml_data` and loads it into object properties.
"""
self.raw_text = self.xml_data.find('raw_text').text
self.station = WeatherStation(self.xml_data.find('station_id').text)
self.station.latitude = float(self.xml_data.find('latitude').t... | def function[parse_xml_data, parameter[self]]:
constant[
Parses `xml_data` and loads it into object properties.
]
name[self].raw_text assign[=] call[name[self].xml_data.find, parameter[constant[raw_text]]].text
name[self].station assign[=] call[name[WeatherStation], parameter[cal... | keyword[def] identifier[parse_xml_data] ( identifier[self] ):
literal[string]
identifier[self] . identifier[raw_text] = identifier[self] . identifier[xml_data] . identifier[find] ( literal[string] ). identifier[text]
identifier[self] . identifier[station] = identifier[WeatherStation] ( id... | def parse_xml_data(self):
"""
Parses `xml_data` and loads it into object properties.
"""
self.raw_text = self.xml_data.find('raw_text').text
self.station = WeatherStation(self.xml_data.find('station_id').text)
self.station.latitude = float(self.xml_data.find('latitude').text)
self.st... |
def min_distance_single(self,
mesh,
transform=None,
return_name=False,
return_data=False):
"""
Get the minimum distance between a single object and any
object in the manager.
... | def function[min_distance_single, parameter[self, mesh, transform, return_name, return_data]]:
constant[
Get the minimum distance between a single object and any
object in the manager.
Parameters
---------------
mesh : Trimesh object
The geometry of the collisi... | keyword[def] identifier[min_distance_single] ( identifier[self] ,
identifier[mesh] ,
identifier[transform] = keyword[None] ,
identifier[return_name] = keyword[False] ,
identifier[return_data] = keyword[False] ):
literal[string]
keyword[if] identifier[transform] keyword[is] keyword[None] :
... | def min_distance_single(self, mesh, transform=None, return_name=False, return_data=False):
"""
Get the minimum distance between a single object and any
object in the manager.
Parameters
---------------
mesh : Trimesh object
The geometry of the collision object
... |
def fit_transform(self, X, y=None):
"""
Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
... | def function[fit_transform, parameter[self, X, y]]:
constant[
Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` an... | keyword[def] identifier[fit_transform] ( identifier[self] , identifier[X] , identifier[y] = keyword[None] ):
literal[string]
identifier[X_original] , identifier[missing_mask] = identifier[self] . identifier[prepare_input_data] ( identifier[X] )
identifier[observed_mask] =~ identifier[missi... | def fit_transform(self, X, y=None):
"""
Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
... |
def __check_config_key(self, key):
"""Check whether the key is valid.
A valid key has the schema <section>.<option>. Keys supported
are listed in CONFIG_OPTIONS dict.
:param key: <section>.<option> key
"""
try:
section, option = key.split('.')
except... | def function[__check_config_key, parameter[self, key]]:
constant[Check whether the key is valid.
A valid key has the schema <section>.<option>. Keys supported
are listed in CONFIG_OPTIONS dict.
:param key: <section>.<option> key
]
<ast.Try object at 0x7da1b0e25030>
... | keyword[def] identifier[__check_config_key] ( identifier[self] , identifier[key] ):
literal[string]
keyword[try] :
identifier[section] , identifier[option] = identifier[key] . identifier[split] ( literal[string] )
keyword[except] ( identifier[AttributeError] , identifier[Value... | def __check_config_key(self, key):
"""Check whether the key is valid.
A valid key has the schema <section>.<option>. Keys supported
are listed in CONFIG_OPTIONS dict.
:param key: <section>.<option> key
"""
try:
(section, option) = key.split('.') # depends on [control=[... |
def _serial_sanitizer(instr):
'''Replaces the last 1/4 of a string with X's'''
length = len(instr)
index = int(math.floor(length * .75))
return '{0}{1}'.format(instr[:index], 'X' * (length - index)) | def function[_serial_sanitizer, parameter[instr]]:
constant[Replaces the last 1/4 of a string with X's]
variable[length] assign[=] call[name[len], parameter[name[instr]]]
variable[index] assign[=] call[name[int], parameter[call[name[math].floor, parameter[binary_operation[name[length] * constant... | keyword[def] identifier[_serial_sanitizer] ( identifier[instr] ):
literal[string]
identifier[length] = identifier[len] ( identifier[instr] )
identifier[index] = identifier[int] ( identifier[math] . identifier[floor] ( identifier[length] * literal[int] ))
keyword[return] literal[string] . identif... | def _serial_sanitizer(instr):
"""Replaces the last 1/4 of a string with X's"""
length = len(instr)
index = int(math.floor(length * 0.75))
return '{0}{1}'.format(instr[:index], 'X' * (length - index)) |
def read_value_from_path(value):
"""Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt}
"""
if value.startswith('file://'):
path = value.split('file://', 1)[1]
config_directory = get_c... | def function[read_value_from_path, parameter[value]]:
constant[Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt}
]
if call[name[value].startswith, parameter[constant[file://]]] begin[:]
... | keyword[def] identifier[read_value_from_path] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] . identifier[startswith] ( literal[string] ):
identifier[path] = identifier[value] . identifier[split] ( literal[string] , literal[int] )[ literal[int] ]
identifier[config_d... | def read_value_from_path(value):
"""Enables translators to read values from files.
The value can be referred to with the `file://` prefix. ie:
conf_key: ${kms file://kms_value.txt}
"""
if value.startswith('file://'):
path = value.split('file://', 1)[1]
config_directory = get_c... |
def unique_id(self):
"""Creates a unique ID for the `Atom` based on its parents.
Returns
-------
unique_id : (str, str, str)
(polymer.id, residue.id, atom.id)
"""
chain = self.parent.parent.id
residue = self.parent.id
return chain, residue, se... | def function[unique_id, parameter[self]]:
constant[Creates a unique ID for the `Atom` based on its parents.
Returns
-------
unique_id : (str, str, str)
(polymer.id, residue.id, atom.id)
]
variable[chain] assign[=] name[self].parent.parent.id
variable[... | keyword[def] identifier[unique_id] ( identifier[self] ):
literal[string]
identifier[chain] = identifier[self] . identifier[parent] . identifier[parent] . identifier[id]
identifier[residue] = identifier[self] . identifier[parent] . identifier[id]
keyword[return] identifier[chain... | def unique_id(self):
"""Creates a unique ID for the `Atom` based on its parents.
Returns
-------
unique_id : (str, str, str)
(polymer.id, residue.id, atom.id)
"""
chain = self.parent.parent.id
residue = self.parent.id
return (chain, residue, self.id) |
def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
"""Open group using metadata previously consolidated into a single key.
This is an optimised method for opening a Zarr group, where instead of
traversing the group/array hierarchy by accessing the metadata keys at
each level,... | def function[open_consolidated, parameter[store, metadata_key, mode]]:
constant[Open group using metadata previously consolidated into a single key.
This is an optimised method for opening a Zarr group, where instead of
traversing the group/array hierarchy by accessing the metadata keys at
each lev... | keyword[def] identifier[open_consolidated] ( identifier[store] , identifier[metadata_key] = literal[string] , identifier[mode] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[from] . identifier[storage] keyword[import] identifier[ConsolidatedMetadataStore]
identifier[stor... | def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
"""Open group using metadata previously consolidated into a single key.
This is an optimised method for opening a Zarr group, where instead of
traversing the group/array hierarchy by accessing the metadata keys at
each level,... |
def load(self, elem):
"""
Converts the inputted string tag to Python.
:param elem | <xml.etree.ElementTree>
:return <str>
"""
self.testTag(elem, 'str')
return elem.text if elem.text is not None else '' | def function[load, parameter[self, elem]]:
constant[
Converts the inputted string tag to Python.
:param elem | <xml.etree.ElementTree>
:return <str>
]
call[name[self].testTag, parameter[name[elem], constant[str]]]
return[<ast.IfExp object at... | keyword[def] identifier[load] ( identifier[self] , identifier[elem] ):
literal[string]
identifier[self] . identifier[testTag] ( identifier[elem] , literal[string] )
keyword[return] identifier[elem] . identifier[text] keyword[if] identifier[elem] . identifier[text] keyword[is] keyword[... | def load(self, elem):
"""
Converts the inputted string tag to Python.
:param elem | <xml.etree.ElementTree>
:return <str>
"""
self.testTag(elem, 'str')
return elem.text if elem.text is not None else '' |
def expand_source_paths(paths):
""" Convert pyc files into their source equivalents."""
for src_path in paths:
# only track the source path if we can find it to avoid double-reloads
# when the source and the compiled path change because on some
# platforms they are not changed at the sam... | def function[expand_source_paths, parameter[paths]]:
constant[ Convert pyc files into their source equivalents.]
for taget[name[src_path]] in starred[name[paths]] begin[:]
if call[name[src_path].endswith, parameter[tuple[[<ast.Constant object at 0x7da1b11a8c10>, <ast.Constant object at 0... | keyword[def] identifier[expand_source_paths] ( identifier[paths] ):
literal[string]
keyword[for] identifier[src_path] keyword[in] identifier[paths] :
keyword[if] identifier[src_path] . identifier[endswith] (( literal[string] , literal[string] )):
identifier[py_path]... | def expand_source_paths(paths):
""" Convert pyc files into their source equivalents."""
for src_path in paths:
# only track the source path if we can find it to avoid double-reloads
# when the source and the compiled path change because on some
# platforms they are not changed at the sam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.