code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _issuer(self, entityid=None):
""" Return an Issuer instance """
if entityid:
if isinstance(entityid, Issuer):
return entityid
else:
return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY)
else:
return Issuer(text=self.conf... | def function[_issuer, parameter[self, entityid]]:
constant[ Return an Issuer instance ]
if name[entityid] begin[:]
if call[name[isinstance], parameter[name[entityid], name[Issuer]]] begin[:]
return[name[entityid]] | keyword[def] identifier[_issuer] ( identifier[self] , identifier[entityid] = keyword[None] ):
literal[string]
keyword[if] identifier[entityid] :
keyword[if] identifier[isinstance] ( identifier[entityid] , identifier[Issuer] ):
keyword[return] identifier[entityid]
... | def _issuer(self, entityid=None):
""" Return an Issuer instance """
if entityid:
if isinstance(entityid, Issuer):
return entityid # depends on [control=['if'], data=[]]
else:
return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY) # depends on [control=['if'], data=[]... |
def R(self,*args,**kwargs):
"""
NAME:
R
PURPOSE:
return cylindrical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to ... | def function[R, parameter[self]]:
constant[
NAME:
R
PURPOSE:
return cylindrical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physi... | keyword[def] identifier[R] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[thiso] = identifier[self] (* identifier[args] ,** identifier[kwargs] )
identifier[onet] =( identifier[len] ( identifier[thiso] . identifier[shape] )== literal[int] )
... | def R(self, *args, **kwargs):
"""
NAME:
R
PURPOSE:
return cylindrical radius at time t
INPUT:
t - (optional) time at which to get the radius
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to ov... |
def generate_network(nl_model,
handler,
seed=1234,
always_include_props=False,
include_connections=True,
include_inputs=True,
base_dir=None):
"""
Generate the network model as describ... | def function[generate_network, parameter[nl_model, handler, seed, always_include_props, include_connections, include_inputs, base_dir]]:
constant[
Generate the network model as described in NeuroMLlite in a specific handler,
e.g. NeuroMLHandler, PyNNHandler, etc.
]
variable[pop_locations] as... | keyword[def] identifier[generate_network] ( identifier[nl_model] ,
identifier[handler] ,
identifier[seed] = literal[int] ,
identifier[always_include_props] = keyword[False] ,
identifier[include_connections] = keyword[True] ,
identifier[include_inputs] = keyword[True] ,
identifier[base_dir] = keyword[None] ):
... | def generate_network(nl_model, handler, seed=1234, always_include_props=False, include_connections=True, include_inputs=True, base_dir=None):
"""
Generate the network model as described in NeuroMLlite in a specific handler,
e.g. NeuroMLHandler, PyNNHandler, etc.
"""
pop_locations = {}
cell_objec... |
def _check_pretrained_file_names(cls, pretrained_file_name):
"""Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file.
"""
embedding_name = cls.__name__.lower()
... | def function[_check_pretrained_file_names, parameter[cls, pretrained_file_name]]:
constant[Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file.
]
variable[embedding... | keyword[def] identifier[_check_pretrained_file_names] ( identifier[cls] , identifier[pretrained_file_name] ):
literal[string]
identifier[embedding_name] = identifier[cls] . identifier[__name__] . identifier[lower] ()
keyword[if] identifier[pretrained_file_name] keyword[not] keyword[in]... | def _check_pretrained_file_names(cls, pretrained_file_name):
"""Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file.
"""
embedding_name = cls.__name__.lower()
if pretra... |
def deleteAllActivationKeys(server):
'''
Delete all activation keys from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllActivationKeys spacewalk01.domain.com
'''
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'E... | def function[deleteAllActivationKeys, parameter[server]]:
constant[
Delete all activation keys from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllActivationKeys spacewalk01.domain.com
]
<ast.Try object at 0x7da1b2003f10>
variable[activation_keys] ... | keyword[def] identifier[deleteAllActivationKeys] ( identifier[server] ):
literal[string]
keyword[try] :
identifier[client] , identifier[key] = identifier[_get_session] ( identifier[server] )
keyword[except] identifier[Exception] keyword[as] identifier[exc] :
identifier[err_msg] =... | def deleteAllActivationKeys(server):
"""
Delete all activation keys from Spacewalk
CLI Example:
.. code-block:: bash
salt-run spacewalk.deleteAllActivationKeys spacewalk01.domain.com
"""
try:
(client, key) = _get_session(server) # depends on [control=['try'], data=[]]
exc... |
def _MoveFileToLibrary(self, oldPath, newPath):
"""
Move file from old file path to new file path. This follows certain
conditions:
- If file already exists at destination do rename inplace.
- If file destination is on same file system and doesn't exist rename and move.
- If source and de... | def function[_MoveFileToLibrary, parameter[self, oldPath, newPath]]:
constant[
Move file from old file path to new file path. This follows certain
conditions:
- If file already exists at destination do rename inplace.
- If file destination is on same file system and doesn't exist rename and... | keyword[def] identifier[_MoveFileToLibrary] ( identifier[self] , identifier[oldPath] , identifier[newPath] ):
literal[string]
keyword[if] identifier[oldPath] == identifier[newPath] :
keyword[return] keyword[False]
identifier[goodlogging] . identifier[Log] . identifier[Info] ( literal[string... | def _MoveFileToLibrary(self, oldPath, newPath):
"""
Move file from old file path to new file path. This follows certain
conditions:
- If file already exists at destination do rename inplace.
- If file destination is on same file system and doesn't exist rename and move.
- If source and de... |
def update(taxids, conn, force_download, silent):
"""Update local UniProt database"""
if not silent:
click.secho("WARNING: Update is very time consuming and can take several "
"hours depending which organisms you are importing!", fg="yellow")
if not taxids:
click... | def function[update, parameter[taxids, conn, force_download, silent]]:
constant[Update local UniProt database]
if <ast.UnaryOp object at 0x7da18fe93b80> begin[:]
call[name[click].secho, parameter[constant[WARNING: Update is very time consuming and can take several hours depending which o... | keyword[def] identifier[update] ( identifier[taxids] , identifier[conn] , identifier[force_download] , identifier[silent] ):
literal[string]
keyword[if] keyword[not] identifier[silent] :
identifier[click] . identifier[secho] ( literal[string]
literal[string] , identifier[fg] = literal[... | def update(taxids, conn, force_download, silent):
"""Update local UniProt database"""
if not silent:
click.secho('WARNING: Update is very time consuming and can take several hours depending which organisms you are importing!', fg='yellow')
if not taxids:
click.echo('Please note that ... |
def markdown(random=random, length=10, *args, **kwargs):
"""
Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\\nNobody will **head** _to_ Mystery Studies Department... | def function[markdown, parameter[random, length]]:
constant[
Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\nNobody will **head** _to_ Mystery Studies Departm... | keyword[def] identifier[markdown] ( identifier[random] = identifier[random] , identifier[length] = literal[int] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[title_sentence] ():
keyword[return] literal[string] + literal[string] * identifier[random] . iden... | def markdown(random=random, length=10, *args, **kwargs):
"""
Produces a bunch of markdown text.
>>> mock_random.seed(0)
>>> markdown(random=mock_random, length=2)
'Nobody will **head** _to_ Mystery Studies Department **to** _buy_ a mighty poop.\\nNobody will **head** _to_ Mystery Studies Department... |
def _equally_weight_samples(samples, weights):
""" Convert samples to be equally weighted.
Samples are trimmed by discarding samples in accordance with a probability
determined by the corresponding weight.
This function has assumed you have normalised the weights properly.
If in doubt, convert wei... | def function[_equally_weight_samples, parameter[samples, weights]]:
constant[ Convert samples to be equally weighted.
Samples are trimmed by discarding samples in accordance with a probability
determined by the corresponding weight.
This function has assumed you have normalised the weights properl... | keyword[def] identifier[_equally_weight_samples] ( identifier[samples] , identifier[weights] ):
literal[string]
keyword[if] identifier[len] ( identifier[weights] )!= identifier[len] ( identifier[samples] ):
keyword[raise] identifier[ValueError] ( literal[string] %
( identifier[len] ( ide... | def _equally_weight_samples(samples, weights):
""" Convert samples to be equally weighted.
Samples are trimmed by discarding samples in accordance with a probability
determined by the corresponding weight.
This function has assumed you have normalised the weights properly.
If in doubt, convert wei... |
def init_app(self, app):
"""
Register this extension with the flask app
:param app: A flask application
"""
# Save this so we can use it later in the extension
if not hasattr(app, 'extensions'): # pragma: no cover
app.extensions = {}
app.extensions[... | def function[init_app, parameter[self, app]]:
constant[
Register this extension with the flask app
:param app: A flask application
]
if <ast.UnaryOp object at 0x7da1b1037d00> begin[:]
name[app].extensions assign[=] dictionary[[], []]
call[name[app].extens... | keyword[def] identifier[init_app] ( identifier[self] , identifier[app] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[app] , literal[string] ):
identifier[app] . identifier[extensions] ={}
identifier[app] . identifier[extensions] [ lite... | def init_app(self, app):
"""
Register this extension with the flask app
:param app: A flask application
"""
# Save this so we can use it later in the extension
if not hasattr(app, 'extensions'): # pragma: no cover
app.extensions = {} # depends on [control=['if'], data=[]]
... |
def export_ply(filename, cutout, level=0):
"""
Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes).
Arguments:
filename (str): The filename to write out to
cutout (numpy.ndarray): The dense annotation
level (int): The level at which to run mcubes
Returns:
... | def function[export_ply, parameter[filename, cutout, level]]:
constant[
Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes).
Arguments:
filename (str): The filename to write out to
cutout (numpy.ndarray): The dense annotation
level (int): The level at which to... | keyword[def] identifier[export_ply] ( identifier[filename] , identifier[cutout] , identifier[level] = literal[int] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[filename] :
identifier[filename] = identifier[filename] + literal[string]
identifier[vs] ... | def export_ply(filename, cutout, level=0):
"""
Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes).
Arguments:
filename (str): The filename to write out to
cutout (numpy.ndarray): The dense annotation
level (int): The level at which to run mcubes
Returns:
... |
def located_error(
original_error: Union[Exception, GraphQLError],
nodes: Sequence["Node"],
path: Sequence[Union[str, int]],
) -> GraphQLError:
"""Located GraphQL Error
Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL
operation, produce a new GraphQLError aware ... | def function[located_error, parameter[original_error, nodes, path]]:
constant[Located GraphQL Error
Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL
operation, produce a new GraphQLError aware of the location in the document
responsible for the original Error.
]... | keyword[def] identifier[located_error] (
identifier[original_error] : identifier[Union] [ identifier[Exception] , identifier[GraphQLError] ],
identifier[nodes] : identifier[Sequence] [ literal[string] ],
identifier[path] : identifier[Sequence] [ identifier[Union] [ identifier[str] , identifier[int] ]],
)-> identif... | def located_error(original_error: Union[Exception, GraphQLError], nodes: Sequence['Node'], path: Sequence[Union[str, int]]) -> GraphQLError:
"""Located GraphQL Error
Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL
operation, produce a new GraphQLError aware of the location... |
def som_train(som_pointer, data, epochs, autostop):
"""!
@brief Trains self-organized feature map (SOM) using CCORE pyclustering library.
@param[in] data (list): Input data - list of points where each point is represented by list of features, for example coordinates.
@param[in] epochs (uint): Numb... | def function[som_train, parameter[som_pointer, data, epochs, autostop]]:
constant[!
@brief Trains self-organized feature map (SOM) using CCORE pyclustering library.
@param[in] data (list): Input data - list of points where each point is represented by list of features, for example coordinates.
@par... | keyword[def] identifier[som_train] ( identifier[som_pointer] , identifier[data] , identifier[epochs] , identifier[autostop] ):
literal[string]
identifier[pointer_data] = identifier[package_builder] ( identifier[data] , identifier[c_double] ). identifier[create] ()
identifier[ccore] = identifier... | def som_train(som_pointer, data, epochs, autostop):
"""!
@brief Trains self-organized feature map (SOM) using CCORE pyclustering library.
@param[in] data (list): Input data - list of points where each point is represented by list of features, for example coordinates.
@param[in] epochs (uint): Number of... |
def get_energy_management_properties(self):
"""
Return the energy management properties of the CPC.
The returned energy management properties are a subset of the
properties of the CPC resource, and are also available as normal
properties of the CPC resource. In so far, there is ... | def function[get_energy_management_properties, parameter[self]]:
constant[
Return the energy management properties of the CPC.
The returned energy management properties are a subset of the
properties of the CPC resource, and are also available as normal
properties of the CPC res... | keyword[def] identifier[get_energy_management_properties] ( identifier[self] ):
literal[string]
identifier[result] = identifier[self] . identifier[manager] . identifier[session] . identifier[get] ( identifier[self] . identifier[uri] + literal[string] )
identifier[em_list] = identifier[resu... | def get_energy_management_properties(self):
"""
Return the energy management properties of the CPC.
The returned energy management properties are a subset of the
properties of the CPC resource, and are also available as normal
properties of the CPC resource. In so far, there is no n... |
def _get_connection(self, conn_or_int_id):
"""Get the data for a connection by either conn_id or internal_id
Args:
conn_or_int_id (int, string): The external integer connection id or
and internal string connection id
Returns:
dict: The context data assoc... | def function[_get_connection, parameter[self, conn_or_int_id]]:
constant[Get the data for a connection by either conn_id or internal_id
Args:
conn_or_int_id (int, string): The external integer connection id or
and internal string connection id
Returns:
d... | keyword[def] identifier[_get_connection] ( identifier[self] , identifier[conn_or_int_id] ):
literal[string]
identifier[key] = identifier[conn_or_int_id]
keyword[if] identifier[isinstance] ( identifier[key] , identifier[str] ):
identifier[table] = identifier[self] . identifi... | def _get_connection(self, conn_or_int_id):
"""Get the data for a connection by either conn_id or internal_id
Args:
conn_or_int_id (int, string): The external integer connection id or
and internal string connection id
Returns:
dict: The context data associate... |
def status(self):
"""
Check if the daemon is currently running.
Requires procfs, so it will only work on POSIX compliant OS'.
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
return False
... | def function[status, parameter[self]]:
constant[
Check if the daemon is currently running.
Requires procfs, so it will only work on POSIX compliant OS'.
]
<ast.Try object at 0x7da1b16d7880>
if <ast.UnaryOp object at 0x7da1b16d7190> begin[:]
return[constant[False]]
<ast.Try object a... | keyword[def] identifier[status] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[pf] = identifier[file] ( identifier[self] . identifier[pidfile] , literal[string] )
identifier[pid] = identifier[int] ( identifier[pf] . identifier[read] (). identifier[strip] ())
identifier[pf] . ide... | def status(self):
"""
Check if the daemon is currently running.
Requires procfs, so it will only work on POSIX compliant OS'.
""" # Get the pid from the pidfile
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close() # depends on [control=['try'], data=[]]
e... |
def get_grouped_translations(instances, **kwargs):
"""
Takes instances and returns grouped translations ready to
be set in cache.
"""
grouped_translations = collections.defaultdict(list)
if not instances:
return grouped_translations
if not isinstance(instances, collections.Iterable... | def function[get_grouped_translations, parameter[instances]]:
constant[
Takes instances and returns grouped translations ready to
be set in cache.
]
variable[grouped_translations] assign[=] call[name[collections].defaultdict, parameter[name[list]]]
if <ast.UnaryOp object at 0x7da18c4... | keyword[def] identifier[get_grouped_translations] ( identifier[instances] ,** identifier[kwargs] ):
literal[string]
identifier[grouped_translations] = identifier[collections] . identifier[defaultdict] ( identifier[list] )
keyword[if] keyword[not] identifier[instances] :
keyword[return] id... | def get_grouped_translations(instances, **kwargs):
"""
Takes instances and returns grouped translations ready to
be set in cache.
"""
grouped_translations = collections.defaultdict(list)
if not instances:
return grouped_translations # depends on [control=['if'], data=[]]
if not isin... |
def __emulate_buttons(self, changed_buttons, timeval=None):
"""Make the button events use the Linux style format."""
events = []
for button in changed_buttons:
code, value, ev_type = self.__map_button(button)
event = self.create_event_object(
ev_type,
... | def function[__emulate_buttons, parameter[self, changed_buttons, timeval]]:
constant[Make the button events use the Linux style format.]
variable[events] assign[=] list[[]]
for taget[name[button]] in starred[name[changed_buttons]] begin[:]
<ast.Tuple object at 0x7da1b084fb20> ass... | keyword[def] identifier[__emulate_buttons] ( identifier[self] , identifier[changed_buttons] , identifier[timeval] = keyword[None] ):
literal[string]
identifier[events] =[]
keyword[for] identifier[button] keyword[in] identifier[changed_buttons] :
identifier[code] , identifie... | def __emulate_buttons(self, changed_buttons, timeval=None):
"""Make the button events use the Linux style format."""
events = []
for button in changed_buttons:
(code, value, ev_type) = self.__map_button(button)
event = self.create_event_object(ev_type, code, value, timeval=timeval)
e... |
def calculate_a(self):
"""
Calculate the client's public value A = g^a%N
with the generated random number a
:param {Long integer} a Randomly generated small A.
:return {Long integer} Computed large A.
"""
big_a = pow(self.g, self.small_a_value, self.big_n)
... | def function[calculate_a, parameter[self]]:
constant[
Calculate the client's public value A = g^a%N
with the generated random number a
:param {Long integer} a Randomly generated small A.
:return {Long integer} Computed large A.
]
variable[big_a] assign[=] call[nam... | keyword[def] identifier[calculate_a] ( identifier[self] ):
literal[string]
identifier[big_a] = identifier[pow] ( identifier[self] . identifier[g] , identifier[self] . identifier[small_a_value] , identifier[self] . identifier[big_n] )
keyword[if] ( identifier[big_a] % identifier[se... | def calculate_a(self):
"""
Calculate the client's public value A = g^a%N
with the generated random number a
:param {Long integer} a Randomly generated small A.
:return {Long integer} Computed large A.
"""
big_a = pow(self.g, self.small_a_value, self.big_n)
# safety ch... |
def writeto(fpath, to_write, aslines=False, verbose=None):
r"""
Writes (utf8) text to a file.
Args:
fpath (PathLike): file path
to_write (str): text to write (must be unicode text)
aslines (bool): if True to_write is assumed to be a list of lines
verbose (bool): verbosity fl... | def function[writeto, parameter[fpath, to_write, aslines, verbose]]:
constant[
Writes (utf8) text to a file.
Args:
fpath (PathLike): file path
to_write (str): text to write (must be unicode text)
aslines (bool): if True to_write is assumed to be a list of lines
verbose (... | keyword[def] identifier[writeto] ( identifier[fpath] , identifier[to_write] , identifier[aslines] = keyword[False] , identifier[verbose] = keyword[None] ):
literal[string]
keyword[if] identifier[verbose] :
identifier[print] ( literal[string] %( identifier[fpath] ,))
keyword[with] identifie... | def writeto(fpath, to_write, aslines=False, verbose=None):
"""
Writes (utf8) text to a file.
Args:
fpath (PathLike): file path
to_write (str): text to write (must be unicode text)
aslines (bool): if True to_write is assumed to be a list of lines
verbose (bool): verbosity fla... |
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
old_umask = os.umask(0o... | def function[_create_file_if_needed, parameter[self]]:
constant[Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
]
if <ast.UnaryOp object at 0x7da1b014d840> begin[:... | keyword[def] identifier[_create_file_if_needed] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[_filename] ):
identifier[old_umask] = identifier[os] . identifier[umask] ( literal[int... | def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
old_umask = os.umask(127)
t... |
def set_default_symbols(self):
"""Set self.symbols based on self.numbers and the periodic table."""
self.symbols = tuple(periodic[n].symbol for n in self.numbers) | def function[set_default_symbols, parameter[self]]:
constant[Set self.symbols based on self.numbers and the periodic table.]
name[self].symbols assign[=] call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da20c6abb50>]] | keyword[def] identifier[set_default_symbols] ( identifier[self] ):
literal[string]
identifier[self] . identifier[symbols] = identifier[tuple] ( identifier[periodic] [ identifier[n] ]. identifier[symbol] keyword[for] identifier[n] keyword[in] identifier[self] . identifier[numbers] ) | def set_default_symbols(self):
"""Set self.symbols based on self.numbers and the periodic table."""
self.symbols = tuple((periodic[n].symbol for n in self.numbers)) |
def run_radia_perchrom(job, bams, univ_options, radia_options, chrom):
"""
Run RADIA call on a single chromosome in the input bams.
:param dict bams: Dict of bam and bai for tumor DNA-Seq, normal DNA-Seq and tumor RNA-Seq
:param dict univ_options: Dict of universal options used by almost all tools
... | def function[run_radia_perchrom, parameter[job, bams, univ_options, radia_options, chrom]]:
constant[
Run RADIA call on a single chromosome in the input bams.
:param dict bams: Dict of bam and bai for tumor DNA-Seq, normal DNA-Seq and tumor RNA-Seq
:param dict univ_options: Dict of universal option... | keyword[def] identifier[run_radia_perchrom] ( identifier[job] , identifier[bams] , identifier[univ_options] , identifier[radia_options] , identifier[chrom] ):
literal[string]
identifier[work_dir] = identifier[os] . identifier[getcwd] ()
identifier[input_files] ={
literal[string] : identifier[bams... | def run_radia_perchrom(job, bams, univ_options, radia_options, chrom):
"""
Run RADIA call on a single chromosome in the input bams.
:param dict bams: Dict of bam and bai for tumor DNA-Seq, normal DNA-Seq and tumor RNA-Seq
:param dict univ_options: Dict of universal options used by almost all tools
... |
def rpc_is_name_zonefile_hash(self, name, zonefile_hash, **con_info):
"""
Was a zone file hash issued by a name? Return {'result': True/False}
"""
if not check_name(name) and not check_subdomain(name):
return {'error': 'invalid name', 'http_status': 400}
if not chec... | def function[rpc_is_name_zonefile_hash, parameter[self, name, zonefile_hash]]:
constant[
Was a zone file hash issued by a name? Return {'result': True/False}
]
if <ast.BoolOp object at 0x7da18f00e950> begin[:]
return[dictionary[[<ast.Constant object at 0x7da18f00f6d0>, <ast.Cons... | keyword[def] identifier[rpc_is_name_zonefile_hash] ( identifier[self] , identifier[name] , identifier[zonefile_hash] ,** identifier[con_info] ):
literal[string]
keyword[if] keyword[not] identifier[check_name] ( identifier[name] ) keyword[and] keyword[not] identifier[check_subdomain] ( identifie... | def rpc_is_name_zonefile_hash(self, name, zonefile_hash, **con_info):
"""
Was a zone file hash issued by a name? Return {'result': True/False}
"""
if not check_name(name) and (not check_subdomain(name)):
return {'error': 'invalid name', 'http_status': 400} # depends on [control=['if'],... |
def del_controller(self):
"""
Deletes the configured OpenFlow controller address.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl del-controller <bridge>
"""
command = ovs_vsctl.VSCtlCommand('del-controller', [self.br_name])
sel... | def function[del_controller, parameter[self]]:
constant[
Deletes the configured OpenFlow controller address.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl del-controller <bridge>
]
variable[command] assign[=] call[name[ovs_vsctl].VSCt... | keyword[def] identifier[del_controller] ( identifier[self] ):
literal[string]
identifier[command] = identifier[ovs_vsctl] . identifier[VSCtlCommand] ( literal[string] ,[ identifier[self] . identifier[br_name] ])
identifier[self] . identifier[run_command] ([ identifier[command] ]) | def del_controller(self):
"""
Deletes the configured OpenFlow controller address.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl del-controller <bridge>
"""
command = ovs_vsctl.VSCtlCommand('del-controller', [self.br_name])
self.run_comman... |
def _handle_status(self, msg):
"""
Reimplemented to refresh the namespacebrowser after kernel
restarts
"""
state = msg['content'].get('execution_state', '')
msg_type = msg['parent_header'].get('msg_type', '')
if state == 'starting':
# This is needed to... | def function[_handle_status, parameter[self, msg]]:
constant[
Reimplemented to refresh the namespacebrowser after kernel
restarts
]
variable[state] assign[=] call[call[name[msg]][constant[content]].get, parameter[constant[execution_state], constant[]]]
variable[msg_type] ... | keyword[def] identifier[_handle_status] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[state] = identifier[msg] [ literal[string] ]. identifier[get] ( literal[string] , literal[string] )
identifier[msg_type] = identifier[msg] [ literal[string] ]. identifier[get] ( liter... | def _handle_status(self, msg):
"""
Reimplemented to refresh the namespacebrowser after kernel
restarts
"""
state = msg['content'].get('execution_state', '')
msg_type = msg['parent_header'].get('msg_type', '')
if state == 'starting':
# This is needed to show the time a ker... |
def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | def function[code, parameter[self]]:
constant[the http status code to return to the client, by default, 200 if a body is present otherwise 204]
variable[code] assign[=] call[name[getattr], parameter[name[self], constant[_code], constant[None]]]
if <ast.UnaryOp object at 0x7da2049625c0> begin[:]
... | keyword[def] identifier[code] ( identifier[self] ):
literal[string]
identifier[code] = identifier[getattr] ( identifier[self] , literal[string] , keyword[None] )
keyword[if] keyword[not] identifier[code] :
keyword[if] identifier[self] . identifier[has_body] ():
... | def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200 # depends on [control=['if'], data=[]]
else:
code = 204 # depends o... |
def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and chrominance.
:return: RGB r... | def function[yiq_to_rgb, parameter[yiq]]:
constant[
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and ... | keyword[def] identifier[yiq_to_rgb] ( identifier[yiq] ):
literal[string]
identifier[y] , identifier[i] , identifier[q] = identifier[yiq]
identifier[r] = identifier[y] +( literal[int] * identifier[i] )+( literal[int] * identifier[q] )
identifier[g] = identifier[y] -( literal[int] * identifier[i] ... | def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and chrominance.
:return: RGB r... |
def consumer_partitions_for_topic(consumer, topic):
"""Returns a list of all TopicPartitions for a given topic.
Arguments:
consumer: an initialized KafkaConsumer
topic: a topic name to fetch TopicPartitions for
:returns:
list(TopicPartition): A list of TopicPartitions that belong t... | def function[consumer_partitions_for_topic, parameter[consumer, topic]]:
constant[Returns a list of all TopicPartitions for a given topic.
Arguments:
consumer: an initialized KafkaConsumer
topic: a topic name to fetch TopicPartitions for
:returns:
list(TopicPartition): A list o... | keyword[def] identifier[consumer_partitions_for_topic] ( identifier[consumer] , identifier[topic] ):
literal[string]
identifier[topic_partitions] =[]
identifier[partitions] = identifier[consumer] . identifier[partitions_for_topic] ( identifier[topic] )
keyword[if] identifier[partitions] keyword... | def consumer_partitions_for_topic(consumer, topic):
"""Returns a list of all TopicPartitions for a given topic.
Arguments:
consumer: an initialized KafkaConsumer
topic: a topic name to fetch TopicPartitions for
:returns:
list(TopicPartition): A list of TopicPartitions that belong t... |
def apply_smoothing(self, smooth_fwhm):
"""Set self._smooth_fwhm and then smooths the data.
See boyle.nifti.smooth.smooth_imgs.
Returns
-------
the smoothed data deepcopied.
"""
if smooth_fwhm <= 0:
return
old_smooth_fwhm = self._smooth_fw... | def function[apply_smoothing, parameter[self, smooth_fwhm]]:
constant[Set self._smooth_fwhm and then smooths the data.
See boyle.nifti.smooth.smooth_imgs.
Returns
-------
the smoothed data deepcopied.
]
if compare[name[smooth_fwhm] less_or_equal[<=] constant[0]]... | keyword[def] identifier[apply_smoothing] ( identifier[self] , identifier[smooth_fwhm] ):
literal[string]
keyword[if] identifier[smooth_fwhm] <= literal[int] :
keyword[return]
identifier[old_smooth_fwhm] = identifier[self] . identifier[_smooth_fwhm]
identifier[self... | def apply_smoothing(self, smooth_fwhm):
"""Set self._smooth_fwhm and then smooths the data.
See boyle.nifti.smooth.smooth_imgs.
Returns
-------
the smoothed data deepcopied.
"""
if smooth_fwhm <= 0:
return # depends on [control=['if'], data=[]]
old_smooth_f... |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
download_debug_certificate
/organizations/<id>/download_debug_certificate
subscriptions
/organizations/<id>/subscripti... | def function[path, parameter[self, which]]:
constant[Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
download_debug_certificate
/organizations/<id>/download_debug_certificate
subscriptions
/organiz... | keyword[def] identifier[path] ( identifier[self] , identifier[which] = keyword[None] ):
literal[string]
keyword[if] identifier[which] keyword[in] (
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
liter... | def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
download_debug_certificate
/organizations/<id>/download_debug_certificate
subscriptions
/organizations/<id>/subscriptions
... |
def add_indicator(self, indicator_data):
"""Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
... | def function[add_indicator, parameter[self, indicator_data]]:
constant[Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
... | keyword[def] identifier[add_indicator] ( identifier[self] , identifier[indicator_data] ):
literal[string]
keyword[if] identifier[indicator_data] . identifier[get] ( literal[string] ) keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] , literal[string]... | def add_indicator(self, indicator_data):
"""Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
: 5... |
def descendants(self):
"""Recursively return every dataset below current item."""
for i in self.current_item.items:
self.move_to(i)
if i.type == TYPE_COLLECTION:
for c in self.children:
yield c
else:
yield i
... | def function[descendants, parameter[self]]:
constant[Recursively return every dataset below current item.]
for taget[name[i]] in starred[name[self].current_item.items] begin[:]
call[name[self].move_to, parameter[name[i]]]
if compare[name[i].type equal[==] name[TYPE_COLLEC... | keyword[def] identifier[descendants] ( identifier[self] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[self] . identifier[current_item] . identifier[items] :
identifier[self] . identifier[move_to] ( identifier[i] )
keyword[if] identifier[i] . iden... | def descendants(self):
"""Recursively return every dataset below current item."""
for i in self.current_item.items:
self.move_to(i)
if i.type == TYPE_COLLECTION:
for c in self.children:
yield c # depends on [control=['for'], data=['c']] # depends on [control=['if'],... |
def _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1):
"""
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
"""
qs = (np.arange(1, n + 1) - 0.5) / n
rank = np.empty(len(qs))
b... | def function[_make_rank, parameter[dist_obj, n, mu, sigma, crit, upper, xtol]]:
constant[
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
]
variable[qs] assign[=] binary_operation[binary_oper... | keyword[def] identifier[_make_rank] ( identifier[dist_obj] , identifier[n] , identifier[mu] , identifier[sigma] , identifier[crit] = literal[int] , identifier[upper] = literal[int] , identifier[xtol] = literal[int] ):
literal[string]
identifier[qs] =( identifier[np] . identifier[arange] ( literal[int] , id... | def _make_rank(dist_obj, n, mu, sigma, crit=0.5, upper=10000, xtol=1):
"""
Make rank distribution using both ppf and brute force.
Setting crit = 1 is equivalent to just using the ppf
Parameters
----------
{0}
"""
qs = (np.arange(1, n + 1) - 0.5) / n
rank = np.empty(len(qs))
br... |
def robust_backtrack(self):
"""Estimate step size L by computing a linesearch that
guarantees that F <= Q according to the robust FISTA
backtracking strategy in :cite:`florea-2017-robust`.
This also updates all the supporting variables.
"""
self.L *= self.L_gamma_d
... | def function[robust_backtrack, parameter[self]]:
constant[Estimate step size L by computing a linesearch that
guarantees that F <= Q according to the robust FISTA
backtracking strategy in :cite:`florea-2017-robust`.
This also updates all the supporting variables.
]
<ast.AugAs... | keyword[def] identifier[robust_backtrack] ( identifier[self] ):
literal[string]
identifier[self] . identifier[L] *= identifier[self] . identifier[L_gamma_d]
identifier[maxiter] = identifier[self] . identifier[L_maxiter]
identifier[iterBTrack] = literal[int]
identifie... | def robust_backtrack(self):
"""Estimate step size L by computing a linesearch that
guarantees that F <= Q according to the robust FISTA
backtracking strategy in :cite:`florea-2017-robust`.
This also updates all the supporting variables.
"""
self.L *= self.L_gamma_d
maxiter = ... |
def _sparse_blockify(tuples, dtype=None):
""" return an array of blocks that potentially have different dtypes (and
are sparse)
"""
new_blocks = []
for i, names, array in tuples:
array = _maybe_to_sparse(array)
block = make_block(array, placement=[i])
new_blocks.append(block... | def function[_sparse_blockify, parameter[tuples, dtype]]:
constant[ return an array of blocks that potentially have different dtypes (and
are sparse)
]
variable[new_blocks] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da18f00ea40>, <ast.Name object at 0x7da18f00fb20>, <ast.... | keyword[def] identifier[_sparse_blockify] ( identifier[tuples] , identifier[dtype] = keyword[None] ):
literal[string]
identifier[new_blocks] =[]
keyword[for] identifier[i] , identifier[names] , identifier[array] keyword[in] identifier[tuples] :
identifier[array] = identifier[_maybe_to_spa... | def _sparse_blockify(tuples, dtype=None):
""" return an array of blocks that potentially have different dtypes (and
are sparse)
"""
new_blocks = []
for (i, names, array) in tuples:
array = _maybe_to_sparse(array)
block = make_block(array, placement=[i])
new_blocks.append(bloc... |
def histogram(self, counts, bin_edges, linestyle='solid'):
"""Plot a polar histogram.
The user needs to supply the histogram. This method only plots
the results. You can use NumPy's histogram function.
:param counts: array containing the count values.
:param bin_edges: array ... | def function[histogram, parameter[self, counts, bin_edges, linestyle]]:
constant[Plot a polar histogram.
The user needs to supply the histogram. This method only plots
the results. You can use NumPy's histogram function.
:param counts: array containing the count values.
:para... | keyword[def] identifier[histogram] ( identifier[self] , identifier[counts] , identifier[bin_edges] , identifier[linestyle] = literal[string] ):
literal[string]
keyword[if] identifier[len] ( identifier[bin_edges] )- literal[int] != identifier[len] ( identifier[counts] ):
keyword[raise]... | def histogram(self, counts, bin_edges, linestyle='solid'):
"""Plot a polar histogram.
The user needs to supply the histogram. This method only plots
the results. You can use NumPy's histogram function.
:param counts: array containing the count values.
:param bin_edges: array cont... |
def save_items(self, rows=None, verbose=False):
"""
Return a dictionary of row data for selected rows:
{1: {col1: val1, col2: val2}, ...}
If a list of row numbers isn't provided, get data for all.
"""
if rows:
rows = rows
else:
rows = list(... | def function[save_items, parameter[self, rows, verbose]]:
constant[
Return a dictionary of row data for selected rows:
{1: {col1: val1, col2: val2}, ...}
If a list of row numbers isn't provided, get data for all.
]
if name[rows] begin[:]
variable[rows] ass... | keyword[def] identifier[save_items] ( identifier[self] , identifier[rows] = keyword[None] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[if] identifier[rows] :
identifier[rows] = identifier[rows]
keyword[else] :
identifier[rows] = identifier[l... | def save_items(self, rows=None, verbose=False):
"""
Return a dictionary of row data for selected rows:
{1: {col1: val1, col2: val2}, ...}
If a list of row numbers isn't provided, get data for all.
"""
if rows:
rows = rows # depends on [control=['if'], data=[]]
else:
... |
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseGuideline.isCompatible`.
Subclasses may override this method.
"""
guideline1 = self
guideline2 = other
# guideline names
if guideline1.name != guide... | def function[_isCompatible, parameter[self, other, reporter]]:
constant[
This is the environment implementation of
:meth:`BaseGuideline.isCompatible`.
Subclasses may override this method.
]
variable[guideline1] assign[=] name[self]
variable[guideline2] assign[=] ... | keyword[def] identifier[_isCompatible] ( identifier[self] , identifier[other] , identifier[reporter] ):
literal[string]
identifier[guideline1] = identifier[self]
identifier[guideline2] = identifier[other]
keyword[if] identifier[guideline1] . identifier[name] != identif... | def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseGuideline.isCompatible`.
Subclasses may override this method.
"""
guideline1 = self
guideline2 = other
# guideline names
if guideline1.name != guideline2.name:
... |
def initialize(self, id=None, text=None):
self.id = none_or(id, int)
"""
Contributing user's identifier : int | None
"""
self.text = none_or(text, str)
"""
Username or IP address of the user at the time of the edit : str | None
""" | def function[initialize, parameter[self, id, text]]:
name[self].id assign[=] call[name[none_or], parameter[name[id], name[int]]]
constant[
Contributing user's identifier : int | None
]
name[self].text assign[=] call[name[none_or], parameter[name[text], name[str]]]
constan... | keyword[def] identifier[initialize] ( identifier[self] , identifier[id] = keyword[None] , identifier[text] = keyword[None] ):
identifier[self] . identifier[id] = identifier[none_or] ( identifier[id] , identifier[int] )
literal[string]
identifier[self] . identifier[text] = identifier[none_... | def initialize(self, id=None, text=None):
self.id = none_or(id, int)
"\n Contributing user's identifier : int | None\n "
self.text = none_or(text, str)
'\n Username or IP address of the user at the time of the edit : str | None\n ' |
def p_factor_unary_operators(self, p):
"""
term : SUB factor
| ADD factor
"""
p[0] = p[2]
if p[1] == '-':
p[0] = Instruction('-x', context={'x': p[0]}) | def function[p_factor_unary_operators, parameter[self, p]]:
constant[
term : SUB factor
| ADD factor
]
call[name[p]][constant[0]] assign[=] call[name[p]][constant[2]]
if compare[call[name[p]][constant[1]] equal[==] constant[-]] begin[:]
call[name[p]][... | keyword[def] identifier[p_factor_unary_operators] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[p] [ literal[int] ]
keyword[if] identifier[p] [ literal[int] ]== literal[string] :
identifier[p] [ literal[int] ]= identifier[In... | def p_factor_unary_operators(self, p):
"""
term : SUB factor
| ADD factor
"""
p[0] = p[2]
if p[1] == '-':
p[0] = Instruction('-x', context={'x': p[0]}) # depends on [control=['if'], data=[]] |
def _get_column(in_file, out_file, column, data=None):
"""Subset one column from a file
"""
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, 'w') as out_handle:
for line in in_handle:
cols = ... | def function[_get_column, parameter[in_file, out_file, column, data]]:
constant[Subset one column from a file
]
with call[name[file_transaction], parameter[name[data], name[out_file]]] begin[:]
with call[name[open], parameter[name[in_file]]] begin[:]
with call... | keyword[def] identifier[_get_column] ( identifier[in_file] , identifier[out_file] , identifier[column] , identifier[data] = keyword[None] ):
literal[string]
keyword[with] identifier[file_transaction] ( identifier[data] , identifier[out_file] ) keyword[as] identifier[tx_out_file] :
keyword[with] ... | def _get_column(in_file, out_file, column, data=None):
"""Subset one column from a file
"""
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, 'w') as out_handle:
for line in in_handle:
cols = ... |
def check_package_data(dist, attr, value):
"""Verify that value is a dictionary of package names to glob lists"""
if isinstance(value, dict):
for k, v in value.items():
if not isinstance(k, str):
break
try:
iter(v)
except TypeError:
... | def function[check_package_data, parameter[dist, attr, value]]:
constant[Verify that value is a dictionary of package names to glob lists]
if call[name[isinstance], parameter[name[value], name[dict]]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da1b1b14700>, <ast.Name object at 0x7d... | keyword[def] identifier[check_package_data] ( identifier[dist] , identifier[attr] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[dict] ):
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[value] . identifier[items] ():... | def check_package_data(dist, attr, value):
"""Verify that value is a dictionary of package names to glob lists"""
if isinstance(value, dict):
for (k, v) in value.items():
if not isinstance(k, str):
break # depends on [control=['if'], data=[]]
try:
... |
def validate(self, name, value):
"""Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.
"""
validator = self.attribute_vali... | def function[validate, parameter[self, name, value]]:
constant[Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.
]
variab... | keyword[def] identifier[validate] ( identifier[self] , identifier[name] , identifier[value] ):
literal[string]
identifier[validator] = identifier[self] . identifier[attribute_validators] . identifier[get] ( identifier[name] , keyword[None] )
keyword[if] identifier[validator] :
... | def validate(self, name, value):
"""Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.
"""
validator = self.attribute_validators.g... |
def generate(num_nodes, num_edges, directed=False, weight_range=(1, 1)):
"""
Create a random graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type directed: bool
@param directed: Whether the ge... | def function[generate, parameter[num_nodes, num_edges, directed, weight_range]]:
constant[
Create a random graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type directed: bool
@param direct... | keyword[def] identifier[generate] ( identifier[num_nodes] , identifier[num_edges] , identifier[directed] = keyword[False] , identifier[weight_range] =( literal[int] , literal[int] )):
literal[string]
keyword[if] identifier[directed] :
identifier[random_graph] = identifier[digraph] ()
ke... | def generate(num_nodes, num_edges, directed=False, weight_range=(1, 1)):
"""
Create a random graph.
@type num_nodes: number
@param num_nodes: Number of nodes.
@type num_edges: number
@param num_edges: Number of edges.
@type directed: bool
@param directed: Whether the ge... |
def run(configobj=None):
"""
TEAL interface for the `acsccd` function.
"""
acsccd(configobj['input'],
exec_path=configobj['exec_path'],
time_stamps=configobj['time_stamps'],
verbose=configobj['verbose'],
quiet=configobj['quiet'] #,
#dqicorr=config... | def function[run, parameter[configobj]]:
constant[
TEAL interface for the `acsccd` function.
]
call[name[acsccd], parameter[call[name[configobj]][constant[input]]]] | keyword[def] identifier[run] ( identifier[configobj] = keyword[None] ):
literal[string]
identifier[acsccd] ( identifier[configobj] [ literal[string] ],
identifier[exec_path] = identifier[configobj] [ literal[string] ],
identifier[time_stamps] = identifier[configobj] [ literal[string] ],
iden... | def run(configobj=None):
"""
TEAL interface for the `acsccd` function.
""" #,
#dqicorr=configobj['dqicorr'],
#atodcorr=configobj['atodcorr'],
#blevcorr=configobj['blevcorr'],
#biascorr=configobj['biascorr']
acsccd(configobj['input'], exec_path=configobj['exec_path'], time_stamps=config... |
def parallel_check(vec1, vec2):
"""Checks whether two vectors are parallel OR anti-parallel.
Vectors must be of the same dimension.
Parameters
----------
vec1
length-R |npfloat_| --
First vector to compare
vec2
length-R |npfloat_| --
Second vector to compare
... | def function[parallel_check, parameter[vec1, vec2]]:
constant[Checks whether two vectors are parallel OR anti-parallel.
Vectors must be of the same dimension.
Parameters
----------
vec1
length-R |npfloat_| --
First vector to compare
vec2
length-R |npfloat_| --
... | keyword[def] identifier[parallel_check] ( identifier[vec1] , identifier[vec2] ):
literal[string]
keyword[from] .. identifier[const] keyword[import] identifier[PRM]
keyword[import] identifier[numpy] keyword[as] identifier[np]
identifier[par] = keyword[False]
keyword[... | def parallel_check(vec1, vec2):
"""Checks whether two vectors are parallel OR anti-parallel.
Vectors must be of the same dimension.
Parameters
----------
vec1
length-R |npfloat_| --
First vector to compare
vec2
length-R |npfloat_| --
Second vector to compare
... |
def disconnect(self, sid, namespace):
"""Register a client disconnect from a namespace."""
if namespace not in self.rooms:
return
rooms = []
for room_name, room in six.iteritems(self.rooms[namespace].copy()):
if sid in room:
rooms.append(room_name)... | def function[disconnect, parameter[self, sid, namespace]]:
constant[Register a client disconnect from a namespace.]
if compare[name[namespace] <ast.NotIn object at 0x7da2590d7190> name[self].rooms] begin[:]
return[None]
variable[rooms] assign[=] list[[]]
for taget[tuple[[<ast.Nam... | keyword[def] identifier[disconnect] ( identifier[self] , identifier[sid] , identifier[namespace] ):
literal[string]
keyword[if] identifier[namespace] keyword[not] keyword[in] identifier[self] . identifier[rooms] :
keyword[return]
identifier[rooms] =[]
keyword[for... | def disconnect(self, sid, namespace):
"""Register a client disconnect from a namespace."""
if namespace not in self.rooms:
return # depends on [control=['if'], data=[]]
rooms = []
for (room_name, room) in six.iteritems(self.rooms[namespace].copy()):
if sid in room:
rooms.app... |
def queue_put_stoppable(self, q, obj):
""" Put obj to queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
q.put(obj, timeout=5)
break
except queue.Full:
pass | def function[queue_put_stoppable, parameter[self, q, obj]]:
constant[ Put obj to queue, but will give up when the thread is stopped]
while <ast.UnaryOp object at 0x7da18f00d510> begin[:]
<ast.Try object at 0x7da18f00c100> | keyword[def] identifier[queue_put_stoppable] ( identifier[self] , identifier[q] , identifier[obj] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[stopped] ():
keyword[try] :
identifier[q] . identifier[put] ( identifier[obj] , identifier[t... | def queue_put_stoppable(self, q, obj):
""" Put obj to queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
q.put(obj, timeout=5)
break # depends on [control=['try'], data=[]]
except queue.Full:
pass # depends on [control=['exc... |
def moment1(self):
"""The first time delay weighted statistical moment of the
instantaneous unit hydrograph."""
delays, response = self.delay_response_series
return statstools.calc_mean_time(delays, response) | def function[moment1, parameter[self]]:
constant[The first time delay weighted statistical moment of the
instantaneous unit hydrograph.]
<ast.Tuple object at 0x7da20e960a90> assign[=] name[self].delay_response_series
return[call[name[statstools].calc_mean_time, parameter[name[delays], name[r... | keyword[def] identifier[moment1] ( identifier[self] ):
literal[string]
identifier[delays] , identifier[response] = identifier[self] . identifier[delay_response_series]
keyword[return] identifier[statstools] . identifier[calc_mean_time] ( identifier[delays] , identifier[response] ) | def moment1(self):
"""The first time delay weighted statistical moment of the
instantaneous unit hydrograph."""
(delays, response) = self.delay_response_series
return statstools.calc_mean_time(delays, response) |
def convert_pad(node, **kwargs):
"""Map MXNet's pad operator attributes to onnx's Pad operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mxnet_pad_width = convert_string_to_list(attrs.get("pad_width"))
onnx_pad_width = transform_padding(mxnet_pad_width... | def function[convert_pad, parameter[node]]:
constant[Map MXNet's pad operator attributes to onnx's Pad operator
and return the created node.
]
<ast.Tuple object at 0x7da20c991510> assign[=] call[name[get_inputs], parameter[name[node], name[kwargs]]]
variable[mxnet_pad_width] assign[=] ca... | keyword[def] identifier[convert_pad] ( identifier[node] ,** identifier[kwargs] ):
literal[string]
identifier[name] , identifier[input_nodes] , identifier[attrs] = identifier[get_inputs] ( identifier[node] , identifier[kwargs] )
identifier[mxnet_pad_width] = identifier[convert_string_to_list] ( identi... | def convert_pad(node, **kwargs):
"""Map MXNet's pad operator attributes to onnx's Pad operator
and return the created node.
"""
(name, input_nodes, attrs) = get_inputs(node, kwargs)
mxnet_pad_width = convert_string_to_list(attrs.get('pad_width'))
onnx_pad_width = transform_padding(mxnet_pad_widt... |
def binary_n(total_N, min_n=50):
"""
Creates a list of values by successively halving the total length total_N
until the resulting value is less than min_n.
Non-integer results are rounded down.
Args:
total_N (int):
total length
Kwargs:
min_n (int):
minimal length after division
Ret... | def function[binary_n, parameter[total_N, min_n]]:
constant[
Creates a list of values by successively halving the total length total_N
until the resulting value is less than min_n.
Non-integer results are rounded down.
Args:
total_N (int):
total length
Kwargs:
min_n (int):
minima... | keyword[def] identifier[binary_n] ( identifier[total_N] , identifier[min_n] = literal[int] ):
literal[string]
identifier[max_exp] = identifier[np] . identifier[log2] ( literal[int] * identifier[total_N] / identifier[min_n] )
identifier[max_exp] = identifier[int] ( identifier[np] . identifier[floor] ( identi... | def binary_n(total_N, min_n=50):
"""
Creates a list of values by successively halving the total length total_N
until the resulting value is less than min_n.
Non-integer results are rounded down.
Args:
total_N (int):
total length
Kwargs:
min_n (int):
minimal length after division
R... |
def move(self, source, dest):
"""Move contents from one path to another relative to the Group.
Parameters
----------
source : string
Name or path to a Zarr object to move.
dest : string
New name or path of the Zarr object.
"""
source = se... | def function[move, parameter[self, source, dest]]:
constant[Move contents from one path to another relative to the Group.
Parameters
----------
source : string
Name or path to a Zarr object to move.
dest : string
New name or path of the Zarr object.
... | keyword[def] identifier[move] ( identifier[self] , identifier[source] , identifier[dest] ):
literal[string]
identifier[source] = identifier[self] . identifier[_item_path] ( identifier[source] )
identifier[dest] = identifier[self] . identifier[_item_path] ( identifier[dest] )
... | def move(self, source, dest):
"""Move contents from one path to another relative to the Group.
Parameters
----------
source : string
Name or path to a Zarr object to move.
dest : string
New name or path of the Zarr object.
"""
source = self._item_... |
def report(self, item_id, report_format="json"):
"""Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_forma... | def function[report, parameter[self, item_id, report_format]]:
constant[Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
... | keyword[def] identifier[report] ( identifier[self] , identifier[item_id] , identifier[report_format] = literal[string] ):
literal[string]
keyword[if] identifier[report_format] == literal[string] :
keyword[return] literal[string]
identifier[response] = identifi... | def report(self, item_id, report_format='json'):
"""Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: R... |
def _to_tuple(self, _list):
""" Recursively converts lists to tuples """
result = list()
for l in _list:
if isinstance(l, list):
result.append(tuple(self._to_tuple(l)))
else:
result.append(l)
return tuple(result) | def function[_to_tuple, parameter[self, _list]]:
constant[ Recursively converts lists to tuples ]
variable[result] assign[=] call[name[list], parameter[]]
for taget[name[l]] in starred[name[_list]] begin[:]
if call[name[isinstance], parameter[name[l], name[list]]] begin[:]
... | keyword[def] identifier[_to_tuple] ( identifier[self] , identifier[_list] ):
literal[string]
identifier[result] = identifier[list] ()
keyword[for] identifier[l] keyword[in] identifier[_list] :
keyword[if] identifier[isinstance] ( identifier[l] , identifier[list] ):
... | def _to_tuple(self, _list):
""" Recursively converts lists to tuples """
result = list()
for l in _list:
if isinstance(l, list):
result.append(tuple(self._to_tuple(l))) # depends on [control=['if'], data=[]]
else:
result.append(l) # depends on [control=['for'], data... |
def provideObjectToInfer(self, inferenceConfig):
"""
Returns the sensations in a canonical format to be sent to an experiment.
The input inferenceConfig should be a dict with the following form:
{
"numSteps": 2 # number of sensations for each column
"pairs": {
0: [(1, 2), (2, 2)] ... | def function[provideObjectToInfer, parameter[self, inferenceConfig]]:
constant[
Returns the sensations in a canonical format to be sent to an experiment.
The input inferenceConfig should be a dict with the following form:
{
"numSteps": 2 # number of sensations for each column
"pairs": ... | keyword[def] identifier[provideObjectToInfer] ( identifier[self] , identifier[inferenceConfig] ):
literal[string]
identifier[numSteps] = identifier[inferenceConfig] . identifier[get] ( literal[string] ,
identifier[len] ( identifier[inferenceConfig] [ literal[string] ][ literal[int] ]))
keyw... | def provideObjectToInfer(self, inferenceConfig):
"""
Returns the sensations in a canonical format to be sent to an experiment.
The input inferenceConfig should be a dict with the following form:
{
"numSteps": 2 # number of sensations for each column
"pairs": {
0: [(1, 2), (2, 2)] ... |
def dafgda(handle, begin, end):
"""
Read the double precision data bounded by two addresses within a DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgda_c.html
:param handle: Handle of a DAF.
:type handle: int
:param begin: Initial address within file.
:type begin: int
... | def function[dafgda, parameter[handle, begin, end]]:
constant[
Read the double precision data bounded by two addresses within a DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgda_c.html
:param handle: Handle of a DAF.
:type handle: int
:param begin: Initial address within ... | keyword[def] identifier[dafgda] ( identifier[handle] , identifier[begin] , identifier[end] ):
literal[string]
identifier[handle] = identifier[ctypes] . identifier[c_int] ( identifier[handle] )
identifier[data] = identifier[stypes] . identifier[emptyDoubleVector] ( identifier[abs] ( identifier[end] - i... | def dafgda(handle, begin, end):
"""
Read the double precision data bounded by two addresses within a DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgda_c.html
:param handle: Handle of a DAF.
:type handle: int
:param begin: Initial address within file.
:type begin: int
... |
def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
if sectors is None:
wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs
else:
try:
wc_keys = [k for s in sectors for k in wcxf.Basis['WET', 'JMS'].sectors[s]]
... | def function[JMS_to_array, parameter[C, sectors]]:
constant[For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays.]
if compare[name[sectors] is constant[None]] begin[:]
variable[wc_keys] assign[=] call[name[wcxf].Basis][tuple[[<ast.Constant object at 0x7da20e9b... | keyword[def] identifier[JMS_to_array] ( identifier[C] , identifier[sectors] = keyword[None] ):
literal[string]
keyword[if] identifier[sectors] keyword[is] keyword[None] :
identifier[wc_keys] = identifier[wcxf] . identifier[Basis] [ literal[string] , literal[string] ]. identifier[all_wcs]
... | def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
if sectors is None:
wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs # depends on [control=['if'], data=[]]
else:
try:
wc_keys = [k for s in sectors for k in wcxf... |
def import_from_dicts(data, samples=None, *args, **kwargs):
"""Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
"""
data = iter(data)
cached_rows, headers = [], []
for in... | def function[import_from_dicts, parameter[data, samples]]:
constant[Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
]
variable[data] assign[=] call[name[iter], parameter[n... | keyword[def] identifier[import_from_dicts] ( identifier[data] , identifier[samples] = keyword[None] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[data] = identifier[iter] ( identifier[data] )
identifier[cached_rows] , identifier[headers] =[],[]
keyword[for] identifie... | def import_from_dicts(data, samples=None, *args, **kwargs):
"""Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
"""
data = iter(data)
(cached_rows, headers) = ([], [])
for ... |
def BooleanTake(input_vertex: vertex_constructor_param_types, index: Collection[int], label: Optional[str]=None) -> Vertex:
"""
A vertex that extracts a scalar at a given index
:param input_vertex: the input vertex to extract from
:param index: the index to extract at
"""
return Boolean(con... | def function[BooleanTake, parameter[input_vertex, index, label]]:
constant[
A vertex that extracts a scalar at a given index
:param input_vertex: the input vertex to extract from
:param index: the index to extract at
]
return[call[name[Boolean], parameter[call[name[context].jvm_view, pa... | keyword[def] identifier[BooleanTake] ( identifier[input_vertex] : identifier[vertex_constructor_param_types] , identifier[index] : identifier[Collection] [ identifier[int] ], identifier[label] : identifier[Optional] [ identifier[str] ]= keyword[None] )-> identifier[Vertex] :
literal[string]
keyword[return]... | def BooleanTake(input_vertex: vertex_constructor_param_types, index: Collection[int], label: Optional[str]=None) -> Vertex:
"""
A vertex that extracts a scalar at a given index
:param input_vertex: the input vertex to extract from
:param index: the index to extract at
"""
return Boolean(con... |
def _index_document(self, document, force=False):
""" Adds parition document to the index. """
from ambry.util import int_maybe
time_coverage = document.pop('time_coverage', [])
from_year = None
to_year = None
if time_coverage:
from_year = int_maybe(time_cover... | def function[_index_document, parameter[self, document, force]]:
constant[ Adds parition document to the index. ]
from relative_module[ambry.util] import module[int_maybe]
variable[time_coverage] assign[=] call[name[document].pop, parameter[constant[time_coverage], list[[]]]]
variable[from_y... | keyword[def] identifier[_index_document] ( identifier[self] , identifier[document] , identifier[force] = keyword[False] ):
literal[string]
keyword[from] identifier[ambry] . identifier[util] keyword[import] identifier[int_maybe]
identifier[time_coverage] = identifier[document] . identif... | def _index_document(self, document, force=False):
""" Adds parition document to the index. """
from ambry.util import int_maybe
time_coverage = document.pop('time_coverage', [])
from_year = None
to_year = None
if time_coverage:
from_year = int_maybe(time_coverage[0])
to_year = in... |
def _parse_dnamasq(filename):
'''
Generic function for parsing dnsmasq files including includes.
'''
fileopts = {}
if not os.path.isfile(filename):
raise CommandExecutionError(
'Error: No such file \'{0}\''.format(filename)
)
with salt.utils.files.fopen(filename, 'r... | def function[_parse_dnamasq, parameter[filename]]:
constant[
Generic function for parsing dnsmasq files including includes.
]
variable[fileopts] assign[=] dictionary[[], []]
if <ast.UnaryOp object at 0x7da1b1f76020> begin[:]
<ast.Raise object at 0x7da1b1f75db0>
with call[... | keyword[def] identifier[_parse_dnamasq] ( identifier[filename] ):
literal[string]
identifier[fileopts] ={}
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[filename] ):
keyword[raise] identifier[CommandExecutionError] (
literal[string] ... | def _parse_dnamasq(filename):
"""
Generic function for parsing dnsmasq files including includes.
"""
fileopts = {}
if not os.path.isfile(filename):
raise CommandExecutionError("Error: No such file '{0}'".format(filename)) # depends on [control=['if'], data=[]]
with salt.utils.files.fope... |
def extract_pixels(X):
""" Extract pixels from array X
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: Reshaped 2D array
:rtype: numpy array, [n_samples*n_pixels_y*n_pixels_x,n_bands]
:raises:... | def function[extract_pixels, parameter[X]]:
constant[ Extract pixels from array X
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: Reshaped 2D array
:rtype: numpy array, [n_samples*n_pixels_y*n_pixels_... | keyword[def] identifier[extract_pixels] ( identifier[X] ):
literal[string]
keyword[if] identifier[len] ( identifier[X] . identifier[shape] )!= literal[int] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
identifier[new_shape] =( ide... | def extract_pixels(X):
""" Extract pixels from array X
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: Reshaped 2D array
:rtype: numpy array, [n_samples*n_pixels_y*n_pixels_x,n_bands]
:raises: Val... |
def tiles_from_geom(self, geometry, zoom):
"""
Return all tiles intersecting with input geometry.
Parameters
----------
geometry : ``shapely.geometry``
zoom : integer
zoom level
Yields
------
intersecting tiles : ``BufferedTile``
... | def function[tiles_from_geom, parameter[self, geometry, zoom]]:
constant[
Return all tiles intersecting with input geometry.
Parameters
----------
geometry : ``shapely.geometry``
zoom : integer
zoom level
Yields
------
intersecting ti... | keyword[def] identifier[tiles_from_geom] ( identifier[self] , identifier[geometry] , identifier[zoom] ):
literal[string]
keyword[for] identifier[tile] keyword[in] identifier[self] . identifier[tile_pyramid] . identifier[tiles_from_geom] ( identifier[geometry] , identifier[zoom] ):
k... | def tiles_from_geom(self, geometry, zoom):
"""
Return all tiles intersecting with input geometry.
Parameters
----------
geometry : ``shapely.geometry``
zoom : integer
zoom level
Yields
------
intersecting tiles : ``BufferedTile``
... |
def _get_expanded_active_specs(specs):
"""
This function removes any unnecessary bundles, apps, libs, and services that aren't needed by
the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed
indirectly by each app
"""
_filter_active(constants.CONFIG_BUND... | def function[_get_expanded_active_specs, parameter[specs]]:
constant[
This function removes any unnecessary bundles, apps, libs, and services that aren't needed by
the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed
indirectly by each app
]
cal... | keyword[def] identifier[_get_expanded_active_specs] ( identifier[specs] ):
literal[string]
identifier[_filter_active] ( identifier[constants] . identifier[CONFIG_BUNDLES_KEY] , identifier[specs] )
identifier[_filter_active] ( literal[string] , identifier[specs] )
identifier[_expand_libs_in_apps] ... | def _get_expanded_active_specs(specs):
"""
This function removes any unnecessary bundles, apps, libs, and services that aren't needed by
the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed
indirectly by each app
"""
_filter_active(constants.CONFIG_BUND... |
def quote_completions(self, completions, cword_prequote, first_colon_pos):
'''
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the beginning of each completion... | def function[quote_completions, parameter[self, completions, cword_prequote, first_colon_pos]]:
constant[
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the b... | keyword[def] identifier[quote_completions] ( identifier[self] , identifier[completions] , identifier[cword_prequote] , identifier[first_colon_pos] ):
literal[string]
identifier[comp_wordbreaks] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] , identifier[os] . identifier[... | def quote_completions(self, completions, cword_prequote, first_colon_pos):
"""
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the beginning of each completion.
... |
def schema_term(self):
"""Return the Table term for this resource, which is referenced either by the `table` property or the
`schema` property"""
if not self.name:
raise MetapackError("Resource for url '{}' doe not have name".format(self.url))
t = self.doc.find_first('Root.... | def function[schema_term, parameter[self]]:
constant[Return the Table term for this resource, which is referenced either by the `table` property or the
`schema` property]
if <ast.UnaryOp object at 0x7da1b196d8a0> begin[:]
<ast.Raise object at 0x7da1b196fd90>
variable[t] assign[=]... | keyword[def] identifier[schema_term] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[name] :
keyword[raise] identifier[MetapackError] ( literal[string] . identifier[format] ( identifier[self] . identifier[url] ))
identifier[t] ... | def schema_term(self):
"""Return the Table term for this resource, which is referenced either by the `table` property or the
`schema` property"""
if not self.name:
raise MetapackError("Resource for url '{}' doe not have name".format(self.url)) # depends on [control=['if'], data=[]]
t = self... |
def process_unknown_arguments(unknowns):
"""Process arguments unknown to the parser"""
result = argparse.Namespace()
result.extra_control = {}
# It would be interesting to use argparse internal
# machinery for this
for unknown in unknowns:
# Check prefixes
prefix = '--parameter-... | def function[process_unknown_arguments, parameter[unknowns]]:
constant[Process arguments unknown to the parser]
variable[result] assign[=] call[name[argparse].Namespace, parameter[]]
name[result].extra_control assign[=] dictionary[[], []]
for taget[name[unknown]] in starred[name[unknowns... | keyword[def] identifier[process_unknown_arguments] ( identifier[unknowns] ):
literal[string]
identifier[result] = identifier[argparse] . identifier[Namespace] ()
identifier[result] . identifier[extra_control] ={}
keyword[for] identifier[unknown] keyword[in] identifier[unknowns] :
... | def process_unknown_arguments(unknowns):
"""Process arguments unknown to the parser"""
result = argparse.Namespace()
result.extra_control = {}
# It would be interesting to use argparse internal
# machinery for this
for unknown in unknowns:
# Check prefixes
prefix = '--parameter-'... |
def detect(self, text):
"""Decide which language is used to write the text.
The method tries first to detect the language with high reliability. If
that is not possible, the method switches to best effort strategy.
Args:
text (string): A snippet of text, the longer it is the more reliable we
... | def function[detect, parameter[self, text]]:
constant[Decide which language is used to write the text.
The method tries first to detect the language with high reliability. If
that is not possible, the method switches to best effort strategy.
Args:
text (string): A snippet of text, the longe... | keyword[def] identifier[detect] ( identifier[self] , identifier[text] ):
literal[string]
identifier[t] = identifier[text] . identifier[encode] ( literal[string] )
identifier[reliable] , identifier[index] , identifier[top_3_choices] = identifier[cld2] . identifier[detect] ( identifier[t] , identifier[b... | def detect(self, text):
"""Decide which language is used to write the text.
The method tries first to detect the language with high reliability. If
that is not possible, the method switches to best effort strategy.
Args:
text (string): A snippet of text, the longer it is the more reliable we
... |
def message_options(self):
"""
Convert config namespace to emails.Message namespace
"""
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key]
return o | def function[message_options, parameter[self]]:
constant[
Convert config namespace to emails.Message namespace
]
variable[o] assign[=] dictionary[[], []]
variable[options] assign[=] name[self].options
for taget[name[key]] in starred[name[self]._default_message_options] be... | keyword[def] identifier[message_options] ( identifier[self] ):
literal[string]
identifier[o] ={}
identifier[options] = identifier[self] . identifier[options]
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[_default_message_options] :
keyword... | def message_options(self):
"""
Convert config namespace to emails.Message namespace
"""
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key] # depends on [control=['if'], data=['key', 'options']] # depends ... |
def get_all_response_headers(self):
''' Gets back all response headers. '''
bstr_headers = c_void_p()
_WinHttpRequest._GetAllResponseHeaders(self, byref(bstr_headers))
bstr_headers = ctypes.cast(bstr_headers, c_wchar_p)
headers = bstr_headers.value
_SysFreeString(bstr_he... | def function[get_all_response_headers, parameter[self]]:
constant[ Gets back all response headers. ]
variable[bstr_headers] assign[=] call[name[c_void_p], parameter[]]
call[name[_WinHttpRequest]._GetAllResponseHeaders, parameter[name[self], call[name[byref], parameter[name[bstr_headers]]]]]
... | keyword[def] identifier[get_all_response_headers] ( identifier[self] ):
literal[string]
identifier[bstr_headers] = identifier[c_void_p] ()
identifier[_WinHttpRequest] . identifier[_GetAllResponseHeaders] ( identifier[self] , identifier[byref] ( identifier[bstr_headers] ))
identif... | def get_all_response_headers(self):
""" Gets back all response headers. """
bstr_headers = c_void_p()
_WinHttpRequest._GetAllResponseHeaders(self, byref(bstr_headers))
bstr_headers = ctypes.cast(bstr_headers, c_wchar_p)
headers = bstr_headers.value
_SysFreeString(bstr_headers)
return headers |
def prt_gene_aart_details(self, geneids, prt=sys.stdout):
"""For each gene, print ASCII art which represents its associated GO IDs."""
_go2nt = self.sortobj.grprobj.go2nt
patgene = self.datobj.kws["fmtgene2"]
patgo = self.datobj.kws["fmtgo2"]
itemid2name = self.datobj.kws.get("it... | def function[prt_gene_aart_details, parameter[self, geneids, prt]]:
constant[For each gene, print ASCII art which represents its associated GO IDs.]
variable[_go2nt] assign[=] name[self].sortobj.grprobj.go2nt
variable[patgene] assign[=] call[name[self].datobj.kws][constant[fmtgene2]]
var... | keyword[def] identifier[prt_gene_aart_details] ( identifier[self] , identifier[geneids] , identifier[prt] = identifier[sys] . identifier[stdout] ):
literal[string]
identifier[_go2nt] = identifier[self] . identifier[sortobj] . identifier[grprobj] . identifier[go2nt]
identifier[patgene] = i... | def prt_gene_aart_details(self, geneids, prt=sys.stdout):
"""For each gene, print ASCII art which represents its associated GO IDs."""
_go2nt = self.sortobj.grprobj.go2nt
patgene = self.datobj.kws['fmtgene2']
patgo = self.datobj.kws['fmtgo2']
itemid2name = self.datobj.kws.get('itemid2name')
chr2... |
def init_proxy(self, config):
"""Initialize and start proxy mode. If proxy configuration entry is not contained in the config
this is a no op. Causes handler to become an instance of WSGIProxMiddleware.
:param dict config: The configuration object used to configure this instance of FrontEndApp
... | def function[init_proxy, parameter[self, config]]:
constant[Initialize and start proxy mode. If proxy configuration entry is not contained in the config
this is a no op. Causes handler to become an instance of WSGIProxMiddleware.
:param dict config: The configuration object used to configure th... | keyword[def] identifier[init_proxy] ( identifier[self] , identifier[config] ):
literal[string]
identifier[proxy_config] = identifier[config] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[proxy_config] :
keyword[return]
keyword[if] iden... | def init_proxy(self, config):
"""Initialize and start proxy mode. If proxy configuration entry is not contained in the config
this is a no op. Causes handler to become an instance of WSGIProxMiddleware.
:param dict config: The configuration object used to configure this instance of FrontEndApp
... |
def search(self, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \
br_coord = (None, None), name = None, country = None, locality = None, \
region = None, postal_code = None, street_address = None,\
website_url = ... | def function[search, parameter[self, category, cuisine, location, radius, tl_coord, br_coord, name, country, locality, region, postal_code, street_address, website_url, has_menu, open_at]]:
constant[
Locu Venue Search API Call Wrapper
Args:
*Note that none of the arguments are... | keyword[def] identifier[search] ( identifier[self] , identifier[category] = keyword[None] , identifier[cuisine] = keyword[None] , identifier[location] =( keyword[None] , keyword[None] ), identifier[radius] = keyword[None] , identifier[tl_coord] =( keyword[None] , keyword[None] ), identifier[br_coord] =( keyword[None]... | def search(self, category=None, cuisine=None, location=(None, None), radius=None, tl_coord=(None, None), br_coord=(None, None), name=None, country=None, locality=None, region=None, postal_code=None, street_address=None, website_url=None, has_menu=None, open_at=None):
"""
Locu Venue Search API Call Wrapper
... |
def describe_arguments(func):
"""
Analyze a function's signature and return a data structure suitable for
passing in as arguments to an argparse parser's add_argument() method."""
argspec = inspect.getargspec(func)
# we should probably raise an exception somewhere if func includes **kwargs
if a... | def function[describe_arguments, parameter[func]]:
constant[
Analyze a function's signature and return a data structure suitable for
passing in as arguments to an argparse parser's add_argument() method.]
variable[argspec] assign[=] call[name[inspect].getargspec, parameter[name[func]]]
i... | keyword[def] identifier[describe_arguments] ( identifier[func] ):
literal[string]
identifier[argspec] = identifier[inspect] . identifier[getargspec] ( identifier[func] )
keyword[if] identifier[argspec] . identifier[defaults] :
identifier[positional_args] = identifier[argspec] . identif... | def describe_arguments(func):
"""
Analyze a function's signature and return a data structure suitable for
passing in as arguments to an argparse parser's add_argument() method."""
argspec = inspect.getargspec(func)
# we should probably raise an exception somewhere if func includes **kwargs
if ar... |
def on_site(self):
"""
Return entries published on current site.
"""
return super(EntryPublishedManager, self).get_queryset().filter(
sites=Site.objects.get_current()) | def function[on_site, parameter[self]]:
constant[
Return entries published on current site.
]
return[call[call[call[name[super], parameter[name[EntryPublishedManager], name[self]]].get_queryset, parameter[]].filter, parameter[]]] | keyword[def] identifier[on_site] ( identifier[self] ):
literal[string]
keyword[return] identifier[super] ( identifier[EntryPublishedManager] , identifier[self] ). identifier[get_queryset] (). identifier[filter] (
identifier[sites] = identifier[Site] . identifier[objects] . identifier[get_... | def on_site(self):
"""
Return entries published on current site.
"""
return super(EntryPublishedManager, self).get_queryset().filter(sites=Site.objects.get_current()) |
def get_top_segmentations(table, n):
"""
Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned
"""
stroke_count = list(range(... | def function[get_top_segmentations, parameter[table, n]]:
constant[
Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned
]
... | keyword[def] identifier[get_top_segmentations] ( identifier[table] , identifier[n] ):
literal[string]
identifier[stroke_count] = identifier[list] ( identifier[range] ( identifier[len] ( identifier[table] )))
identifier[topf] = identifier[TopFinder] ( identifier[n] )
keyword[for] identifier[curr_... | def get_top_segmentations(table, n):
"""
Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned
"""
stroke_count = list(range(... |
def start(self, *args, **kw):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pidfile = file(self.pidfile, 'r')
pid = int(pidfile.read().strip())
pidfile.close()
except IOError:
pid = No... | def function[start, parameter[self]]:
constant[
Start the daemon
]
<ast.Try object at 0x7da18f58ff70>
if name[pid] begin[:]
variable[message] assign[=] constant[pidfile %s already exist. Daemon already running?
]
call[name[sys].stderr.write, parameter[... | keyword[def] identifier[start] ( identifier[self] ,* identifier[args] ,** identifier[kw] ):
literal[string]
keyword[try] :
identifier[pidfile] = identifier[file] ( identifier[self] . identifier[pidfile] , literal[string] )
identifier[pid] = identifier[int] ( ident... | def start(self, *args, **kw):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pidfile = file(self.pidfile, 'r')
pid = int(pidfile.read().strip())
pidfile.close() # depends on [control=['try'], data=[]]
except IOError:
... |
def download_file(filename, session):
""" Downloads a file """
print('Downloading file %s' % filename)
infilesource = os.path.join('sftp://' + ADDRESS + WORKING_DIR,
filename)
infiletarget = os.path.join(os.getcwd(), filename)
incoming = saga.filesystem.File(infileso... | def function[download_file, parameter[filename, session]]:
constant[ Downloads a file ]
call[name[print], parameter[binary_operation[constant[Downloading file %s] <ast.Mod object at 0x7da2590d6920> name[filename]]]]
variable[infilesource] assign[=] call[name[os].path.join, parameter[binary_opera... | keyword[def] identifier[download_file] ( identifier[filename] , identifier[session] ):
literal[string]
identifier[print] ( literal[string] % identifier[filename] )
identifier[infilesource] = identifier[os] . identifier[path] . identifier[join] ( literal[string] + identifier[ADDRESS] + identifier[WORKI... | def download_file(filename, session):
""" Downloads a file """
print('Downloading file %s' % filename)
infilesource = os.path.join('sftp://' + ADDRESS + WORKING_DIR, filename)
infiletarget = os.path.join(os.getcwd(), filename)
incoming = saga.filesystem.File(infilesource, session=session, flags=OVER... |
def _setup_catalog(portal, catalog_id, catalog_definition):
"""
Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
... | def function[_setup_catalog, parameter[portal, catalog_id, catalog_definition]]:
constant[
Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dic... | keyword[def] identifier[_setup_catalog] ( identifier[portal] , identifier[catalog_id] , identifier[catalog_definition] ):
literal[string]
identifier[reindex] = keyword[False]
identifier[catalog] = identifier[getToolByName] ( identifier[portal] , identifier[catalog_id] , keyword[None] )
keyword[... | def _setup_catalog(portal, catalog_id, catalog_definition):
"""
Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
... |
def validate(self, nonce):
"""Does the nonce exist and is it valid for the request?"""
if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr)
try:
opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable
if expiretime < time.time():
... | def function[validate, parameter[self, nonce]]:
constant[Does the nonce exist and is it valid for the request?]
if name[self].debug begin[:]
call[name[print], parameter[binary_operation[constant[Checking nonce ] + call[name[str], parameter[name[nonce]]]]]]
<ast.Try object at 0x7da18c... | keyword[def] identifier[validate] ( identifier[self] , identifier[nonce] ):
literal[string]
keyword[if] identifier[self] . identifier[debug] : identifier[print] ( literal[string] + identifier[str] ( identifier[nonce] ), identifier[file] = identifier[sys] . identifier[stderr] )
keyword[try... | def validate(self, nonce):
"""Does the nonce exist and is it valid for the request?"""
if self.debug:
print('Checking nonce ' + str(nonce), file=sys.stderr) # depends on [control=['if'], data=[]]
try:
(opaque, ip, expiretime) = self.get(nonce) #pylint: disable=unused-variable
if ex... |
def _From(self, t):
""" Handle "from xyz import foo, bar as baz".
"""
# fixme: Are From and ImportFrom handled differently?
self._fill("from ")
self._write(t.modname)
self._write(" import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
... | def function[_From, parameter[self, t]]:
constant[ Handle "from xyz import foo, bar as baz".
]
call[name[self]._fill, parameter[constant[from ]]]
call[name[self]._write, parameter[name[t].modname]]
call[name[self]._write, parameter[constant[ import ]]]
for taget[tuple[[<a... | keyword[def] identifier[_From] ( identifier[self] , identifier[t] ):
literal[string]
identifier[self] . identifier[_fill] ( literal[string] )
identifier[self] . identifier[_write] ( identifier[t] . identifier[modname] )
identifier[self] . identifier[_write] ( literal[stri... | def _From(self, t):
""" Handle "from xyz import foo, bar as baz".
"""
# fixme: Are From and ImportFrom handled differently?
self._fill('from ')
self._write(t.modname)
self._write(' import ')
for (i, (name, asname)) in enumerate(t.names):
if i != 0:
self._write(', ') ... |
def make(game, state=State.DEFAULT, inttype=retro.data.Integrations.DEFAULT, **kwargs):
"""
Create a Gym environment for the specified game
"""
try:
retro.data.get_romfile_path(game, inttype)
except FileNotFoundError:
if not retro.data.get_file_path(game, "rom.sha", inttype):
... | def function[make, parameter[game, state, inttype]]:
constant[
Create a Gym environment for the specified game
]
<ast.Try object at 0x7da18c4cd6f0>
return[call[name[RetroEnv], parameter[name[game], name[state]]]] | keyword[def] identifier[make] ( identifier[game] , identifier[state] = identifier[State] . identifier[DEFAULT] , identifier[inttype] = identifier[retro] . identifier[data] . identifier[Integrations] . identifier[DEFAULT] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[retro] . ... | def make(game, state=State.DEFAULT, inttype=retro.data.Integrations.DEFAULT, **kwargs):
"""
Create a Gym environment for the specified game
"""
try:
retro.data.get_romfile_path(game, inttype) # depends on [control=['try'], data=[]]
except FileNotFoundError:
if not retro.data.get_fil... |
async def post_data(self, path, data=None, headers=None, timeout=None):
"""Perform a POST request."""
url = self.base_url + path
_LOGGER.debug('POST URL: %s', url)
self._log_data(data, False)
resp = None
try:
resp = await self._session.post(
u... | <ast.AsyncFunctionDef object at 0x7da18f720dc0> | keyword[async] keyword[def] identifier[post_data] ( identifier[self] , identifier[path] , identifier[data] = keyword[None] , identifier[headers] = keyword[None] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[url] = identifier[self] . identifier[base_url] + identifier[path]
... | async def post_data(self, path, data=None, headers=None, timeout=None):
"""Perform a POST request."""
url = self.base_url + path
_LOGGER.debug('POST URL: %s', url)
self._log_data(data, False)
resp = None
try:
resp = await self._session.post(url, headers=headers, data=data, timeout=DEFAUL... |
def search_point(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None):
''' Perform a catalog search over a specific point, specified by lat,lng
Args:
lat: latitude
lng: longitude
filters: Array of filters. Optional. Example:
... | def function[search_point, parameter[self, lat, lng, filters, startDate, endDate, types, type]]:
constant[ Perform a catalog search over a specific point, specified by lat,lng
Args:
lat: latitude
lng: longitude
filters: Array of filters. Optional. Example:
... | keyword[def] identifier[search_point] ( identifier[self] , identifier[lat] , identifier[lng] , identifier[filters] = keyword[None] , identifier[startDate] = keyword[None] , identifier[endDate] = keyword[None] , identifier[types] = keyword[None] , identifier[type] = keyword[None] ):
literal[string]
... | def search_point(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None):
""" Perform a catalog search over a specific point, specified by lat,lng
Args:
lat: latitude
lng: longitude
filters: Array of filters. Optional. Example:
[
... |
def _raw_sentences(paracrawl_file):
"""Generates Unicode strings, one for each <seg> in a ParaCrawl data file.
Also decodes some of the most common HTML entities found in ParaCrawl data.
Args:
paracrawl_file: A ParaCrawl V3.0 en-.. data file.
Yields:
One Unicode string for each <seg> element in the Pa... | def function[_raw_sentences, parameter[paracrawl_file]]:
constant[Generates Unicode strings, one for each <seg> in a ParaCrawl data file.
Also decodes some of the most common HTML entities found in ParaCrawl data.
Args:
paracrawl_file: A ParaCrawl V3.0 en-.. data file.
Yields:
One Unicode string... | keyword[def] identifier[_raw_sentences] ( identifier[paracrawl_file] ):
literal[string]
keyword[for] identifier[line_utf8] keyword[in] identifier[paracrawl_file] :
identifier[line_uni] = identifier[line_utf8] . identifier[decode] ( literal[string] )
identifier[text_match] = identifier[re] . identi... | def _raw_sentences(paracrawl_file):
"""Generates Unicode strings, one for each <seg> in a ParaCrawl data file.
Also decodes some of the most common HTML entities found in ParaCrawl data.
Args:
paracrawl_file: A ParaCrawl V3.0 en-.. data file.
Yields:
One Unicode string for each <seg> element in the ... |
def add(self, files, items):
"""
Add a list of files with a reference to a list of objects.
"""
if isinstance(files, (str, bytes)):
files = iter([files])
for pathname in files:
try:
values = self._filemap[pathname]
except KeyErr... | def function[add, parameter[self, files, items]]:
constant[
Add a list of files with a reference to a list of objects.
]
if call[name[isinstance], parameter[name[files], tuple[[<ast.Name object at 0x7da18eb55870>, <ast.Name object at 0x7da18eb57760>]]]] begin[:]
variable[... | keyword[def] identifier[add] ( identifier[self] , identifier[files] , identifier[items] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[files] ,( identifier[str] , identifier[bytes] )):
identifier[files] = identifier[iter] ([ identifier[files] ])
keyword[fo... | def add(self, files, items):
"""
Add a list of files with a reference to a list of objects.
"""
if isinstance(files, (str, bytes)):
files = iter([files]) # depends on [control=['if'], data=[]]
for pathname in files:
try:
values = self._filemap[pathname] # depend... |
def scatter_drag(
x_points: 'Array',
y_points: 'Array',
*,
fig=None,
show_eqn=True,
options={}
):
"""
Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
... | def function[scatter_drag, parameter[x_points, y_points]]:
constant[
Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
x_points (Array Number): x-values of points to p... | keyword[def] identifier[scatter_drag] (
identifier[x_points] : literal[string] ,
identifier[y_points] : literal[string] ,
*,
identifier[fig] = keyword[None] ,
identifier[show_eqn] = keyword[True] ,
identifier[options] ={}
):
literal[string]
identifier[params] ={
literal[string] :[{
literal[s... | def scatter_drag(x_points: 'Array', y_points: 'Array', *, fig=None, show_eqn=True, options={}):
"""
Generates an interactive scatter plot with the best fit line plotted over
the points. The points can be dragged by the user and the line will
automatically update.
Args:
x_points (Array Numbe... |
def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manager_decorator(*args, **kwargs):
with transaction.manager:
return fn(*args, **kwargs)
return transaction_manager_decorator | def function[transaction_manager, parameter[fn]]:
constant[
Decorator which wraps whole function into ``with transaction.manager:``.
]
def function[transaction_manager_decorator, parameter[]]:
with name[transaction].manager begin[:]
return[call[name[fn], parameter[<as... | keyword[def] identifier[transaction_manager] ( identifier[fn] ):
literal[string]
@ identifier[wraps] ( identifier[fn] )
keyword[def] identifier[transaction_manager_decorator] (* identifier[args] ,** identifier[kwargs] ):
keyword[with] identifier[transaction] . identifier[manager] :
... | def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manager_decorator(*args, **kwargs):
with transaction.manager:
return fn(*args, **kwargs) # depends on [control=['with'], data=[]]
return ... |
def deal_list_query(self, code="", trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
"""for querying deal list"""
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if r... | def function[deal_list_query, parameter[self, code, trd_env, acc_id, acc_index]]:
constant[for querying deal list]
<ast.Tuple object at 0x7da20c991bd0> assign[=] call[name[self]._check_trd_env, parameter[name[trd_env]]]
if compare[name[ret] not_equal[!=] name[RET_OK]] begin[:]
return[tup... | keyword[def] identifier[deal_list_query] ( identifier[self] , identifier[code] = literal[string] , identifier[trd_env] = identifier[TrdEnv] . identifier[REAL] , identifier[acc_id] = literal[int] , identifier[acc_index] = literal[int] ):
literal[string]
identifier[ret] , identifier[msg] = identifier... | def deal_list_query(self, code='', trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
"""for querying deal list"""
(ret, msg) = self._check_trd_env(trd_env)
if ret != RET_OK:
return (ret, msg) # depends on [control=['if'], data=['ret']]
(ret, msg, acc_id) = self._check_acc_id_and_acc_index(trd_env, a... |
def density(self):
"""
The percent of non- ``fill_value`` points, as decimal.
Examples
--------
>>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0)
>>> s.density
0.6
"""
r = float(self.sp_index.npoints) / float(self.sp_index.length)
return ... | def function[density, parameter[self]]:
constant[
The percent of non- ``fill_value`` points, as decimal.
Examples
--------
>>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0)
>>> s.density
0.6
]
variable[r] assign[=] binary_operation[call[name[floa... | keyword[def] identifier[density] ( identifier[self] ):
literal[string]
identifier[r] = identifier[float] ( identifier[self] . identifier[sp_index] . identifier[npoints] )/ identifier[float] ( identifier[self] . identifier[sp_index] . identifier[length] )
keyword[return] identifier[r] | def density(self):
"""
The percent of non- ``fill_value`` points, as decimal.
Examples
--------
>>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0)
>>> s.density
0.6
"""
r = float(self.sp_index.npoints) / float(self.sp_index.length)
return r |
def find_natural_neighbors(tri, grid_points):
r"""Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is within the circumradius of the ... | def function[find_natural_neighbors, parameter[tri, grid_points]]:
constant[Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is w... | keyword[def] identifier[find_natural_neighbors] ( identifier[tri] , identifier[grid_points] ):
literal[string]
identifier[tree] = identifier[cKDTree] ( identifier[grid_points] )
identifier[in_triangulation] = identifier[tri] . identifier[find_simplex] ( identifier[tree] . identifier[data] )>= literal... | def find_natural_neighbors(tri, grid_points):
"""Return the natural neighbor triangles for each given grid cell.
These are determined by the properties of the given delaunay triangulation.
A triangle is a natural neighbor of a grid cell if that triangles circumcenter
is within the circumradius of the g... |
def create_user(self, username, password):
"""
Creates a user in the CouchDB instance with the username `username` and
password `password`
"""
user_id = "org.couchdb.user:" + username
res = self["_users"].resource.put(
user_id, body=json.dumps({
... | def function[create_user, parameter[self, username, password]]:
constant[
Creates a user in the CouchDB instance with the username `username` and
password `password`
]
variable[user_id] assign[=] binary_operation[constant[org.couchdb.user:] + name[username]]
variable[res]... | keyword[def] identifier[create_user] ( identifier[self] , identifier[username] , identifier[password] ):
literal[string]
identifier[user_id] = literal[string] + identifier[username]
identifier[res] = identifier[self] [ literal[string] ]. identifier[resource] . identifier[put] (
i... | def create_user(self, username, password):
"""
Creates a user in the CouchDB instance with the username `username` and
password `password`
"""
user_id = 'org.couchdb.user:' + username
res = self['_users'].resource.put(user_id, body=json.dumps({'_id': user_id, 'name': username, 'roles... |
def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo]
except KeyError as ex:
raise InvalidTodoException from ex | def function[uid, parameter[self, p_todo]]:
constant[
Returns the unique text-based ID for a todo item.
]
<ast.Try object at 0x7da20c6e4a90> | keyword[def] identifier[uid] ( identifier[self] , identifier[p_todo] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_todo_id_map] [ identifier[p_todo] ]
keyword[except] identifier[KeyError] keyword[as] identifier[ex] :
keyword[... | def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo] # depends on [control=['try'], data=[]]
except KeyError as ex:
raise InvalidTodoException from ex # depends on [control=['except'], data=['ex']] |
def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | def function[_bg_combine, parameter[self, bgs]]:
constant[Combine several background amplitude images]
variable[out] assign[=] call[name[np].ones, parameter[call[name[self].h5][constant[raw]].shape]]
for taget[name[bg]] in starred[name[bgs]] begin[:]
<ast.AugAssign object at 0x7da1b10457... | keyword[def] identifier[_bg_combine] ( identifier[self] , identifier[bgs] ):
literal[string]
identifier[out] = identifier[np] . identifier[ones] ( identifier[self] . identifier[h5] [ literal[string] ]. identifier[shape] , identifier[dtype] = identifier[float] )
keyword[for] ident... | def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5['raw'].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:] # depends on [control=['for'], data=['bg']]
return out |
def filter(self, model=None, context=None):
"""
Perform filtering on the model. Will change model in place.
:param model: object or dict
:param context: object, dict or None
:return: None
"""
if model is None:
return
# properties
self.... | def function[filter, parameter[self, model, context]]:
constant[
Perform filtering on the model. Will change model in place.
:param model: object or dict
:param context: object, dict or None
:return: None
]
if compare[name[model] is constant[None]] begin[:]
... | keyword[def] identifier[filter] ( identifier[self] , identifier[model] = keyword[None] , identifier[context] = keyword[None] ):
literal[string]
keyword[if] identifier[model] keyword[is] keyword[None] :
keyword[return]
identifier[self] . identifier[filter_prop... | def filter(self, model=None, context=None):
"""
Perform filtering on the model. Will change model in place.
:param model: object or dict
:param context: object, dict or None
:return: None
"""
if model is None:
return # depends on [control=['if'], data=[]]
# p... |
def cleanup(self):
"""Clean up, making sure the process is stopped before we pack up and go home."""
if self.process is None: # Process wasn't running yet, so nothing to worry about
return
if self.process.poll() is None:
log.info("Sending TERM to %d", self.process.pid)
... | def function[cleanup, parameter[self]]:
constant[Clean up, making sure the process is stopped before we pack up and go home.]
if compare[name[self].process is constant[None]] begin[:]
return[None]
if compare[call[name[self].process.poll, parameter[]] is constant[None]] begin[:]
... | keyword[def] identifier[cleanup] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[process] keyword[is] keyword[None] :
keyword[return]
keyword[if] identifier[self] . identifier[process] . identifier[poll] () keyword[is] keyword[None] :
... | def cleanup(self):
"""Clean up, making sure the process is stopped before we pack up and go home."""
if self.process is None: # Process wasn't running yet, so nothing to worry about
return # depends on [control=['if'], data=[]]
if self.process.poll() is None:
log.info('Sending TERM to %d',... |
def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
"""
reads in columns of multiple alignment and returns them iteratively
"""
if l is None:
l = _getMultiFastaOffsets(fasta)
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seqNo):
j = open(fasta, 'r')
... | def function[fastaAlignmentRead, parameter[fasta, mapFn, l]]:
constant[
reads in columns of multiple alignment and returns them iteratively
]
if compare[name[l] is constant[None]] begin[:]
variable[l] assign[=] call[name[_getMultiFastaOffsets], parameter[name[fasta]]]
var... | keyword[def] identifier[fastaAlignmentRead] ( identifier[fasta] , identifier[mapFn] =( keyword[lambda] identifier[x] : identifier[x] ), identifier[l] = keyword[None] ):
literal[string]
keyword[if] identifier[l] keyword[is] keyword[None] :
identifier[l] = identifier[_getMultiFastaOffsets] ( ide... | def fastaAlignmentRead(fasta, mapFn=lambda x: x, l=None):
"""
reads in columns of multiple alignment and returns them iteratively
"""
if l is None:
l = _getMultiFastaOffsets(fasta) # depends on [control=['if'], data=['l']]
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seq... |
def get_facets(self):
'''
Returns a dictionary of facets::
>>> res = solr.query('SolrClient_unittest',{
'q':'product_name:Lorem',
'facet':True,
'facet.field':'facet_test',
})... ... ... ...
>>> res.get_resul... | def function[get_facets, parameter[self]]:
constant[
Returns a dictionary of facets::
>>> res = solr.query('SolrClient_unittest',{
'q':'product_name:Lorem',
'facet':True,
'facet.field':'facet_test',
})... ... ... ...
... | keyword[def] identifier[get_facets] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[facets] ={}
identifier[data] = identifier[self] . identifier[data]
k... | def get_facets(self):
"""
Returns a dictionary of facets::
>>> res = solr.query('SolrClient_unittest',{
'q':'product_name:Lorem',
'facet':True,
'facet.field':'facet_test',
})... ... ... ...
>>> res.get_results_c... |
def terminate_bits(self, payload):
"""This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
"""
data_capacity = tables.data_capacity[self.version][self.error][0]
... | def function[terminate_bits, parameter[self, payload]]:
constant[This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
]
variable[data_capacity] assign[=] call[call[call... | keyword[def] identifier[terminate_bits] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[data_capacity] = identifier[tables] . identifier[data_capacity] [ identifier[self] . identifier[version] ][ identifier[self] . identifier[error] ][ literal[int] ]
keyword[if] id... | def terminate_bits(self, payload):
"""This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
"""
data_capacity = tables.data_capacity[self.version][self.error][0]
if len(payl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.