code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def corrections(self, word, prefix=1, distance=2):
"""Get corrections for word, if word is an invalid word.
:prefix: is the number of characters the prefix of the word must
have in common with the suggested corrections.
:distance: is the character distance the corrections may have betw... | def function[corrections, parameter[self, word, prefix, distance]]:
constant[Get corrections for word, if word is an invalid word.
:prefix: is the number of characters the prefix of the word must
have in common with the suggested corrections.
:distance: is the character distance the co... | keyword[def] identifier[corrections] ( identifier[self] , identifier[word] , identifier[prefix] = literal[int] , identifier[distance] = literal[int] ):
literal[string]
keyword[if] identifier[word] keyword[not] keyword[in] identifier[self] . identifier[_words] :
keyword[return] ide... | def corrections(self, word, prefix=1, distance=2):
"""Get corrections for word, if word is an invalid word.
:prefix: is the number of characters the prefix of the word must
have in common with the suggested corrections.
:distance: is the character distance the corrections may have between
... |
def request_and_check(self, url, method='get',
expected_content_type=None, **kwargs):
"""Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
... | def function[request_and_check, parameter[self, url, method, expected_content_type]]:
constant[Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_co... | keyword[def] identifier[request_and_check] ( identifier[self] , identifier[url] , identifier[method] = literal[string] ,
identifier[expected_content_type] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[method] keyword[in] [ literal[string] , literal[string] ... | def request_and_check(self, url, method='get', expected_content_type=None, **kwargs):
"""Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_content_type... |
def to_device(self, device, non_blocking=True):
""" Move a rollout to a selected device """
return Transitions(
size=self.size,
environment_information=self.environment_information,
transition_tensors={k: v.to(device, non_blocking=non_blocking) for k, v in self.transi... | def function[to_device, parameter[self, device, non_blocking]]:
constant[ Move a rollout to a selected device ]
return[call[name[Transitions], parameter[]]] | keyword[def] identifier[to_device] ( identifier[self] , identifier[device] , identifier[non_blocking] = keyword[True] ):
literal[string]
keyword[return] identifier[Transitions] (
identifier[size] = identifier[self] . identifier[size] ,
identifier[environment_information] = identi... | def to_device(self, device, non_blocking=True):
""" Move a rollout to a selected device """
return Transitions(size=self.size, environment_information=self.environment_information, transition_tensors={k: v.to(device, non_blocking=non_blocking) for (k, v) in self.transition_tensors.items()}, extra_data=self.extr... |
def _(obj):
"""ISO 8601 format. Interprets naive datetime as UTC with zulu suffix."""
tz_offset = obj.utcoffset()
if not tz_offset or tz_offset == UTC_ZERO:
iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
else:
iso_datetime = obj.isoformat()
return iso_datetime | def function[_, parameter[obj]]:
constant[ISO 8601 format. Interprets naive datetime as UTC with zulu suffix.]
variable[tz_offset] assign[=] call[name[obj].utcoffset, parameter[]]
if <ast.BoolOp object at 0x7da18c4cc040> begin[:]
variable[iso_datetime] assign[=] call[name[obj].st... | keyword[def] identifier[_] ( identifier[obj] ):
literal[string]
identifier[tz_offset] = identifier[obj] . identifier[utcoffset] ()
keyword[if] keyword[not] identifier[tz_offset] keyword[or] identifier[tz_offset] == identifier[UTC_ZERO] :
identifier[iso_datetime] = identifier[obj] . iden... | def _(obj):
"""ISO 8601 format. Interprets naive datetime as UTC with zulu suffix."""
tz_offset = obj.utcoffset()
if not tz_offset or tz_offset == UTC_ZERO:
iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # depends on [control=['if'], data=[]]
else:
iso_datetime = obj.isoformat()
... |
def metric(self):
"""
Compute a matrix of Hilbert-Schmidt inner products for the basis operators, update
self._metric, and return the value.
:return: The matrix of inner products.
:rtype: numpy.matrix
"""
if self._metric is None:
_log.debug("Computing... | def function[metric, parameter[self]]:
constant[
Compute a matrix of Hilbert-Schmidt inner products for the basis operators, update
self._metric, and return the value.
:return: The matrix of inner products.
:rtype: numpy.matrix
]
if compare[name[self]._metric is ... | keyword[def] identifier[metric] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_metric] keyword[is] keyword[None] :
identifier[_log] . identifier[debug] ( literal[string] )
identifier[self] . identifier[_metric] = identifier[np] . identi... | def metric(self):
"""
Compute a matrix of Hilbert-Schmidt inner products for the basis operators, update
self._metric, and return the value.
:return: The matrix of inner products.
:rtype: numpy.matrix
"""
if self._metric is None:
_log.debug('Computing and caching... |
def run_example(example_name, environ):
"""
Run an example module from zipline.examples.
"""
mod = EXAMPLE_MODULES[example_name]
register_calendar("YAHOO", get_calendar("NYSE"), force=True)
return run_algorithm(
initialize=getattr(mod, 'initialize', None),
handle_data=getattr(m... | def function[run_example, parameter[example_name, environ]]:
constant[
Run an example module from zipline.examples.
]
variable[mod] assign[=] call[name[EXAMPLE_MODULES]][name[example_name]]
call[name[register_calendar], parameter[constant[YAHOO], call[name[get_calendar], parameter[consta... | keyword[def] identifier[run_example] ( identifier[example_name] , identifier[environ] ):
literal[string]
identifier[mod] = identifier[EXAMPLE_MODULES] [ identifier[example_name] ]
identifier[register_calendar] ( literal[string] , identifier[get_calendar] ( literal[string] ), identifier[force] = keywo... | def run_example(example_name, environ):
"""
Run an example module from zipline.examples.
"""
mod = EXAMPLE_MODULES[example_name]
register_calendar('YAHOO', get_calendar('NYSE'), force=True)
# Provide a default capital base, but allow the test to override.
return run_algorithm(initialize=geta... |
def i2c_read(self, address, register, number_of_bytes, read_type, cb=None):
"""
This method requests the read of an i2c device. Results are retrieved by a call to
i2c_get_read_data().
If a callback method is provided, when data is received from the device it will be sent to the callback ... | def function[i2c_read, parameter[self, address, register, number_of_bytes, read_type, cb]]:
constant[
This method requests the read of an i2c device. Results are retrieved by a call to
i2c_get_read_data().
If a callback method is provided, when data is received from the device it will be... | keyword[def] identifier[i2c_read] ( identifier[self] , identifier[address] , identifier[register] , identifier[number_of_bytes] , identifier[read_type] , identifier[cb] = keyword[None] ):
literal[string]
identifier[data] =[ identifier[address] , identifier[read_type] , identifier[register] & litera... | def i2c_read(self, address, register, number_of_bytes, read_type, cb=None):
"""
This method requests the read of an i2c device. Results are retrieved by a call to
i2c_get_read_data().
If a callback method is provided, when data is received from the device it will be sent to the callback meth... |
def save(self, *args, **kwargs):
"""
saves creates or updates current resource
returns new resource
"""
self._pre_save(*args, **kwargs)
response = self._save(*args, **kwargs)
response = self._post_save(response, *args, **kwargs)
return response | def function[save, parameter[self]]:
constant[
saves creates or updates current resource
returns new resource
]
call[name[self]._pre_save, parameter[<ast.Starred object at 0x7da18f09cfd0>]]
variable[response] assign[=] call[name[self]._save, parameter[<ast.Starred object ... | keyword[def] identifier[save] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_pre_save] (* identifier[args] ,** identifier[kwargs] )
identifier[response] = identifier[self] . identifier[_save] (* identifier[args] ,** identifie... | def save(self, *args, **kwargs):
"""
saves creates or updates current resource
returns new resource
"""
self._pre_save(*args, **kwargs)
response = self._save(*args, **kwargs)
response = self._post_save(response, *args, **kwargs)
return response |
def _indentUpTo(self, text, width):
"""Add space to text, so text width will be at least width.
Return text, which must be added
"""
visibleTextWidth = self._realToVisibleColumn(text, len(text))
diff = width - visibleTextWidth
if diff <= 0:
return ''
e... | def function[_indentUpTo, parameter[self, text, width]]:
constant[Add space to text, so text width will be at least width.
Return text, which must be added
]
variable[visibleTextWidth] assign[=] call[name[self]._realToVisibleColumn, parameter[name[text], call[name[len], parameter[name[te... | keyword[def] identifier[_indentUpTo] ( identifier[self] , identifier[text] , identifier[width] ):
literal[string]
identifier[visibleTextWidth] = identifier[self] . identifier[_realToVisibleColumn] ( identifier[text] , identifier[len] ( identifier[text] ))
identifier[diff] = identifier[widt... | def _indentUpTo(self, text, width):
"""Add space to text, so text width will be at least width.
Return text, which must be added
"""
visibleTextWidth = self._realToVisibleColumn(text, len(text))
diff = width - visibleTextWidth
if diff <= 0:
return '' # depends on [control=['if']... |
def finalize(self, result=None):
"""
Clean up any created database and schema.
"""
if not self.settings_path:
# short circuit if no settings file can be found
return
from django.test.utils import teardown_test_environment
from django.db import con... | def function[finalize, parameter[self, result]]:
constant[
Clean up any created database and schema.
]
if <ast.UnaryOp object at 0x7da20c6e5030> begin[:]
return[None]
from relative_module[django.test.utils] import module[teardown_test_environment]
from relative_module[dja... | keyword[def] identifier[finalize] ( identifier[self] , identifier[result] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[settings_path] :
keyword[return]
keyword[from] identifier[django] . identifier[test] . identifier[u... | def finalize(self, result=None):
"""
Clean up any created database and schema.
"""
if not self.settings_path:
# short circuit if no settings file can be found
return # depends on [control=['if'], data=[]]
from django.test.utils import teardown_test_environment
from djang... |
def _connect(self):
"""Connect to socket. This should be run in a new thread."""
while self.protocol:
_LOGGER.info('Trying to connect to %s', self.server_address)
try:
sock = socket.create_connection(
self.server_address, self.reconnect_timeout... | def function[_connect, parameter[self]]:
constant[Connect to socket. This should be run in a new thread.]
while name[self].protocol begin[:]
call[name[_LOGGER].info, parameter[constant[Trying to connect to %s], name[self].server_address]]
<ast.Try object at 0x7da2041da140> | keyword[def] identifier[_connect] ( identifier[self] ):
literal[string]
keyword[while] identifier[self] . identifier[protocol] :
identifier[_LOGGER] . identifier[info] ( literal[string] , identifier[self] . identifier[server_address] )
keyword[try] :
iden... | def _connect(self):
"""Connect to socket. This should be run in a new thread."""
while self.protocol:
_LOGGER.info('Trying to connect to %s', self.server_address)
try:
sock = socket.create_connection(self.server_address, self.reconnect_timeout) # depends on [control=['try'], data=[]... |
def _calc_overlap_coef(
markers1: dict,
markers2: dict,
):
"""Calculate overlap coefficient between the values of two dictionaries
Note: dict values must be sets
"""
overlap_coef=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].i... | def function[_calc_overlap_coef, parameter[markers1, markers2]]:
constant[Calculate overlap coefficient between the values of two dictionaries
Note: dict values must be sets
]
variable[overlap_coef] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Call object at 0x7da1b2344b20>, <ast.Call o... | keyword[def] identifier[_calc_overlap_coef] (
identifier[markers1] : identifier[dict] ,
identifier[markers2] : identifier[dict] ,
):
literal[string]
identifier[overlap_coef] = identifier[np] . identifier[zeros] (( identifier[len] ( identifier[markers1] ), identifier[len] ( identifier[markers2] )))
... | def _calc_overlap_coef(markers1: dict, markers2: dict):
"""Calculate overlap coefficient between the values of two dictionaries
Note: dict values must be sets
"""
overlap_coef = np.zeros((len(markers1), len(markers2)))
j = 0
for marker_group in markers1:
tmp = [len(markers2[i].intersect... |
def clean_df(df, header=None, **read_csv_kwargs):
""" Convert UTF8 characters in a CSV file or dataframe into ASCII
Args:
df (DataFrame or str): DataFrame or path or url to CSV
"""
df = read_csv(df, header=header, **read_csv_kwargs)
df = df.fillna(' ')
for col in df.columns:
df[co... | def function[clean_df, parameter[df, header]]:
constant[ Convert UTF8 characters in a CSV file or dataframe into ASCII
Args:
df (DataFrame or str): DataFrame or path or url to CSV
]
variable[df] assign[=] call[name[read_csv], parameter[name[df]]]
variable[df] assign[=] call[name[d... | keyword[def] identifier[clean_df] ( identifier[df] , identifier[header] = keyword[None] ,** identifier[read_csv_kwargs] ):
literal[string]
identifier[df] = identifier[read_csv] ( identifier[df] , identifier[header] = identifier[header] ,** identifier[read_csv_kwargs] )
identifier[df] = identifier[df] ... | def clean_df(df, header=None, **read_csv_kwargs):
""" Convert UTF8 characters in a CSV file or dataframe into ASCII
Args:
df (DataFrame or str): DataFrame or path or url to CSV
"""
df = read_csv(df, header=header, **read_csv_kwargs)
df = df.fillna(' ')
for col in df.columns:
df[co... |
def _calculate_num_queries(self):
"""
Calculate the total number of request and response queries.
Used for count header and count table.
"""
request_totals = self._totals("request")
response_totals = self._totals("response")
return request_totals[2] + response_to... | def function[_calculate_num_queries, parameter[self]]:
constant[
Calculate the total number of request and response queries.
Used for count header and count table.
]
variable[request_totals] assign[=] call[name[self]._totals, parameter[constant[request]]]
variable[respons... | keyword[def] identifier[_calculate_num_queries] ( identifier[self] ):
literal[string]
identifier[request_totals] = identifier[self] . identifier[_totals] ( literal[string] )
identifier[response_totals] = identifier[self] . identifier[_totals] ( literal[string] )
keyword[return] ... | def _calculate_num_queries(self):
"""
Calculate the total number of request and response queries.
Used for count header and count table.
"""
request_totals = self._totals('request')
response_totals = self._totals('response')
return request_totals[2] + response_totals[2] |
def ExpandRelativePath(method_config, params, relative_path=None):
"""Determine the relative path for request."""
path = relative_path or method_config.relative_path or ''
for param in method_config.path_params:
param_template = '{%s}' % param
# For more details about "reserved word expansi... | def function[ExpandRelativePath, parameter[method_config, params, relative_path]]:
constant[Determine the relative path for request.]
variable[path] assign[=] <ast.BoolOp object at 0x7da1b07b9b10>
for taget[name[param]] in starred[name[method_config].path_params] begin[:]
variabl... | keyword[def] identifier[ExpandRelativePath] ( identifier[method_config] , identifier[params] , identifier[relative_path] = keyword[None] ):
literal[string]
identifier[path] = identifier[relative_path] keyword[or] identifier[method_config] . identifier[relative_path] keyword[or] literal[string]
k... | def ExpandRelativePath(method_config, params, relative_path=None):
"""Determine the relative path for request."""
path = relative_path or method_config.relative_path or ''
for param in method_config.path_params:
param_template = '{%s}' % param
# For more details about "reserved word expansio... |
def _metric_names_for_training_job(self):
"""Helper method to discover the metrics defined for a training job.
"""
training_description = self._sage_client.describe_training_job(TrainingJobName=self._training_job_name)
metric_definitions = training_description['AlgorithmSpecification'][... | def function[_metric_names_for_training_job, parameter[self]]:
constant[Helper method to discover the metrics defined for a training job.
]
variable[training_description] assign[=] call[name[self]._sage_client.describe_training_job, parameter[]]
variable[metric_definitions] assign[=] cal... | keyword[def] identifier[_metric_names_for_training_job] ( identifier[self] ):
literal[string]
identifier[training_description] = identifier[self] . identifier[_sage_client] . identifier[describe_training_job] ( identifier[TrainingJobName] = identifier[self] . identifier[_training_job_name] )
... | def _metric_names_for_training_job(self):
"""Helper method to discover the metrics defined for a training job.
"""
training_description = self._sage_client.describe_training_job(TrainingJobName=self._training_job_name)
metric_definitions = training_description['AlgorithmSpecification']['MetricDefini... |
def fix_reserved_word(word, is_module=False):
"""
Replaces words that may be problematic
In particular the term 'type' is used in the osid spec, primarily as an argument
parameter where a type is provided to a method. 'type' is a reserved word
in python, so we give ours a trailing underscore. If w... | def function[fix_reserved_word, parameter[word, is_module]]:
constant[
Replaces words that may be problematic
In particular the term 'type' is used in the osid spec, primarily as an argument
parameter where a type is provided to a method. 'type' is a reserved word
in python, so we give ours a ... | keyword[def] identifier[fix_reserved_word] ( identifier[word] , identifier[is_module] = keyword[False] ):
literal[string]
keyword[if] identifier[is_module] :
keyword[if] identifier[word] == literal[string] :
identifier[word] = literal[string]
keyword[else] :
keyword[i... | def fix_reserved_word(word, is_module=False):
"""
Replaces words that may be problematic
In particular the term 'type' is used in the osid spec, primarily as an argument
parameter where a type is provided to a method. 'type' is a reserved word
in python, so we give ours a trailing underscore. If w... |
def asdict(self):
"""Encode the data in this event into a dictionary.
The dictionary returned from this method is a reference to the data
stored in the IOTileEvent, not a copy. It should be treated as read
only.
Returns:
dict: A dictionary containing the informatio... | def function[asdict, parameter[self]]:
constant[Encode the data in this event into a dictionary.
The dictionary returned from this method is a reference to the data
stored in the IOTileEvent, not a copy. It should be treated as read
only.
Returns:
dict: A dictionar... | keyword[def] identifier[asdict] ( identifier[self] ):
literal[string]
keyword[return] {
literal[string] : identifier[self] . identifier[stream] ,
literal[string] : identifier[self] . identifier[raw_time] ,
literal[string] : identifier[self] . identifier[reading_id] ,
... | def asdict(self):
"""Encode the data in this event into a dictionary.
The dictionary returned from this method is a reference to the data
stored in the IOTileEvent, not a copy. It should be treated as read
only.
Returns:
dict: A dictionary containing the information fr... |
def top_comments(self):
"""Return a markdown representation of the top comments."""
num = min(10, len(self.comments))
if num <= 0:
return ''
top_comments = sorted(
self.comments, key=lambda x: (-x.score, str(x.author)))[:num]
retval = self.post_header.for... | def function[top_comments, parameter[self]]:
constant[Return a markdown representation of the top comments.]
variable[num] assign[=] call[name[min], parameter[constant[10], call[name[len], parameter[name[self].comments]]]]
if compare[name[num] less_or_equal[<=] constant[0]] begin[:]
retu... | keyword[def] identifier[top_comments] ( identifier[self] ):
literal[string]
identifier[num] = identifier[min] ( literal[int] , identifier[len] ( identifier[self] . identifier[comments] ))
keyword[if] identifier[num] <= literal[int] :
keyword[return] literal[string]
... | def top_comments(self):
"""Return a markdown representation of the top comments."""
num = min(10, len(self.comments))
if num <= 0:
return '' # depends on [control=['if'], data=[]]
top_comments = sorted(self.comments, key=lambda x: (-x.score, str(x.author)))[:num]
retval = self.post_header.f... |
def do_resolve(cls, executor, extra_args, ivyxml, jvm_options, workdir_report_paths_by_conf,
confs, ivy_resolution_cache_dir, ivy_cache_classpath_filename, resolve_hash_name,
workunit_factory, workunit_name):
"""Execute Ivy with the given ivy.xml and copies all relevant files into ... | def function[do_resolve, parameter[cls, executor, extra_args, ivyxml, jvm_options, workdir_report_paths_by_conf, confs, ivy_resolution_cache_dir, ivy_cache_classpath_filename, resolve_hash_name, workunit_factory, workunit_name]]:
constant[Execute Ivy with the given ivy.xml and copies all relevant files into the... | keyword[def] identifier[do_resolve] ( identifier[cls] , identifier[executor] , identifier[extra_args] , identifier[ivyxml] , identifier[jvm_options] , identifier[workdir_report_paths_by_conf] ,
identifier[confs] , identifier[ivy_resolution_cache_dir] , identifier[ivy_cache_classpath_filename] , identifier[resolve_ha... | def do_resolve(cls, executor, extra_args, ivyxml, jvm_options, workdir_report_paths_by_conf, confs, ivy_resolution_cache_dir, ivy_cache_classpath_filename, resolve_hash_name, workunit_factory, workunit_name):
"""Execute Ivy with the given ivy.xml and copies all relevant files into the workdir.
This method does... |
def load_motif_db(filename, skipn_matrix=0):
"""Read the motif file in the following format
```
>motif_name
<skip n>0.1<delim>0.2<delim>0.5<delim>0.6
...
>motif_name2
....
```
Delim can be anything supported by np.loadtxt
# Arguments
filename: str, file path
sk... | def function[load_motif_db, parameter[filename, skipn_matrix]]:
constant[Read the motif file in the following format
```
>motif_name
<skip n>0.1<delim>0.2<delim>0.5<delim>0.6
...
>motif_name2
....
```
Delim can be anything supported by np.loadtxt
# Arguments
filena... | keyword[def] identifier[load_motif_db] ( identifier[filename] , identifier[skipn_matrix] = literal[int] ):
literal[string]
keyword[if] identifier[filename] . identifier[endswith] ( literal[string] ):
identifier[f] = identifier[gzip] . identifier[open] ( identifier[filename] , literal[string... | def load_motif_db(filename, skipn_matrix=0):
"""Read the motif file in the following format
```
>motif_name
<skip n>0.1<delim>0.2<delim>0.5<delim>0.6
...
>motif_name2
....
```
Delim can be anything supported by np.loadtxt
# Arguments
filename: str, file path
sk... |
def millipede(size, comment=None, reverse=False, template='default', position=0, opposite=False):
"""
Output the millipede
"""
padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3]
padding_suite_length = len(padding_offsets)
head_padding_extra_offset = 2
if opposite:
padding_offsets.reverse... | def function[millipede, parameter[size, comment, reverse, template, position, opposite]]:
constant[
Output the millipede
]
variable[padding_offsets] assign[=] list[[<ast.Constant object at 0x7da1b11c0070>, <ast.Constant object at 0x7da1b11c04f0>, <ast.Constant object at 0x7da1b11c1210>, <ast.Con... | keyword[def] identifier[millipede] ( identifier[size] , identifier[comment] = keyword[None] , identifier[reverse] = keyword[False] , identifier[template] = literal[string] , identifier[position] = literal[int] , identifier[opposite] = keyword[False] ):
literal[string]
identifier[padding_offsets] =[ literal... | def millipede(size, comment=None, reverse=False, template='default', position=0, opposite=False):
"""
Output the millipede
"""
padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3]
padding_suite_length = len(padding_offsets)
head_padding_extra_offset = 2
if opposite:
padding_offsets.reverse(... |
def parse_patients(job, patient_dict, skip_fusions=False):
"""
Parse a dict of patient entries to retain only the useful entries (The user may provide more
than we need and we don't want to download redundant things)
:param dict patient_dict: The dict of patient entries parsed from the input config
... | def function[parse_patients, parameter[job, patient_dict, skip_fusions]]:
constant[
Parse a dict of patient entries to retain only the useful entries (The user may provide more
than we need and we don't want to download redundant things)
:param dict patient_dict: The dict of patient entries parsed ... | keyword[def] identifier[parse_patients] ( identifier[job] , identifier[patient_dict] , identifier[skip_fusions] = keyword[False] ):
literal[string]
identifier[output_dict] ={ literal[string] : identifier[patient_dict] . identifier[get] ( literal[string] ) keyword[in] ( keyword[True] , literal[string] , lit... | def parse_patients(job, patient_dict, skip_fusions=False):
"""
Parse a dict of patient entries to retain only the useful entries (The user may provide more
than we need and we don't want to download redundant things)
:param dict patient_dict: The dict of patient entries parsed from the input config
... |
def delete_config(self, media):
"""Deletes the files associated with this machine from disk. If medium objects are passed
in with the @a aMedia argument, they are closed and, if closing was successful, their
storage files are deleted as well. For convenience, this array of media files can be
... | def function[delete_config, parameter[self, media]]:
constant[Deletes the files associated with this machine from disk. If medium objects are passed
in with the @a aMedia argument, they are closed and, if closing was successful, their
storage files are deleted as well. For convenience, this arra... | keyword[def] identifier[delete_config] ( identifier[self] , identifier[media] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[media] , identifier[list] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[for] identifier[a] k... | def delete_config(self, media):
"""Deletes the files associated with this machine from disk. If medium objects are passed
in with the @a aMedia argument, they are closed and, if closing was successful, their
storage files are deleted as well. For convenience, this array of media files can be
... |
def get_group(group, flags=FLAGS.BASE | FLAGS.INLINE_POLICIES | FLAGS.MANAGED_POLICIES, **conn):
"""
Orchestrates all the calls required to fully build out an IAM Group in the following format:
{
"Arn": ...,
"GroupName": ...,
"Path": ...,
"GroupId": ...,
"CreateDate"... | def function[get_group, parameter[group, flags]]:
constant[
Orchestrates all the calls required to fully build out an IAM Group in the following format:
{
"Arn": ...,
"GroupName": ...,
"Path": ...,
"GroupId": ...,
"CreateDate": ..., # str
"InlinePolicies... | keyword[def] identifier[get_group] ( identifier[group] , identifier[flags] = identifier[FLAGS] . identifier[BASE] | identifier[FLAGS] . identifier[INLINE_POLICIES] | identifier[FLAGS] . identifier[MANAGED_POLICIES] ,** identifier[conn] ):
literal[string]
keyword[if] keyword[not] identifier[group] . ident... | def get_group(group, flags=FLAGS.BASE | FLAGS.INLINE_POLICIES | FLAGS.MANAGED_POLICIES, **conn):
"""
Orchestrates all the calls required to fully build out an IAM Group in the following format:
{
"Arn": ...,
"GroupName": ...,
"Path": ...,
"GroupId": ...,
"CreateDate"... |
def subset_bed_by_chrom(in_file, chrom, data, out_dir=None):
"""Subset a BED file to only have items from the specified chromosome.
"""
if out_dir is None:
out_dir = os.path.dirname(in_file)
base, ext = os.path.splitext(os.path.basename(in_file))
out_file = os.path.join(out_dir, "%s-%s%s" % ... | def function[subset_bed_by_chrom, parameter[in_file, chrom, data, out_dir]]:
constant[Subset a BED file to only have items from the specified chromosome.
]
if compare[name[out_dir] is constant[None]] begin[:]
variable[out_dir] assign[=] call[name[os].path.dirname, parameter[name[in_f... | keyword[def] identifier[subset_bed_by_chrom] ( identifier[in_file] , identifier[chrom] , identifier[data] , identifier[out_dir] = keyword[None] ):
literal[string]
keyword[if] identifier[out_dir] keyword[is] keyword[None] :
identifier[out_dir] = identifier[os] . identifier[path] . identifier[dir... | def subset_bed_by_chrom(in_file, chrom, data, out_dir=None):
"""Subset a BED file to only have items from the specified chromosome.
"""
if out_dir is None:
out_dir = os.path.dirname(in_file) # depends on [control=['if'], data=['out_dir']]
(base, ext) = os.path.splitext(os.path.basename(in_file)... |
def histogram1d(x, bins, range, weights=None):
"""
Compute a 1D histogram assuming equally spaced bins.
Parameters
----------
x : `~numpy.ndarray`
The position of the points to bin in the 1D histogram
bins : int
The number of bins
range : iterable
The range as a tupl... | def function[histogram1d, parameter[x, bins, range, weights]]:
constant[
Compute a 1D histogram assuming equally spaced bins.
Parameters
----------
x : `~numpy.ndarray`
The position of the points to bin in the 1D histogram
bins : int
The number of bins
range : iterable
... | keyword[def] identifier[histogram1d] ( identifier[x] , identifier[bins] , identifier[range] , identifier[weights] = keyword[None] ):
literal[string]
identifier[nx] = identifier[bins]
keyword[if] keyword[not] identifier[np] . identifier[isscalar] ( identifier[bins] ):
keyword[raise] iden... | def histogram1d(x, bins, range, weights=None):
"""
Compute a 1D histogram assuming equally spaced bins.
Parameters
----------
x : `~numpy.ndarray`
The position of the points to bin in the 1D histogram
bins : int
The number of bins
range : iterable
The range as a tupl... |
def _group_tokens(cls, token_stream, range_list):
"""
Group tokens into snippet ranges.
`token_stream` is a generator that produces
`(token_type, value)` tuples,
`range_list` is a list of `(start, end)` tuples representing
the (inclusive) range of line numbers for each ... | def function[_group_tokens, parameter[cls, token_stream, range_list]]:
constant[
Group tokens into snippet ranges.
`token_stream` is a generator that produces
`(token_type, value)` tuples,
`range_list` is a list of `(start, end)` tuples representing
the (inclusive) rang... | keyword[def] identifier[_group_tokens] ( identifier[cls] , identifier[token_stream] , identifier[range_list] ):
literal[string]
identifier[token_map] ={ identifier[rng] :[] keyword[for] identifier[rng] keyword[in] identifier[range_list] }
identifier[line_num... | def _group_tokens(cls, token_stream, range_list):
"""
Group tokens into snippet ranges.
`token_stream` is a generator that produces
`(token_type, value)` tuples,
`range_list` is a list of `(start, end)` tuples representing
the (inclusive) range of line numbers for each snip... |
def tax_class_based_on(self, tax_class_based_on):
"""Sets the tax_class_based_on of this TaxSettings.
:param tax_class_based_on: The tax_class_based_on of this TaxSettings.
:type: str
"""
allowed_values = ["shippingAddress", "billingAddress"] # noqa: E501
if tax_class_... | def function[tax_class_based_on, parameter[self, tax_class_based_on]]:
constant[Sets the tax_class_based_on of this TaxSettings.
:param tax_class_based_on: The tax_class_based_on of this TaxSettings.
:type: str
]
variable[allowed_values] assign[=] list[[<ast.Constant object at ... | keyword[def] identifier[tax_class_based_on] ( identifier[self] , identifier[tax_class_based_on] ):
literal[string]
identifier[allowed_values] =[ literal[string] , literal[string] ]
keyword[if] identifier[tax_class_based_on] keyword[is] keyword[not] keyword[None] keyword[and] identifi... | def tax_class_based_on(self, tax_class_based_on):
"""Sets the tax_class_based_on of this TaxSettings.
:param tax_class_based_on: The tax_class_based_on of this TaxSettings.
:type: str
"""
allowed_values = ['shippingAddress', 'billingAddress'] # noqa: E501
if tax_class_based_on is ... |
def setup_network_agents(self):
"""Initializes agents on nodes of graph and registers them to the SimPy environment"""
for i in self.env.G.nodes():
self.env.G.node[i]['agent'] = self.agent_type(environment=self.env, agent_id=i,
state=... | def function[setup_network_agents, parameter[self]]:
constant[Initializes agents on nodes of graph and registers them to the SimPy environment]
for taget[name[i]] in starred[call[name[self].env.G.nodes, parameter[]]] begin[:]
call[call[name[self].env.G.node][name[i]]][constant[agent]] as... | keyword[def] identifier[setup_network_agents] ( identifier[self] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[self] . identifier[env] . identifier[G] . identifier[nodes] ():
identifier[self] . identifier[env] . identifier[G] . identifier[node] [ identifier[i]... | def setup_network_agents(self):
"""Initializes agents on nodes of graph and registers them to the SimPy environment"""
for i in self.env.G.nodes():
self.env.G.node[i]['agent'] = self.agent_type(environment=self.env, agent_id=i, state=deepcopy(self.initial_states[i])) # depends on [control=['for'], data... |
def func_on_enter(func):
"""
Register the `func` as a callback reacting only to ENTER.
Note:
This function doesn't bind the key to the element, just creates sort of
filter, which ignores all other events.
"""
def function_after_enter_pressed(ev):
ev.stopPropagation()
... | def function[func_on_enter, parameter[func]]:
constant[
Register the `func` as a callback reacting only to ENTER.
Note:
This function doesn't bind the key to the element, just creates sort of
filter, which ignores all other events.
]
def function[function_after_enter_pressed... | keyword[def] identifier[func_on_enter] ( identifier[func] ):
literal[string]
keyword[def] identifier[function_after_enter_pressed] ( identifier[ev] ):
identifier[ev] . identifier[stopPropagation] ()
keyword[if] identifier[ev] . identifier[keyCode] == literal[int] :
... | def func_on_enter(func):
"""
Register the `func` as a callback reacting only to ENTER.
Note:
This function doesn't bind the key to the element, just creates sort of
filter, which ignores all other events.
"""
def function_after_enter_pressed(ev):
ev.stopPropagation()
... |
def photeq(files='*_flt.fits', sciext='SCI', errext='ERR',
ref_phot=None, ref_phot_ext=None,
phot_kwd='PHOTFLAM', aux_phot_kwd='PHOTFNU',
search_primary=True,
readonly=True, clobber=False, logfile='photeq.log'):
"""
Adjust data values of images by equalizing each chip... | def function[photeq, parameter[files, sciext, errext, ref_phot, ref_phot_ext, phot_kwd, aux_phot_kwd, search_primary, readonly, clobber, logfile]]:
constant[
Adjust data values of images by equalizing each chip's PHOTFLAM value
to a single common value so that all chips can be treated equally
by ``A... | keyword[def] identifier[photeq] ( identifier[files] = literal[string] , identifier[sciext] = literal[string] , identifier[errext] = literal[string] ,
identifier[ref_phot] = keyword[None] , identifier[ref_phot_ext] = keyword[None] ,
identifier[phot_kwd] = literal[string] , identifier[aux_phot_kwd] = literal[string] ... | def photeq(files='*_flt.fits', sciext='SCI', errext='ERR', ref_phot=None, ref_phot_ext=None, phot_kwd='PHOTFLAM', aux_phot_kwd='PHOTFNU', search_primary=True, readonly=True, clobber=False, logfile='photeq.log'):
"""
Adjust data values of images by equalizing each chip's PHOTFLAM value
to a single common val... |
def _sync(original, processed):
"""
Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers.
"""
for original_sample in original:
original_sample[0]["peaks_files"] = {}
for process_sample in processed:
if dd.get_... | def function[_sync, parameter[original, processed]]:
constant[
Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers.
]
for taget[name[original_sample]] in starred[name[original]] begin[:]
call[call[name[original_s... | keyword[def] identifier[_sync] ( identifier[original] , identifier[processed] ):
literal[string]
keyword[for] identifier[original_sample] keyword[in] identifier[original] :
identifier[original_sample] [ literal[int] ][ literal[string] ]={}
keyword[for] identifier[process_sample] keyw... | def _sync(original, processed):
"""
Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers.
"""
for original_sample in original:
original_sample[0]['peaks_files'] = {}
for process_sample in processed:
if dd.get_... |
def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null',
blank_value='Unknown', missing_value='Unknown DB Code'):
'''Output the human-readable strings associated with the list of database values for a model field.
Uses the trans... | def function[normalize_choices, parameter[db_values, field_name, app, model_name, human_readable, none_value, blank_value, missing_value]]:
constant[Output the human-readable strings associated with the list of database values for a model field.
Uses the translation dictionary `CHOICES_<FIELD_NAME>` attrib... | keyword[def] identifier[normalize_choices] ( identifier[db_values] , identifier[field_name] , identifier[app] = identifier[DEFAULT_APP] , identifier[model_name] = literal[string] , identifier[human_readable] = keyword[True] , identifier[none_value] = literal[string] ,
identifier[blank_value] = literal[string] , iden... | def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null', blank_value='Unknown', missing_value='Unknown DB Code'):
"""Output the human-readable strings associated with the list of database values for a model field.
Uses the translation dictionary `CHOI... |
def match_query_to_corpus(self):
"""Q.match_query_to_corpus() -> index -- return the matched corpus
index of the user query
"""
ranking = []
for i,doc in enumerate(self.processed_corpus):
rank = 0.0
for word in self.processed_query:
if word in doc:
rank += self.term_frequencies[i][word] * sel... | def function[match_query_to_corpus, parameter[self]]:
constant[Q.match_query_to_corpus() -> index -- return the matched corpus
index of the user query
]
variable[ranking] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da18ede6e30>, <ast.Name object at 0x7da18ede7970>]]] in star... | keyword[def] identifier[match_query_to_corpus] ( identifier[self] ):
literal[string]
identifier[ranking] =[]
keyword[for] identifier[i] , identifier[doc] keyword[in] identifier[enumerate] ( identifier[self] . identifier[processed_corpus] ):
identifier[rank] = literal[int]
keyword[for] identifie... | def match_query_to_corpus(self):
"""Q.match_query_to_corpus() -> index -- return the matched corpus
index of the user query
"""
ranking = []
for (i, doc) in enumerate(self.processed_corpus):
rank = 0.0
for word in self.processed_query:
if word in doc:
rank +... |
def from_url(cls, url):
"Construct a (possibly null) ContentChecker from a URL"
fragment = urlparse(url)[-1]
if not fragment:
return ContentChecker()
match = cls.pattern.search(fragment)
if not match:
return ContentChecker()
return cls(**match.grou... | def function[from_url, parameter[cls, url]]:
constant[Construct a (possibly null) ContentChecker from a URL]
variable[fragment] assign[=] call[call[name[urlparse], parameter[name[url]]]][<ast.UnaryOp object at 0x7da20c6aa6b0>]
if <ast.UnaryOp object at 0x7da20c6aa050> begin[:]
return[cal... | keyword[def] identifier[from_url] ( identifier[cls] , identifier[url] ):
literal[string]
identifier[fragment] = identifier[urlparse] ( identifier[url] )[- literal[int] ]
keyword[if] keyword[not] identifier[fragment] :
keyword[return] identifier[ContentChecker] ()
i... | def from_url(cls, url):
"""Construct a (possibly null) ContentChecker from a URL"""
fragment = urlparse(url)[-1]
if not fragment:
return ContentChecker() # depends on [control=['if'], data=[]]
match = cls.pattern.search(fragment)
if not match:
return ContentChecker() # depends on [... |
def model_page(self, request, app_label, model_name, rest_of_url=None):
"""
Handles the model-specific functionality of the databrowse site,
delegating<to the appropriate ModelDatabrowse class.
"""
try:
model = get_model(app_label, model_name)
except LookupErr... | def function[model_page, parameter[self, request, app_label, model_name, rest_of_url]]:
constant[
Handles the model-specific functionality of the databrowse site,
delegating<to the appropriate ModelDatabrowse class.
]
<ast.Try object at 0x7da204567340>
if compare[name[model] ... | keyword[def] identifier[model_page] ( identifier[self] , identifier[request] , identifier[app_label] , identifier[model_name] , identifier[rest_of_url] = keyword[None] ):
literal[string]
keyword[try] :
identifier[model] = identifier[get_model] ( identifier[app_label] , identifier[model... | def model_page(self, request, app_label, model_name, rest_of_url=None):
"""
Handles the model-specific functionality of the databrowse site,
delegating<to the appropriate ModelDatabrowse class.
"""
try:
model = get_model(app_label, model_name) # depends on [control=['try'], data... |
def download_to_file(self, local_file, headers=None, cookies=None,
chunk_size=1024):
"""Downloads link to local file
:param local_file: Save url as this path
:param headers: Headers to fetch url
:param cookies: Cookies to fetch url
:param chunk_size: int... | def function[download_to_file, parameter[self, local_file, headers, cookies, chunk_size]]:
constant[Downloads link to local file
:param local_file: Save url as this path
:param headers: Headers to fetch url
:param cookies: Cookies to fetch url
:param chunk_size: int
]
... | keyword[def] identifier[download_to_file] ( identifier[self] , identifier[local_file] , identifier[headers] = keyword[None] , identifier[cookies] = keyword[None] ,
identifier[chunk_size] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[headers] :
identifier[hea... | def download_to_file(self, local_file, headers=None, cookies=None, chunk_size=1024):
"""Downloads link to local file
:param local_file: Save url as this path
:param headers: Headers to fetch url
:param cookies: Cookies to fetch url
:param chunk_size: int
"""
if not heade... |
def escape(pattern):
"Escape all non-alphanumeric characters in pattern."
s = list(pattern)
alphanum = _alphanum
for i, c in enumerate(pattern):
if c not in alphanum:
if c == "\000":
s[i] = "\\000"
else:
s[i] = "\\" + c
return pattern[:... | def function[escape, parameter[pattern]]:
constant[Escape all non-alphanumeric characters in pattern.]
variable[s] assign[=] call[name[list], parameter[name[pattern]]]
variable[alphanum] assign[=] name[_alphanum]
for taget[tuple[[<ast.Name object at 0x7da18bcc8340>, <ast.Name object at 0... | keyword[def] identifier[escape] ( identifier[pattern] ):
literal[string]
identifier[s] = identifier[list] ( identifier[pattern] )
identifier[alphanum] = identifier[_alphanum]
keyword[for] identifier[i] , identifier[c] keyword[in] identifier[enumerate] ( identifier[pattern] ):
keyword... | def escape(pattern):
"""Escape all non-alphanumeric characters in pattern."""
s = list(pattern)
alphanum = _alphanum
for (i, c) in enumerate(pattern):
if c not in alphanum:
if c == '\x00':
s[i] = '\\000' # depends on [control=['if'], data=[]]
else:
... |
def ccmodmd_setcoef(k):
"""Set the coefficient maps for the ccmod stage. The only parameter is
the slice index `k` and there are no return values; all inputs and
outputs are from and to global variables.
"""
# Set working coefficient maps for ccmod step and compute DFT of
# coefficient maps Z
... | def function[ccmodmd_setcoef, parameter[k]]:
constant[Set the coefficient maps for the ccmod stage. The only parameter is
the slice index `k` and there are no return values; all inputs and
outputs are from and to global variables.
]
call[name[mp_Zf]][name[k]] assign[=] call[name[sl].rfftn, p... | keyword[def] identifier[ccmodmd_setcoef] ( identifier[k] ):
literal[string]
identifier[mp_Zf] [ identifier[k] ]= identifier[sl] . identifier[rfftn] ( identifier[mp_Z_Y1] [ identifier[k] ], identifier[mp_cri] . identifier[Nv] , identifier[mp_cri] . identifier[axisN] ) | def ccmodmd_setcoef(k):
"""Set the coefficient maps for the ccmod stage. The only parameter is
the slice index `k` and there are no return values; all inputs and
outputs are from and to global variables.
"""
# Set working coefficient maps for ccmod step and compute DFT of
# coefficient maps Z
... |
def frequency(self, mapping):
"""
Returns frequency of a given :class:`caspo.core.mapping.Mapping`
Parameters
----------
mapping : :class:`caspo.core.mapping.Mapping`
A logical conjuntion mapping
Returns
-------
float
Frequency of... | def function[frequency, parameter[self, mapping]]:
constant[
Returns frequency of a given :class:`caspo.core.mapping.Mapping`
Parameters
----------
mapping : :class:`caspo.core.mapping.Mapping`
A logical conjuntion mapping
Returns
-------
flo... | keyword[def] identifier[frequency] ( identifier[self] , identifier[mapping] ):
literal[string]
keyword[return] identifier[self] . identifier[__matrix] [:, identifier[self] . identifier[hg] . identifier[mappings] [ identifier[mapping] ]]. identifier[mean] () | def frequency(self, mapping):
"""
Returns frequency of a given :class:`caspo.core.mapping.Mapping`
Parameters
----------
mapping : :class:`caspo.core.mapping.Mapping`
A logical conjuntion mapping
Returns
-------
float
Frequency of the... |
def publish(self, message):
"""
Publishes the message to all subscribers of this topic
:param message: (object), the message to be published.
"""
message_data = self._to_data(message)
self._encode_invoke(topic_publish_codec, message=message_data) | def function[publish, parameter[self, message]]:
constant[
Publishes the message to all subscribers of this topic
:param message: (object), the message to be published.
]
variable[message_data] assign[=] call[name[self]._to_data, parameter[name[message]]]
call[name[self]... | keyword[def] identifier[publish] ( identifier[self] , identifier[message] ):
literal[string]
identifier[message_data] = identifier[self] . identifier[_to_data] ( identifier[message] )
identifier[self] . identifier[_encode_invoke] ( identifier[topic_publish_codec] , identifier[message] = id... | def publish(self, message):
"""
Publishes the message to all subscribers of this topic
:param message: (object), the message to be published.
"""
message_data = self._to_data(message)
self._encode_invoke(topic_publish_codec, message=message_data) |
def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):
"""Send a request to BitMEX Servers."""
# Handle URL
url = self.base_url + api
# Default to POST if data is attached, GET otherwise
if not verb:
verb = 'POST' if postdict else 'GET'
... | def function[_curl_bitmex, parameter[self, api, query, postdict, timeout, verb]]:
constant[Send a request to BitMEX Servers.]
variable[url] assign[=] binary_operation[name[self].base_url + name[api]]
if <ast.UnaryOp object at 0x7da18dc07d00> begin[:]
variable[verb] assign[=] <ast... | keyword[def] identifier[_curl_bitmex] ( identifier[self] , identifier[api] , identifier[query] = keyword[None] , identifier[postdict] = keyword[None] , identifier[timeout] = literal[int] , identifier[verb] = keyword[None] ):
literal[string]
identifier[url] = identifier[self] . identifier[b... | def _curl_bitmex(self, api, query=None, postdict=None, timeout=3, verb=None):
"""Send a request to BitMEX Servers."""
# Handle URL
url = self.base_url + api
# Default to POST if data is attached, GET otherwise
if not verb:
verb = 'POST' if postdict else 'GET' # depends on [control=['if'], d... |
def clear_stats(self):
"""Reset server stat counters.."""
self._start_time = None
self._run_time = 0
self.stats = {
'Enabled': False,
'Bind Address': lambda s: repr(self.bind_addr),
'Run time': lambda s: (not s['Enabled']) and -1 or self.runtime(),
... | def function[clear_stats, parameter[self]]:
constant[Reset server stat counters..]
name[self]._start_time assign[=] constant[None]
name[self]._run_time assign[=] constant[0]
name[self].stats assign[=] dictionary[[<ast.Constant object at 0x7da18c4ce8c0>, <ast.Constant object at 0x7da18c4c... | keyword[def] identifier[clear_stats] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_start_time] = keyword[None]
identifier[self] . identifier[_run_time] = literal[int]
identifier[self] . identifier[stats] ={
literal[string] : keyword[False] ,
... | def clear_stats(self):
"""Reset server stat counters.."""
self._start_time = None
self._run_time = 0
self.stats = {'Enabled': False, 'Bind Address': lambda s: repr(self.bind_addr), 'Run time': lambda s: not s['Enabled'] and -1 or self.runtime(), 'Accepts': 0, 'Accepts/sec': lambda s: s['Accepts'] / self... |
def parse_options(self, option_values):
""" Set the options (with parsing) and returns a dict of all options values
"""
self.set_options_values(option_values, parse=True)
return self.get_options_values(hidden=False) | def function[parse_options, parameter[self, option_values]]:
constant[ Set the options (with parsing) and returns a dict of all options values
]
call[name[self].set_options_values, parameter[name[option_values]]]
return[call[name[self].get_options_values, parameter[]]] | keyword[def] identifier[parse_options] ( identifier[self] , identifier[option_values] ):
literal[string]
identifier[self] . identifier[set_options_values] ( identifier[option_values] , identifier[parse] = keyword[True] )
keyword[return] identifier[self] . identifier[get_options_values] ( ... | def parse_options(self, option_values):
""" Set the options (with parsing) and returns a dict of all options values
"""
self.set_options_values(option_values, parse=True)
return self.get_options_values(hidden=False) |
def except_keyword(source, start, keyword):
""" Returns position after keyword if found else None
Note: skips white space"""
start = pass_white(source, start)
kl = len(keyword) #keyword len
if kl + start > len(source):
return None
if source[start:start + kl] != keyword:
retu... | def function[except_keyword, parameter[source, start, keyword]]:
constant[ Returns position after keyword if found else None
Note: skips white space]
variable[start] assign[=] call[name[pass_white], parameter[name[source], name[start]]]
variable[kl] assign[=] call[name[len], parameter[na... | keyword[def] identifier[except_keyword] ( identifier[source] , identifier[start] , identifier[keyword] ):
literal[string]
identifier[start] = identifier[pass_white] ( identifier[source] , identifier[start] )
identifier[kl] = identifier[len] ( identifier[keyword] )
keyword[if] identifier[kl] + id... | def except_keyword(source, start, keyword):
""" Returns position after keyword if found else None
Note: skips white space"""
start = pass_white(source, start)
kl = len(keyword) #keyword len
if kl + start > len(source):
return None # depends on [control=['if'], data=[]]
if source[st... |
def is_success(self, check_timeout=True):
'''
Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization
and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default).
:param check_timeout: When ``True``, check time be... | def function[is_success, parameter[self, check_timeout]]:
constant[
Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization
and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default).
:param check_timeout: When `... | keyword[def] identifier[is_success] ( identifier[self] , identifier[check_timeout] = keyword[True] ):
literal[string]
keyword[if] identifier[check_timeout] keyword[and] identifier[self] . identifier[is_timeout] ():
keyword[return] keyword[False]
keyword[return] identifie... | def is_success(self, check_timeout=True):
"""
Check if Webpay response ``TBK_RESPUESTA`` is equal to ``0`` and if the lapse between initialization
and this call is less than ``self.timeout`` when ``check_timeout`` is ``True`` (default).
:param check_timeout: When ``True``, check time betwee... |
def run(self, statement):
'''Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
'''
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty str... | def function[run, parameter[self, statement]]:
constant[Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
]
variable[statement] assign[=] call[name[statement].strip, parameter[]]
... | keyword[def] identifier[run] ( identifier[self] , identifier[statement] ):
literal[string]
identifier[statement] = identifier[statement] . identifier[strip] ()
keyword[if] keyword[not] identifier[statement] :
keyword[yield] ( keyword[None] , keyword[None] , keyword[... | def run(self, statement):
"""Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
"""
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty string
yiel... |
def _dataset_qa(self, dataset):
"""Chequea si el dataset tiene una calidad mínima para cosechar."""
# 1. VALIDACIONES
# chequea que haya por lo menos algún formato de datos reconocido
has_data_format = helpers.dataset_has_data_distributions(dataset)
# chequea que algunos campos... | def function[_dataset_qa, parameter[self, dataset]]:
constant[Chequea si el dataset tiene una calidad mínima para cosechar.]
variable[has_data_format] assign[=] call[name[helpers].dataset_has_data_distributions, parameter[name[dataset]]]
variable[has_title] assign[=] compare[constant[title] in n... | keyword[def] identifier[_dataset_qa] ( identifier[self] , identifier[dataset] ):
literal[string]
identifier[has_data_format] = identifier[helpers] . identifier[dataset_has_data_distributions] ( identifier[dataset] )
identifier[has_title] = literal[string] keyw... | def _dataset_qa(self, dataset):
"""Chequea si el dataset tiene una calidad mínima para cosechar."""
# 1. VALIDACIONES
# chequea que haya por lo menos algún formato de datos reconocido
has_data_format = helpers.dataset_has_data_distributions(dataset)
# chequea que algunos campos tengan longitudes mín... |
def signal_to_noise_map(self):
"""The signal-to-noise_map of the data and noise-map which are fitted."""
signal_to_noise_map = np.divide(self.data, self.noise_map)
signal_to_noise_map[signal_to_noise_map < 0] = 0
return signal_to_noise_map | def function[signal_to_noise_map, parameter[self]]:
constant[The signal-to-noise_map of the data and noise-map which are fitted.]
variable[signal_to_noise_map] assign[=] call[name[np].divide, parameter[name[self].data, name[self].noise_map]]
call[name[signal_to_noise_map]][compare[name[signal_to... | keyword[def] identifier[signal_to_noise_map] ( identifier[self] ):
literal[string]
identifier[signal_to_noise_map] = identifier[np] . identifier[divide] ( identifier[self] . identifier[data] , identifier[self] . identifier[noise_map] )
identifier[signal_to_noise_map] [ identifier[signal_to... | def signal_to_noise_map(self):
"""The signal-to-noise_map of the data and noise-map which are fitted."""
signal_to_noise_map = np.divide(self.data, self.noise_map)
signal_to_noise_map[signal_to_noise_map < 0] = 0
return signal_to_noise_map |
def _aload8(ins):
''' Loads an 8 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _addr(ins.quad[2])
output.append('ld a, (hl)')
output.append('push af')
return output | def function[_aload8, parameter[ins]]:
constant[ Loads an 8 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
]
variable[output] assign[=] call[name[_addr], parameter[call[name[ins].quad][constant[2]]]]
call[name[output].append, pa... | keyword[def] identifier[_aload8] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_addr] ( identifier[ins] . identifier[quad] [ literal[int] ])
identifier[output] . identifier[append] ( literal[string] )
identifier[output] . identifier[append] ( literal[string] )
keyword... | def _aload8(ins):
""" Loads an 8 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _addr(ins.quad[2])
output.append('ld a, (hl)')
output.append('push af')
return output |
def __envelope(x, hop):
'''Compute the max-envelope of x at a stride/frame length of h'''
return util.frame(x, hop_length=hop, frame_length=hop).max(axis=0) | def function[__envelope, parameter[x, hop]]:
constant[Compute the max-envelope of x at a stride/frame length of h]
return[call[call[name[util].frame, parameter[name[x]]].max, parameter[]]] | keyword[def] identifier[__envelope] ( identifier[x] , identifier[hop] ):
literal[string]
keyword[return] identifier[util] . identifier[frame] ( identifier[x] , identifier[hop_length] = identifier[hop] , identifier[frame_length] = identifier[hop] ). identifier[max] ( identifier[axis] = literal[int] ) | def __envelope(x, hop):
"""Compute the max-envelope of x at a stride/frame length of h"""
return util.frame(x, hop_length=hop, frame_length=hop).max(axis=0) |
def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:
"""Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
Yields:
For every match, a tuple of the matching pattern and the match substitution.
... | def function[match, parameter[self, subject]]:
constant[Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
Yields:
For every match, a tuple of the matching pattern and the match substitution.
]
return[call[name[_MatchI... | keyword[def] identifier[match] ( identifier[self] , identifier[subject] : identifier[Expression] )-> identifier[Iterator] [ identifier[Tuple] [ identifier[Expression] , identifier[Substitution] ]]:
literal[string]
keyword[return] identifier[_MatchIter] ( identifier[self] , identifier[subject] ) | def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:
"""Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
Yields:
For every match, a tuple of the matching pattern and the match substitution.
"""
... |
def fit(self, X, y, sample_weight=None):
"""Fit the Genetic Program according to X, y.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
... | def function[fit, parameter[self, X, y, sample_weight]]:
constant[Fit the Genetic Program according to X, y.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the num... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] , identifier[sample_weight] = keyword[None] ):
literal[string]
identifier[random_state] = identifier[check_random_state] ( identifier[self] . identifier[random_state] )
keyword[if] identifier[isinsta... | def fit(self, X, y, sample_weight=None):
"""Fit the Genetic Program according to X, y.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
... |
def filled_quantity(self):
"""
[int] 订单已成交数量
"""
if np.isnan(self._filled_quantity):
raise RuntimeError("Filled quantity of order {} is not supposed to be nan.".format(self.order_id))
return self._filled_quantity | def function[filled_quantity, parameter[self]]:
constant[
[int] 订单已成交数量
]
if call[name[np].isnan, parameter[name[self]._filled_quantity]] begin[:]
<ast.Raise object at 0x7da1b211d300>
return[name[self]._filled_quantity] | keyword[def] identifier[filled_quantity] ( identifier[self] ):
literal[string]
keyword[if] identifier[np] . identifier[isnan] ( identifier[self] . identifier[_filled_quantity] ):
keyword[raise] identifier[RuntimeError] ( literal[string] . identifier[format] ( identifier[self] . ident... | def filled_quantity(self):
"""
[int] 订单已成交数量
"""
if np.isnan(self._filled_quantity):
raise RuntimeError('Filled quantity of order {} is not supposed to be nan.'.format(self.order_id)) # depends on [control=['if'], data=[]]
return self._filled_quantity |
def wait(self, time):
"""Pauses the thread for a specified time.
Returns False if interrupted by another thread and True if the
time runs out normally.
"""
self._wait = Event()
return not self._wait.wait(time) | def function[wait, parameter[self, time]]:
constant[Pauses the thread for a specified time.
Returns False if interrupted by another thread and True if the
time runs out normally.
]
name[self]._wait assign[=] call[name[Event], parameter[]]
return[<ast.UnaryOp object at 0x7da2... | keyword[def] identifier[wait] ( identifier[self] , identifier[time] ):
literal[string]
identifier[self] . identifier[_wait] = identifier[Event] ()
keyword[return] keyword[not] identifier[self] . identifier[_wait] . identifier[wait] ( identifier[time] ) | def wait(self, time):
"""Pauses the thread for a specified time.
Returns False if interrupted by another thread and True if the
time runs out normally.
"""
self._wait = Event()
return not self._wait.wait(time) |
def list_outputs(db, job_id, full=True):
"""
List the outputs for a given
:class:`~openquake.server.db.models.OqJob`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of a calculation.
:param bool full:
If True produce a full listing, otherwise ... | def function[list_outputs, parameter[db, job_id, full]]:
constant[
List the outputs for a given
:class:`~openquake.server.db.models.OqJob`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of a calculation.
:param bool full:
If True produce ... | keyword[def] identifier[list_outputs] ( identifier[db] , identifier[job_id] , identifier[full] = keyword[True] ):
literal[string]
identifier[outputs] = identifier[get_outputs] ( identifier[db] , identifier[job_id] )
identifier[out] =[]
keyword[if] identifier[len] ( identifier[outputs] )> literal... | def list_outputs(db, job_id, full=True):
"""
List the outputs for a given
:class:`~openquake.server.db.models.OqJob`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of a calculation.
:param bool full:
If True produce a full listing, otherwise ... |
def paint(self, painter, option, widget):
"""
Draws this item with the inputed painter. This will call the
scene's renderer to draw this item.
"""
scene = self.scene()
if not scene:
return
scene.chart().renderer().drawItem(self, pain... | def function[paint, parameter[self, painter, option, widget]]:
constant[
Draws this item with the inputed painter. This will call the
scene's renderer to draw this item.
]
variable[scene] assign[=] call[name[self].scene, parameter[]]
if <ast.UnaryOp object at 0x7da2054a4... | keyword[def] identifier[paint] ( identifier[self] , identifier[painter] , identifier[option] , identifier[widget] ):
literal[string]
identifier[scene] = identifier[self] . identifier[scene] ()
keyword[if] keyword[not] identifier[scene] :
keyword[return]
iden... | def paint(self, painter, option, widget):
"""
Draws this item with the inputed painter. This will call the
scene's renderer to draw this item.
"""
scene = self.scene()
if not scene:
return # depends on [control=['if'], data=[]]
scene.chart().renderer().drawItem(self, pa... |
def execute(self, argv=None, compile=None, preprocessor=None, compiler_factory=None):
"""Parse arguments and execute decorated function
argv: list of arguments
compile:
- None, pass args as keyword args to function
- True, pass args as single dictionary
- fun... | def function[execute, parameter[self, argv, compile, preprocessor, compiler_factory]]:
constant[Parse arguments and execute decorated function
argv: list of arguments
compile:
- None, pass args as keyword args to function
- True, pass args as single dictionary
... | keyword[def] identifier[execute] ( identifier[self] , identifier[argv] = keyword[None] , identifier[compile] = keyword[None] , identifier[preprocessor] = keyword[None] , identifier[compiler_factory] = keyword[None] ):
literal[string]
identifier[action] , identifier[args] , identifier[kwargs] = ide... | def execute(self, argv=None, compile=None, preprocessor=None, compiler_factory=None):
"""Parse arguments and execute decorated function
argv: list of arguments
compile:
- None, pass args as keyword args to function
- True, pass args as single dictionary
- functio... |
def handle(self, message):
'''Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metadata'][... | def function[handle, parameter[self, message]]:
constant[Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
]
call[name[logger].debug, parameter[name[message]]]... | keyword[def] identifier[handle] ( identifier[self] , identifier[message] ):
literal[string]
identifier[logger] . identifier[debug] ( identifier[message] )
keyword[if] identifier[Utilities] . identifier[isNotEmpty] ( identifier[message] [ literal[string] ][ literal[string] ]):
... | def handle(self, message):
"""Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
"""
logger.debug(message)
if Utilities.isNotEmpty(message['metadata']['opts']):
... |
def we_depend_on_them(decls):
"""Returns set of declarations. every item in the returned set,
depends on a declaration from the input"""
to_be_included = set()
for decl in decls:
to_be_included.update(dependency_info_t.i_depend_on_them(decl))
return to_be_included | def function[we_depend_on_them, parameter[decls]]:
constant[Returns set of declarations. every item in the returned set,
depends on a declaration from the input]
variable[to_be_included] assign[=] call[name[set], parameter[]]
for taget[name[decl]] in starred[name[decls]] begin[:]
... | keyword[def] identifier[we_depend_on_them] ( identifier[decls] ):
literal[string]
identifier[to_be_included] = identifier[set] ()
keyword[for] identifier[decl] keyword[in] identifier[decls] :
identifier[to_be_included] . identifier[update] ( identifier[dependency_info_t] . ... | def we_depend_on_them(decls):
"""Returns set of declarations. every item in the returned set,
depends on a declaration from the input"""
to_be_included = set()
for decl in decls:
to_be_included.update(dependency_info_t.i_depend_on_them(decl)) # depends on [control=['for'], data=['decl']]
... |
def _spectrum(self, photon_energy):
"""
Compute differential spectrum from pp interactions using the
parametrization of Kafexhiu, E., Aharonian, F., Taylor, A.~M., and
Vila, G.~S.\ 2014, `arXiv:1406.7369
<http://www.arxiv.org/abs/1406.7369>`_.
Parameters
--------... | def function[_spectrum, parameter[self, photon_energy]]:
constant[
Compute differential spectrum from pp interactions using the
parametrization of Kafexhiu, E., Aharonian, F., Taylor, A.~M., and
Vila, G.~S.\ 2014, `arXiv:1406.7369
<http://www.arxiv.org/abs/1406.7369>`_.
... | keyword[def] identifier[_spectrum] ( identifier[self] , identifier[photon_energy] ):
literal[string]
keyword[if] identifier[self] . identifier[useLUT] :
identifier[LUT_base] = literal[string]
keyword[if] identifier[self] . identifier[nuclear_enhancement] :
... | def _spectrum(self, photon_energy):
"""
Compute differential spectrum from pp interactions using the
parametrization of Kafexhiu, E., Aharonian, F., Taylor, A.~M., and
Vila, G.~S.\\ 2014, `arXiv:1406.7369
<http://www.arxiv.org/abs/1406.7369>`_.
Parameters
----------
... |
def _makedirs(name, mode=0o777, exist_ok=False):
"""Source: https://github.com/python/cpython/blob/
3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
"""
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
if head and tail and not os.path.exists(... | def function[_makedirs, parameter[name, mode, exist_ok]]:
constant[Source: https://github.com/python/cpython/blob/
3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
]
<ast.Tuple object at 0x7da20c6a91b0> assign[=] call[name[os].path.split, parameter[name[name]]]
if <ast.Un... | keyword[def] identifier[_makedirs] ( identifier[name] , identifier[mode] = literal[int] , identifier[exist_ok] = keyword[False] ):
literal[string]
identifier[head] , identifier[tail] = identifier[os] . identifier[path] . identifier[split] ( identifier[name] )
keyword[if] keyword[not] identifier[tail... | def _makedirs(name, mode=511, exist_ok=False):
"""Source: https://github.com/python/cpython/blob/
3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
"""
(head, tail) = os.path.split(name)
if not tail:
(head, tail) = os.path.split(head) # depends on [control=['if'], data=[]]
... |
def count(self, minval, maxval, include_min=True, include_max=True):
'''Returns the number of elements in the skiplist with a score
between min and max.
'''
rank1 = self.rank(minval)
if rank1 < 0:
rank1 = -rank1 - 1
elif not include_min:
rank1 += 1... | def function[count, parameter[self, minval, maxval, include_min, include_max]]:
constant[Returns the number of elements in the skiplist with a score
between min and max.
]
variable[rank1] assign[=] call[name[self].rank, parameter[name[minval]]]
if compare[name[rank1] less[<] cons... | keyword[def] identifier[count] ( identifier[self] , identifier[minval] , identifier[maxval] , identifier[include_min] = keyword[True] , identifier[include_max] = keyword[True] ):
literal[string]
identifier[rank1] = identifier[self] . identifier[rank] ( identifier[minval] )
keyword[if] ide... | def count(self, minval, maxval, include_min=True, include_max=True):
"""Returns the number of elements in the skiplist with a score
between min and max.
"""
rank1 = self.rank(minval)
if rank1 < 0:
rank1 = -rank1 - 1 # depends on [control=['if'], data=['rank1']]
elif not include_... |
def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False):
"""
Return list of all dirs and files inside given dir.
Also can filter contents to return only dirs or files.
Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
- get_files: Re... | def function[listdir, parameter[dir_name, get_dirs, get_files, hide_ignored]]:
constant[
Return list of all dirs and files inside given dir.
Also can filter contents to return only dirs or files.
Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
... | keyword[def] identifier[listdir] ( identifier[dir_name] , identifier[get_dirs] = keyword[None] , identifier[get_files] = keyword[None] , identifier[hide_ignored] = keyword[False] ):
literal[string]
keyword[if] identifier[get_dirs] keyword[is] keyword[None] keyword[and] identifier[get_files] keyword[i... | def listdir(dir_name, get_dirs=None, get_files=None, hide_ignored=False):
"""
Return list of all dirs and files inside given dir.
Also can filter contents to return only dirs or files.
Args:
- dir_name: Which directory we need to scan (relative)
- get_dirs: Return dirs list
- get_files: Re... |
def load_params(self, path, exclude_free_params=False):
from deepy.core import graph
"""
Load parameters to the block.
"""
from deepy.core.comp_graph import ComputationalGraph
model = graph.compile(blocks=[self])
model.load_params(path, exclude_free_params=exclude... | def function[load_params, parameter[self, path, exclude_free_params]]:
from relative_module[deepy.core] import module[graph]
constant[
Load parameters to the block.
]
from relative_module[deepy.core.comp_graph] import module[ComputationalGraph]
variable[model] assign[=] call[name... | keyword[def] identifier[load_params] ( identifier[self] , identifier[path] , identifier[exclude_free_params] = keyword[False] ):
keyword[from] identifier[deepy] . identifier[core] keyword[import] identifier[graph]
literal[string]
keyword[from] identifier[deepy] . identifier[core] . id... | def load_params(self, path, exclude_free_params=False):
from deepy.core import graph
'\n Load parameters to the block.\n '
from deepy.core.comp_graph import ComputationalGraph
model = graph.compile(blocks=[self])
model.load_params(path, exclude_free_params=exclude_free_params) |
def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite"... | def function[_repair, parameter[record]]:
constant[Repair a corrupted IterationRecord with a specific known issue.]
variable[output_records] assign[=] call[name[record].get, parameter[constant[output_records]]]
if <ast.BoolOp object at 0x7da18f09f220> begin[:]
variable[birdsite_r... | keyword[def] identifier[_repair] ( identifier[record] : identifier[Dict] [ identifier[str] , identifier[Any] ])-> identifier[Dict] [ identifier[str] , identifier[Any] ]:
literal[string]
identifier[output_records] = identifier[record] . identifier[get] ( literal[string] )
keyword[if] identifier[record... | def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get('output_records')
if record.get('_type', None) == 'IterationRecord' and output_records is not None:
birdsite_record = output_records.get('birdsite'... |
def team(self, name=None, id=None, is_hidden=False, **kwargs):
"""
Team of KE-chain.
Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id.
:param name: (optional) team name to filter
:type name: basestring or None
:param id: (optional)... | def function[team, parameter[self, name, id, is_hidden]]:
constant[
Team of KE-chain.
Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id.
:param name: (optional) team name to filter
:type name: basestring or None
:param id: (optional... | keyword[def] identifier[team] ( identifier[self] , identifier[name] = keyword[None] , identifier[id] = keyword[None] , identifier[is_hidden] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[_teams] = identifier[self] . identifier[teams] ( identifier[name] = identifier[name] , i... | def team(self, name=None, id=None, is_hidden=False, **kwargs):
"""
Team of KE-chain.
Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id.
:param name: (optional) team name to filter
:type name: basestring or None
:param id: (optional) id ... |
def __hardparse(self,meterPos,pos_i=None,slot_i=None,num_slots=None,all_positions=None,parse=None):
import prosodic as p
#if meterPos.slots[0].i<2:
# print meterPos.slots[0].word
#print meterPos,pos_i,slot_i,num_slots,all_positions
#prevpos=all_positions[pos_i-1]
#print pos_i, meterPos, prevpos, pos_i,pos_... | def function[__hardparse, parameter[self, meterPos, pos_i, slot_i, num_slots, all_positions, parse]]:
import module[prosodic] as alias[p]
if compare[constant[.] in name[self].name] begin[:]
if <ast.BoolOp object at 0x7da20c6e7be0> begin[:]
return[constant[0]]
vari... | keyword[def] identifier[__hardparse] ( identifier[self] , identifier[meterPos] , identifier[pos_i] = keyword[None] , identifier[slot_i] = keyword[None] , identifier[num_slots] = keyword[None] , identifier[all_positions] = keyword[None] , identifier[parse] = keyword[None] ):
keyword[import] identifier[prosodic] k... | def __hardparse(self, meterPos, pos_i=None, slot_i=None, num_slots=None, all_positions=None, parse=None):
import prosodic as p #if meterPos.slots[0].i<2:
# print meterPos.slots[0].word
#print meterPos,pos_i,slot_i,num_slots,all_positions
#prevpos=all_positions[pos_i-1]
#print pos_i, meterPos, prevp... |
def latex(self, force=False):
"""
Build PDF documentation.
"""
if sys.platform == 'win32':
sys.stderr.write('latex build has not been tested on windows\n')
else:
ret_code = self._sphinx_build('latex')
os.chdir(os.path.join(BUILD_PATH, 'latex'))... | def function[latex, parameter[self, force]]:
constant[
Build PDF documentation.
]
if compare[name[sys].platform equal[==] constant[win32]] begin[:]
call[name[sys].stderr.write, parameter[constant[latex build has not been tested on windows
]]] | keyword[def] identifier[latex] ( identifier[self] , identifier[force] = keyword[False] ):
literal[string]
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] )
keyword[else] :
... | def latex(self, force=False):
"""
Build PDF documentation.
"""
if sys.platform == 'win32':
sys.stderr.write('latex build has not been tested on windows\n') # depends on [control=['if'], data=[]]
else:
ret_code = self._sphinx_build('latex')
os.chdir(os.path.join(BUILD... |
def iter_successors(self, graph, orig, branch, turn, tick, *, forward=None):
"""Iterate over successors of a given origin node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.successors[graph, orig], branch, turn, tick)[0]
return
if forward ... | def function[iter_successors, parameter[self, graph, orig, branch, turn, tick]]:
constant[Iterate over successors of a given origin node at a given time.]
if name[self].db._no_kc begin[:]
<ast.YieldFrom object at 0x7da1b0ba7010>
return[None]
if compare[name[forward] is co... | keyword[def] identifier[iter_successors] ( identifier[self] , identifier[graph] , identifier[orig] , identifier[branch] , identifier[turn] , identifier[tick] ,*, identifier[forward] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[db] . identifier[_no_kc] :
... | def iter_successors(self, graph, orig, branch, turn, tick, *, forward=None):
"""Iterate over successors of a given origin node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.successors[graph, orig], branch, turn, tick)[0]
return # depends on [control=['if'], data... |
def load(fileobj):
"""Load the submission from a file-like object
:param fileobj: File-like object
:return: the loaded submission
"""
with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
submission = Submission(metadata=json.loads(z.readline()))
for line ... | def function[load, parameter[fileobj]]:
constant[Load the submission from a file-like object
:param fileobj: File-like object
:return: the loaded submission
]
with call[name[gzip].GzipFile, parameter[]] begin[:]
variable[submission] assign[=] call[name[Submission... | keyword[def] identifier[load] ( identifier[fileobj] ):
literal[string]
keyword[with] identifier[gzip] . identifier[GzipFile] ( identifier[fileobj] = identifier[fileobj] , identifier[mode] = literal[string] ) keyword[as] identifier[z] :
identifier[submission] = identifier[Submission] ... | def load(fileobj):
"""Load the submission from a file-like object
:param fileobj: File-like object
:return: the loaded submission
"""
with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
submission = Submission(metadata=json.loads(z.readline()))
for line in z:
... |
def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None,
non_blocking=False,
prepare_batch=_prepare_batch
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computation... | def function[create_supervised_tbptt_trainer, parameter[model, optimizer, loss_fn, tbtt_step, dim, device, non_blocking, prepare_batch]]:
constant[Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requir... | keyword[def] identifier[create_supervised_tbptt_trainer] (
identifier[model] ,
identifier[optimizer] ,
identifier[loss_fn] ,
identifier[tbtt_step] ,
identifier[dim] = literal[int] ,
identifier[device] = keyword[None] ,
identifier[non_blocking] = keyword[False] ,
identifier[prepare_batch] = identifier[_prepare... | def create_supervised_tbptt_trainer(model, optimizer, loss_fn, tbtt_step, dim=0, device=None, non_blocking=False, prepare_batch=_prepare_batch):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requires ... |
def run_cell(self, cell):
"""Run the Cell code using the IPython globals and locals
Args:
cell (str): Python code to be executed
"""
globals = self.ipy_shell.user_global_ns
locals = self.ipy_shell.user_ns
globals.update({
"__ipy_scope__": None,
... | def function[run_cell, parameter[self, cell]]:
constant[Run the Cell code using the IPython globals and locals
Args:
cell (str): Python code to be executed
]
variable[globals] assign[=] name[self].ipy_shell.user_global_ns
variable[locals] assign[=] name[self].ipy_she... | keyword[def] identifier[run_cell] ( identifier[self] , identifier[cell] ):
literal[string]
identifier[globals] = identifier[self] . identifier[ipy_shell] . identifier[user_global_ns]
identifier[locals] = identifier[self] . identifier[ipy_shell] . identifier[user_ns]
identifier[g... | def run_cell(self, cell):
"""Run the Cell code using the IPython globals and locals
Args:
cell (str): Python code to be executed
"""
globals = self.ipy_shell.user_global_ns
locals = self.ipy_shell.user_ns
globals.update({'__ipy_scope__': None})
try:
with redirect... |
def css_files(self):
''' The CSS files in the BokehJS directory.
'''
bokehjsdir = self.bokehjsdir()
js_files = []
for root, dirnames, files in os.walk(bokehjsdir):
for fname in files:
if fname.endswith(".css"):
js_files.append(join... | def function[css_files, parameter[self]]:
constant[ The CSS files in the BokehJS directory.
]
variable[bokehjsdir] assign[=] call[name[self].bokehjsdir, parameter[]]
variable[js_files] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da207f9b910>, <ast.Name object at 0... | keyword[def] identifier[css_files] ( identifier[self] ):
literal[string]
identifier[bokehjsdir] = identifier[self] . identifier[bokehjsdir] ()
identifier[js_files] =[]
keyword[for] identifier[root] , identifier[dirnames] , identifier[files] keyword[in] identifier[os] . identifi... | def css_files(self):
""" The CSS files in the BokehJS directory.
"""
bokehjsdir = self.bokehjsdir()
js_files = []
for (root, dirnames, files) in os.walk(bokehjsdir):
for fname in files:
if fname.endswith('.css'):
js_files.append(join(root, fname)) # depends ... |
def import_global(node: Node, key: str, path: Any):
"""Import passed module, class, function full name and stores it to node's globals"""
node.node_globals[key] = import_path(path) | def function[import_global, parameter[node, key, path]]:
constant[Import passed module, class, function full name and stores it to node's globals]
call[name[node].node_globals][name[key]] assign[=] call[name[import_path], parameter[name[path]]] | keyword[def] identifier[import_global] ( identifier[node] : identifier[Node] , identifier[key] : identifier[str] , identifier[path] : identifier[Any] ):
literal[string]
identifier[node] . identifier[node_globals] [ identifier[key] ]= identifier[import_path] ( identifier[path] ) | def import_global(node: Node, key: str, path: Any):
"""Import passed module, class, function full name and stores it to node's globals"""
node.node_globals[key] = import_path(path) |
def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
""... | def function[get_status_from_async, parameter[self, response]]:
constant[Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
... | keyword[def] identifier[get_status_from_async] ( identifier[self] , identifier[response] ):
literal[string]
identifier[self] . identifier[_raise_if_bad_http_status_and_method] ( identifier[response] )
keyword[if] identifier[self] . identifier[_is_empty] ( identifier[response] ):
... | def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
"""
... |
def check_assumptions(
self, training_df, advice=True, show_plots=False, p_value_threshold=0.01, plot_n_bootstraps=10
):
"""
Use this function to test the proportional hazards assumption. See usage example at
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%2... | def function[check_assumptions, parameter[self, training_df, advice, show_plots, p_value_threshold, plot_n_bootstraps]]:
constant[
Use this function to test the proportional hazards assumption. See usage example at
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazar... | keyword[def] identifier[check_assumptions] (
identifier[self] , identifier[training_df] , identifier[advice] = keyword[True] , identifier[show_plots] = keyword[False] , identifier[p_value_threshold] = literal[int] , identifier[plot_n_bootstraps] = literal[int]
):
literal[string]
keyword[if] key... | def check_assumptions(self, training_df, advice=True, show_plots=False, p_value_threshold=0.01, plot_n_bootstraps=10):
"""
Use this function to test the proportional hazards assumption. See usage example at
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumpti... |
def yosys_area_delay(library, abc_cmd=None, block=None):
""" Synthesize with Yosys and return estimate of area and delay.
:param library: stdcell library file to target in liberty format
:param abc_cmd: string of commands for yosys to pass to abc for synthesis
:param block: pyrtl block to analyze
:... | def function[yosys_area_delay, parameter[library, abc_cmd, block]]:
constant[ Synthesize with Yosys and return estimate of area and delay.
:param library: stdcell library file to target in liberty format
:param abc_cmd: string of commands for yosys to pass to abc for synthesis
:param block: pyrtl b... | keyword[def] identifier[yosys_area_delay] ( identifier[library] , identifier[abc_cmd] = keyword[None] , identifier[block] = keyword[None] ):
literal[string]
keyword[if] identifier[abc_cmd] keyword[is] keyword[None] :
identifier[abc_cmd] = literal[string]
keyword[else] :
ide... | def yosys_area_delay(library, abc_cmd=None, block=None):
""" Synthesize with Yosys and return estimate of area and delay.
:param library: stdcell library file to target in liberty format
:param abc_cmd: string of commands for yosys to pass to abc for synthesis
:param block: pyrtl block to analyze
:... |
def check_mac(original_mac):
'''
Checks the format of a MAC address and returns it without double-colons and in capital letters, if it is correct. Otherwise it returns None.
* it accepts the format of the double colons and a single hex string
'''
mac = (original_mac.upper()).strip()
parts = mac.... | def function[check_mac, parameter[original_mac]]:
constant[
Checks the format of a MAC address and returns it without double-colons and in capital letters, if it is correct. Otherwise it returns None.
* it accepts the format of the double colons and a single hex string
]
variable[mac] assign... | keyword[def] identifier[check_mac] ( identifier[original_mac] ):
literal[string]
identifier[mac] =( identifier[original_mac] . identifier[upper] ()). identifier[strip] ()
identifier[parts] = identifier[mac] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[parts] )... | def check_mac(original_mac):
"""
Checks the format of a MAC address and returns it without double-colons and in capital letters, if it is correct. Otherwise it returns None.
* it accepts the format of the double colons and a single hex string
"""
mac = original_mac.upper().strip()
parts = mac.sp... |
def _generateFind(self, **kwargs):
"""Generator which yields matches on AXChildren."""
for needle in self._generateChildren():
if needle._match(**kwargs):
yield needle | def function[_generateFind, parameter[self]]:
constant[Generator which yields matches on AXChildren.]
for taget[name[needle]] in starred[call[name[self]._generateChildren, parameter[]]] begin[:]
if call[name[needle]._match, parameter[]] begin[:]
<ast.Yield object ... | keyword[def] identifier[_generateFind] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[needle] keyword[in] identifier[self] . identifier[_generateChildren] ():
keyword[if] identifier[needle] . identifier[_match] (** identifier[kwargs] ):
... | def _generateFind(self, **kwargs):
"""Generator which yields matches on AXChildren."""
for needle in self._generateChildren():
if needle._match(**kwargs):
yield needle # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['needle']] |
def get_new_locations(self, urls):
"""Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL addresses
:returns: ... | def function[get_new_locations, parameter[self, urls]]:
constant[Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL a... | keyword[def] identifier[get_new_locations] ( identifier[self] , identifier[urls] ):
literal[string]
identifier[seen] = identifier[set] ( identifier[urls] )
keyword[for] identifier[i] keyword[in] identifier[urls] :
keyword[for] identifier[k] keyword[in] identifier[self] .... | def get_new_locations(self, urls):
"""Get valid location header values for all given URLs.
The returned values are new, that is: they do not repeat any
value contained in the original input. Only unique values
are yielded.
:param urls: a list of URL addresses
:returns: vali... |
def __shpFileLength(self):
"""Calculates the file length of the shp file."""
# Start with header length
size = 100
# Calculate size of all shapes
for s in self._shapes:
# Add in record header and shape type fields
size += 12
# nParts an... | def function[__shpFileLength, parameter[self]]:
constant[Calculates the file length of the shp file.]
variable[size] assign[=] constant[100]
for taget[name[s]] in starred[name[self]._shapes] begin[:]
<ast.AugAssign object at 0x7da1b084f340>
if call[name[hasattr], paramete... | keyword[def] identifier[__shpFileLength] ( identifier[self] ):
literal[string]
identifier[size] = literal[int]
keyword[for] identifier[s] keyword[in] identifier[self] . identifier[_shapes] :
identifier[size] += literal[int]
... | def __shpFileLength(self):
"""Calculates the file length of the shp file.""" # Start with header length
size = 100 # Calculate size of all shapes
for s in self._shapes: # Add in record header and shape type fields
size += 12 # nParts and nPoints do not apply to all shapes
#if self.shapeT... |
def infer(args):
"""
%prog infer scaffolds.fasta genome.fasta
Infer where the components are in the genome. This function is rarely used,
but can be useful when distributor does not ship an AGP file.
"""
from jcvi.apps.grid import WriteJobs
from jcvi.formats.bed import sort
p = OptionP... | def function[infer, parameter[args]]:
constant[
%prog infer scaffolds.fasta genome.fasta
Infer where the components are in the genome. This function is rarely used,
but can be useful when distributor does not ship an AGP file.
]
from relative_module[jcvi.apps.grid] import module[WriteJobs]
... | keyword[def] identifier[infer] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[apps] . identifier[grid] keyword[import] identifier[WriteJobs]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[bed] keyword[import] identifier[sort]
identifi... | def infer(args):
"""
%prog infer scaffolds.fasta genome.fasta
Infer where the components are in the genome. This function is rarely used,
but can be useful when distributor does not ship an AGP file.
"""
from jcvi.apps.grid import WriteJobs
from jcvi.formats.bed import sort
p = OptionPa... |
def radianceSpectrum(Omegas,AbsorptionCoefficient,Environment={'l':100.,'T':296.},
File=None, Format='%e %e', Wavenumber=None):
"""
INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (re... | def function[radianceSpectrum, parameter[Omegas, AbsorptionCoefficient, Environment, File, Format, Wavenumber]]:
constant[
INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (required)
Environmen... | keyword[def] identifier[radianceSpectrum] ( identifier[Omegas] , identifier[AbsorptionCoefficient] , identifier[Environment] ={ literal[string] : literal[int] , literal[string] : literal[int] },
identifier[File] = keyword[None] , identifier[Format] = literal[string] , identifier[Wavenumber] = keyword[None] ):
l... | def radianceSpectrum(Omegas, AbsorptionCoefficient, Environment={'l': 100.0, 'T': 296.0}, File=None, Format='%e %e', Wavenumber=None):
"""
INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (required)
... |
def exit(code=0, text=''):
"""Exit and print text (if defined) to stderr if code > 0 or stdout
otherwise.
>>> exit(code=1, text='Invalid directory path')
"""
if not isinstance(text, basestring_type):
text = unicode_type(text)
if code > 0:
if text:
if not isinstance... | def function[exit, parameter[code, text]]:
constant[Exit and print text (if defined) to stderr if code > 0 or stdout
otherwise.
>>> exit(code=1, text='Invalid directory path')
]
if <ast.UnaryOp object at 0x7da20e9618a0> begin[:]
variable[text] assign[=] call[name[unicode_t... | keyword[def] identifier[exit] ( identifier[code] = literal[int] , identifier[text] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[text] , identifier[basestring_type] ):
identifier[text] = identifier[unicode_type] ( identifier[text] )
keywor... | def exit(code=0, text=''):
"""Exit and print text (if defined) to stderr if code > 0 or stdout
otherwise.
>>> exit(code=1, text='Invalid directory path')
"""
if not isinstance(text, basestring_type):
text = unicode_type(text) # depends on [control=['if'], data=[]]
if code > 0:
... |
def generate_parameters_validator(api_path, path_definition, parameters,
context, **kwargs):
"""
Generates a validator function to validate.
- request.path against the path parameters.
- request.query against the query parameters.
- request.headers against the head... | def function[generate_parameters_validator, parameter[api_path, path_definition, parameters, context]]:
constant[
Generates a validator function to validate.
- request.path against the path parameters.
- request.query against the query parameters.
- request.headers against the header parameters... | keyword[def] identifier[generate_parameters_validator] ( identifier[api_path] , identifier[path_definition] , identifier[parameters] ,
identifier[context] ,** identifier[kwargs] ):
literal[string]
identifier[validators] = identifier[ValidationDict] ()
identifier[path_level_parameters] = ide... | def generate_parameters_validator(api_path, path_definition, parameters, context, **kwargs):
"""
Generates a validator function to validate.
- request.path against the path parameters.
- request.query against the query parameters.
- request.headers against the header parameters.
- TODO: request... |
def simxReadCollision(clientID, collisionObjectHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
collisionState = ct.c_ubyte()
return c_ReadCollision(clientID, collisionObjectHandle, ct.byref(collisionState), operationMode), bool(co... | def function[simxReadCollision, parameter[clientID, collisionObjectHandle, operationMode]]:
constant[
Please have a look at the function description/documentation in the V-REP user manual
]
variable[collisionState] assign[=] call[name[ct].c_ubyte, parameter[]]
return[tuple[[<ast.Call object ... | keyword[def] identifier[simxReadCollision] ( identifier[clientID] , identifier[collisionObjectHandle] , identifier[operationMode] ):
literal[string]
identifier[collisionState] = identifier[ct] . identifier[c_ubyte] ()
keyword[return] identifier[c_ReadCollision] ( identifier[clientID] , identifier[col... | def simxReadCollision(clientID, collisionObjectHandle, operationMode):
"""
Please have a look at the function description/documentation in the V-REP user manual
"""
collisionState = ct.c_ubyte()
return (c_ReadCollision(clientID, collisionObjectHandle, ct.byref(collisionState), operationMode), bool(c... |
def add(self, fn, name=None):
"""Add a function that the dispatcher will know about.
fn -- a callable object
name -- optional alias for the function
"""
if not name:
name = fn.__name__
self.functions[name] = fn | def function[add, parameter[self, fn, name]]:
constant[Add a function that the dispatcher will know about.
fn -- a callable object
name -- optional alias for the function
]
if <ast.UnaryOp object at 0x7da1b09122c0> begin[:]
variable[name] assign[=] name[fn].__na... | keyword[def] identifier[add] ( identifier[self] , identifier[fn] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[name] :
identifier[name] = identifier[fn] . identifier[__name__]
identifier[self] . identifier[functions] [ identifier[... | def add(self, fn, name=None):
"""Add a function that the dispatcher will know about.
fn -- a callable object
name -- optional alias for the function
"""
if not name:
name = fn.__name__ # depends on [control=['if'], data=[]]
self.functions[name] = fn |
def returnValueList(self, key_list, last=False):
'''Return a list of key values for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty. If a key is missing, then
that entry in the list is None.
Example of u... | def function[returnValueList, parameter[self, key_list, last]]:
constant[Return a list of key values for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty. If a key is missing, then
that entry in the list is None.
... | keyword[def] identifier[returnValueList] ( identifier[self] , identifier[key_list] , identifier[last] = keyword[False] ):
literal[string]
identifier[result] =[]
identifier[row] = identifier[self] . identifier[returnOneEntry] ( identifier[last] = identifier[last] )
keyword[if] key... | def returnValueList(self, key_list, last=False):
"""Return a list of key values for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty. If a key is missing, then
that entry in the list is None.
Example of use:
... |
def modify_qc(self, qc_id=None, **kwargs):
'''
modify_qc(self, qc_id=None, **kwargs)
Modify a Quality Criteria
:Parameters:
* *qc_id* (`string`) -- The Quality criteria identifier
'''
if qc_id:
request_data = {'id': qc_id}
request_data.u... | def function[modify_qc, parameter[self, qc_id]]:
constant[
modify_qc(self, qc_id=None, **kwargs)
Modify a Quality Criteria
:Parameters:
* *qc_id* (`string`) -- The Quality criteria identifier
]
if name[qc_id] begin[:]
variable[request_data] assi... | keyword[def] identifier[modify_qc] ( identifier[self] , identifier[qc_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[qc_id] :
identifier[request_data] ={ literal[string] : identifier[qc_id] }
identifier[request_data] . identifier[upda... | def modify_qc(self, qc_id=None, **kwargs):
"""
modify_qc(self, qc_id=None, **kwargs)
Modify a Quality Criteria
:Parameters:
* *qc_id* (`string`) -- The Quality criteria identifier
"""
if qc_id:
request_data = {'id': qc_id}
request_data.update(**kwargs)
... |
def record_diff(old, new):
"""Return a JSON-compatible structure capable turn the `new` record back
into the `old` record. The parameters must be structures compatible with
json.dumps *or* strings compatible with json.loads. Note that by design,
`old == record_patch(new, record_diff(old, new))`"""
o... | def function[record_diff, parameter[old, new]]:
constant[Return a JSON-compatible structure capable turn the `new` record back
into the `old` record. The parameters must be structures compatible with
json.dumps *or* strings compatible with json.loads. Note that by design,
`old == record_patch(new, r... | keyword[def] identifier[record_diff] ( identifier[old] , identifier[new] ):
literal[string]
identifier[old] , identifier[new] = identifier[_norm_json_params] ( identifier[old] , identifier[new] )
keyword[return] identifier[json_delta] . identifier[diff] ( identifier[new] , identifier[old] , identifie... | def record_diff(old, new):
"""Return a JSON-compatible structure capable turn the `new` record back
into the `old` record. The parameters must be structures compatible with
json.dumps *or* strings compatible with json.loads. Note that by design,
`old == record_patch(new, record_diff(old, new))`"""
(... |
def chunk(self, maxSize):
"""Splits the `Collection` into _maxSize_ size or smaller `Collections`
# Parameters
_maxSize_ : `int`
> The maximum number of elements in a retuned `Collection`
# Returns
`list [Collection]`
> A list of `Collections` that if all m... | def function[chunk, parameter[self, maxSize]]:
constant[Splits the `Collection` into _maxSize_ size or smaller `Collections`
# Parameters
_maxSize_ : `int`
> The maximum number of elements in a retuned `Collection`
# Returns
`list [Collection]`
> A list of ... | keyword[def] identifier[chunk] ( identifier[self] , identifier[maxSize] ):
literal[string]
identifier[chunks] =[]
identifier[currentSize] = identifier[maxSize] + literal[int]
keyword[for] identifier[i] keyword[in] identifier[self] :
keyword[if] identifier[current... | def chunk(self, maxSize):
"""Splits the `Collection` into _maxSize_ size or smaller `Collections`
# Parameters
_maxSize_ : `int`
> The maximum number of elements in a retuned `Collection`
# Returns
`list [Collection]`
> A list of `Collections` that if all merge... |
def fem(ab, off, angle, zsrc, zrec, lsrc, lrec, depth, freq, etaH, etaV, zetaH,
zetaV, xdirect, isfullspace, ht, htarg, use_ne_eval, msrc, mrec,
loop_freq, loop_off, conv=True):
r"""Return the electromagnetic frequency-domain response.
This function is called from one of the above modelling rou... | def function[fem, parameter[ab, off, angle, zsrc, zrec, lsrc, lrec, depth, freq, etaH, etaV, zetaH, zetaV, xdirect, isfullspace, ht, htarg, use_ne_eval, msrc, mrec, loop_freq, loop_off, conv]]:
constant[Return the electromagnetic frequency-domain response.
This function is called from one of the above mode... | keyword[def] identifier[fem] ( identifier[ab] , identifier[off] , identifier[angle] , identifier[zsrc] , identifier[zrec] , identifier[lsrc] , identifier[lrec] , identifier[depth] , identifier[freq] , identifier[etaH] , identifier[etaV] , identifier[zetaH] ,
identifier[zetaV] , identifier[xdirect] , identifier[isful... | def fem(ab, off, angle, zsrc, zrec, lsrc, lrec, depth, freq, etaH, etaV, zetaH, zetaV, xdirect, isfullspace, ht, htarg, use_ne_eval, msrc, mrec, loop_freq, loop_off, conv=True):
"""Return the electromagnetic frequency-domain response.
This function is called from one of the above modelling routines. No
inp... |
def _load(formula):
'''
Generates a list of salt://<formula>/defaults.(json|yaml) files
and fetches them from the Salt master.
Returns first defaults file as python dict.
'''
# Compute possibilities
_mk_client()
paths = []
for ext in ('yaml', 'json'):
source_url = salt.util... | def function[_load, parameter[formula]]:
constant[
Generates a list of salt://<formula>/defaults.(json|yaml) files
and fetches them from the Salt master.
Returns first defaults file as python dict.
]
call[name[_mk_client], parameter[]]
variable[paths] assign[=] list[[]]
... | keyword[def] identifier[_load] ( identifier[formula] ):
literal[string]
identifier[_mk_client] ()
identifier[paths] =[]
keyword[for] identifier[ext] keyword[in] ( literal[string] , literal[string] ):
identifier[source_url] = identifier[salt] . identifier[utils] . identifier[url] ... | def _load(formula):
"""
Generates a list of salt://<formula>/defaults.(json|yaml) files
and fetches them from the Salt master.
Returns first defaults file as python dict.
"""
# Compute possibilities
_mk_client()
paths = []
for ext in ('yaml', 'json'):
source_url = salt.utils... |
def keyPressEvent( self, event ):
"""
Overloads the keyPressEvent method to support backtab operations.
:param event | <QKeyPressEvent>
"""
if ( event.key() == Qt.Key_Backtab ):
self.unindentSelection()
else:
super(XScintilla... | def function[keyPressEvent, parameter[self, event]]:
constant[
Overloads the keyPressEvent method to support backtab operations.
:param event | <QKeyPressEvent>
]
if compare[call[name[event].key, parameter[]] equal[==] name[Qt].Key_Backtab] begin[:]
... | keyword[def] identifier[keyPressEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] ( identifier[event] . identifier[key] ()== identifier[Qt] . identifier[Key_Backtab] ):
identifier[self] . identifier[unindentSelection] ()
keyword[else] :
... | def keyPressEvent(self, event):
"""
Overloads the keyPressEvent method to support backtab operations.
:param event | <QKeyPressEvent>
"""
if event.key() == Qt.Key_Backtab:
self.unindentSelection() # depends on [control=['if'], data=[]]
else:
super(XScin... |
def lock(self, timeout=10):
"""
Advisory lock.
Use to ensure that only one LocalSyncClient is working on the Target at the same time.
"""
logger.debug("Locking %s", self.lock_file)
if not os.path.exists(self.lock_file):
self.ensure_path(self.lock_file)
... | def function[lock, parameter[self, timeout]]:
constant[
Advisory lock.
Use to ensure that only one LocalSyncClient is working on the Target at the same time.
]
call[name[logger].debug, parameter[constant[Locking %s], name[self].lock_file]]
if <ast.UnaryOp object at 0x7da1... | keyword[def] identifier[lock] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[self] . identifier[lock_file] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] (... | def lock(self, timeout=10):
"""
Advisory lock.
Use to ensure that only one LocalSyncClient is working on the Target at the same time.
"""
logger.debug('Locking %s', self.lock_file)
if not os.path.exists(self.lock_file):
self.ensure_path(self.lock_file)
with open(self.... |
def execute(self, source, interval, input_plate_value):
"""
Execute the tool over the given time interval.
:param source: The source stream
:param interval: The time interval
:param input_plate_value: The value of the plate where data comes from (can be None)
:type sourc... | def function[execute, parameter[self, source, interval, input_plate_value]]:
constant[
Execute the tool over the given time interval.
:param source: The source stream
:param interval: The time interval
:param input_plate_value: The value of the plate where data comes from (can b... | keyword[def] identifier[execute] ( identifier[self] , identifier[source] , identifier[interval] , identifier[input_plate_value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[interval] , identifier[TimeInterval] ):
keyword[raise] identifier[TypeError... | def execute(self, source, interval, input_plate_value):
"""
Execute the tool over the given time interval.
:param source: The source stream
:param interval: The time interval
:param input_plate_value: The value of the plate where data comes from (can be None)
:type source: S... |
def _get_data_from_bigquery(self, queries):
"""Get data from bigquery table or query."""
all_df = []
for query in queries:
all_df.append(query.execute().result().to_dataframe())
df = pd.concat(all_df, ignore_index=True)
return df | def function[_get_data_from_bigquery, parameter[self, queries]]:
constant[Get data from bigquery table or query.]
variable[all_df] assign[=] list[[]]
for taget[name[query]] in starred[name[queries]] begin[:]
call[name[all_df].append, parameter[call[call[call[name[query].execute, ... | keyword[def] identifier[_get_data_from_bigquery] ( identifier[self] , identifier[queries] ):
literal[string]
identifier[all_df] =[]
keyword[for] identifier[query] keyword[in] identifier[queries] :
identifier[all_df] . identifier[append] ( identifier[query] . identifier[execute] (). identifi... | def _get_data_from_bigquery(self, queries):
"""Get data from bigquery table or query."""
all_df = []
for query in queries:
all_df.append(query.execute().result().to_dataframe()) # depends on [control=['for'], data=['query']]
df = pd.concat(all_df, ignore_index=True)
return df |
def closenessScores(self, expValues, actValues, fractional=True):
"""
See the function description in base.py
"""
# Compute the percent error in log space
if expValues[0] > 0:
expValue = math.log10(expValues[0])
else:
expValue = self.minScaledValue
if actValues [0] > 0:
... | def function[closenessScores, parameter[self, expValues, actValues, fractional]]:
constant[
See the function description in base.py
]
if compare[call[name[expValues]][constant[0]] greater[>] constant[0]] begin[:]
variable[expValue] assign[=] call[name[math].log10, parameter[call[... | keyword[def] identifier[closenessScores] ( identifier[self] , identifier[expValues] , identifier[actValues] , identifier[fractional] = keyword[True] ):
literal[string]
keyword[if] identifier[expValues] [ literal[int] ]> literal[int] :
identifier[expValue] = identifier[math] . identifier[log10... | def closenessScores(self, expValues, actValues, fractional=True):
"""
See the function description in base.py
"""
# Compute the percent error in log space
if expValues[0] > 0:
expValue = math.log10(expValues[0]) # depends on [control=['if'], data=[]]
else:
expValue = self.minSca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.