code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def process_allele(allele_data, dbsnp_data, header, reference):
"""Combine data from multiple lines refering to a single allele.
Returns three items in this order:
(string) concatenated variant sequence (ie allele the genome has)
(string) concatenated reference sequence
(string) start p... | def function[process_allele, parameter[allele_data, dbsnp_data, header, reference]]:
constant[Combine data from multiple lines refering to a single allele.
Returns three items in this order:
(string) concatenated variant sequence (ie allele the genome has)
(string) concatenated reference se... | keyword[def] identifier[process_allele] ( identifier[allele_data] , identifier[dbsnp_data] , identifier[header] , identifier[reference] ):
literal[string]
identifier[start] = identifier[str] ( identifier[int] ( identifier[allele_data] [ literal[int] ][ identifier[header] [ literal[string] ]]))
id... | def process_allele(allele_data, dbsnp_data, header, reference):
"""Combine data from multiple lines refering to a single allele.
Returns three items in this order:
(string) concatenated variant sequence (ie allele the genome has)
(string) concatenated reference sequence
(string) start p... |
def _show_final_paste_message(self, tl_key, no_pasted_cells):
"""Show actually pasted number of cells"""
plural = "" if no_pasted_cells == 1 else _("s")
statustext = _("{ncells} cell{plural} pasted at cell {topleft}").\
format(ncells=no_pasted_cells, plural=plural, topleft=tl_key)
... | def function[_show_final_paste_message, parameter[self, tl_key, no_pasted_cells]]:
constant[Show actually pasted number of cells]
variable[plural] assign[=] <ast.IfExp object at 0x7da1b17224a0>
variable[statustext] assign[=] call[call[name[_], parameter[constant[{ncells} cell{plural} pasted at c... | keyword[def] identifier[_show_final_paste_message] ( identifier[self] , identifier[tl_key] , identifier[no_pasted_cells] ):
literal[string]
identifier[plural] = literal[string] keyword[if] identifier[no_pasted_cells] == literal[int] keyword[else] identifier[_] ( literal[string] )
ide... | def _show_final_paste_message(self, tl_key, no_pasted_cells):
"""Show actually pasted number of cells"""
plural = '' if no_pasted_cells == 1 else _('s')
statustext = _('{ncells} cell{plural} pasted at cell {topleft}').format(ncells=no_pasted_cells, plural=plural, topleft=tl_key)
post_command_event(self.... |
def count(self, signature = None):
"""
Counts how many crash dumps have been stored in this database.
Optionally filters the count by heuristic signature.
@type signature: object
@param signature: (Optional) Count only the crashes that match
this signature. See L{Cr... | def function[count, parameter[self, signature]]:
constant[
Counts how many crash dumps have been stored in this database.
Optionally filters the count by heuristic signature.
@type signature: object
@param signature: (Optional) Count only the crashes that match
this... | keyword[def] identifier[count] ( identifier[self] , identifier[signature] = keyword[None] ):
literal[string]
identifier[query] = identifier[self] . identifier[_session] . identifier[query] ( identifier[CrashDTO] . identifier[id] )
keyword[if] identifier[signature] :
identifie... | def count(self, signature=None):
"""
Counts how many crash dumps have been stored in this database.
Optionally filters the count by heuristic signature.
@type signature: object
@param signature: (Optional) Count only the crashes that match
this signature. See L{Crash.si... |
def blockSelectionSignals( self, state ):
"""
Sets the state for the seleciton finished signal. When it \
is set to True, it will emit the signal. This is used \
internally to control selection signal propogation, so \
should not really be called unless you know why you are \
... | def function[blockSelectionSignals, parameter[self, state]]:
constant[
Sets the state for the seleciton finished signal. When it is set to True, it will emit the signal. This is used internally to control selection signal propogation, so should not really be called unless you ... | keyword[def] identifier[blockSelectionSignals] ( identifier[self] , identifier[state] ):
literal[string]
keyword[if] ( identifier[self] . identifier[_selectionSignalsBlocked] == identifier[state] ):
keyword[return]
identifier[self] . identifier[_selectionSignalsBlocked] = id... | def blockSelectionSignals(self, state):
"""
Sets the state for the seleciton finished signal. When it is set to True, it will emit the signal. This is used internally to control selection signal propogation, so should not really be called unless you know why you are callin... |
def from_line(cls, line):
""":return: New RefLogEntry instance from the given revlog line.
:param line: line bytes without trailing newline
:raise ValueError: If line could not be parsed"""
line = line.decode(defenc)
fields = line.split('\t', 1)
if len(fields) == 1:
... | def function[from_line, parameter[cls, line]]:
constant[:return: New RefLogEntry instance from the given revlog line.
:param line: line bytes without trailing newline
:raise ValueError: If line could not be parsed]
variable[line] assign[=] call[name[line].decode, parameter[name[defenc]]]... | keyword[def] identifier[from_line] ( identifier[cls] , identifier[line] ):
literal[string]
identifier[line] = identifier[line] . identifier[decode] ( identifier[defenc] )
identifier[fields] = identifier[line] . identifier[split] ( literal[string] , literal[int] )
keyword[if] iden... | def from_line(cls, line):
""":return: New RefLogEntry instance from the given revlog line.
:param line: line bytes without trailing newline
:raise ValueError: If line could not be parsed"""
line = line.decode(defenc)
fields = line.split('\t', 1)
if len(fields) == 1:
(info, msg) =... |
def all_regions(self):
"""Get a tuple of all chromosome, start and end regions.
"""
regions = []
for sq in self._bam.header["SQ"]:
regions.append((sq["SN"], 1, int(sq["LN"])))
return regions | def function[all_regions, parameter[self]]:
constant[Get a tuple of all chromosome, start and end regions.
]
variable[regions] assign[=] list[[]]
for taget[name[sq]] in starred[call[name[self]._bam.header][constant[SQ]]] begin[:]
call[name[regions].append, parameter[tuple... | keyword[def] identifier[all_regions] ( identifier[self] ):
literal[string]
identifier[regions] =[]
keyword[for] identifier[sq] keyword[in] identifier[self] . identifier[_bam] . identifier[header] [ literal[string] ]:
identifier[regions] . identifier[append] (( identifier[sq... | def all_regions(self):
"""Get a tuple of all chromosome, start and end regions.
"""
regions = []
for sq in self._bam.header['SQ']:
regions.append((sq['SN'], 1, int(sq['LN']))) # depends on [control=['for'], data=['sq']]
return regions |
def parse_transform(transform_str):
"""Converts a valid SVG transformation string into a 3x3 matrix.
If the string is empty or null, this returns a 3x3 identity matrix"""
if not transform_str:
return np.identity(3)
elif not isinstance(transform_str, str):
raise TypeError('Must provide a ... | def function[parse_transform, parameter[transform_str]]:
constant[Converts a valid SVG transformation string into a 3x3 matrix.
If the string is empty or null, this returns a 3x3 identity matrix]
if <ast.UnaryOp object at 0x7da1b2344f40> begin[:]
return[call[name[np].identity, parameter[cons... | keyword[def] identifier[parse_transform] ( identifier[transform_str] ):
literal[string]
keyword[if] keyword[not] identifier[transform_str] :
keyword[return] identifier[np] . identifier[identity] ( literal[int] )
keyword[elif] keyword[not] identifier[isinstance] ( identifier[transform_str... | def parse_transform(transform_str):
"""Converts a valid SVG transformation string into a 3x3 matrix.
If the string is empty or null, this returns a 3x3 identity matrix"""
if not transform_str:
return np.identity(3) # depends on [control=['if'], data=[]]
elif not isinstance(transform_str, str):
... |
def get_suitable_slot_for_duplicate(self, src_slot):
"""Returns the suitable position for a duplicate analysis, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
is a slot defined for a... | def function[get_suitable_slot_for_duplicate, parameter[self, src_slot]]:
constant[Returns the suitable position for a duplicate analysis, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
... | keyword[def] identifier[get_suitable_slot_for_duplicate] ( identifier[self] , identifier[src_slot] ):
literal[string]
identifier[slot_from] = identifier[to_int] ( identifier[src_slot] , literal[int] )
keyword[if] identifier[slot_from] < literal[int] :
keyword[return] - litera... | def get_suitable_slot_for_duplicate(self, src_slot):
"""Returns the suitable position for a duplicate analysis, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
is a slot defined for a dup... |
def release(version):
"""Tags all submodules for a new release.
Ensures that git tags, as well as the version.py files in each submodule, agree and that the
new version is strictly greater than the current version. Will fail if the new version
is not an increment (following PEP 440). Creates a new git ... | def function[release, parameter[version]]:
constant[Tags all submodules for a new release.
Ensures that git tags, as well as the version.py files in each submodule, agree and that the
new version is strictly greater than the current version. Will fail if the new version
is not an increment (followi... | keyword[def] identifier[release] ( identifier[version] ):
literal[string]
identifier[check_new_version] ( identifier[version] )
identifier[set_new_version] ( identifier[version] )
identifier[commit_new_version] ( identifier[version] )
identifier[set_git_tag] ( identifier[version] ) | def release(version):
"""Tags all submodules for a new release.
Ensures that git tags, as well as the version.py files in each submodule, agree and that the
new version is strictly greater than the current version. Will fail if the new version
is not an increment (following PEP 440). Creates a new git ... |
def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime... | def function[to_dict, parameter[self]]:
constant[Return this message as a dict suitable for json encoding.]
import module[copy]
variable[options] assign[=] call[name[copy].deepcopy, parameter[name[self]._options]]
variable[eta] assign[=] call[call[name[options].get, parameter[constant[task_a... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
keyword[import] identifier[copy]
identifier[options] = identifier[copy] . identifier[deepcopy] ( identifier[self] . identifier[_options] )
identifier[eta] = identifier[options] . identifier[get] ( ... | def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple()) # depends o... |
def make_room_alias(chain_id: ChainID, *suffixes: str) -> str:
"""Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
... | def function[make_room_alias, parameter[chain_id]]:
constant[Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
... | keyword[def] identifier[make_room_alias] ( identifier[chain_id] : identifier[ChainID] ,* identifier[suffixes] : identifier[str] )-> identifier[str] :
literal[string]
identifier[network_name] = identifier[ID_TO_NETWORKNAME] . identifier[get] ( identifier[chain_id] , identifier[str] ( identifier[chain_id] ))... | def make_room_alias(chain_id: ChainID, *suffixes: str) -> str:
"""Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
... |
def list_vm_images_sub(access_token, subscription_id):
'''List VM images in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM images.
'''
endpoint = '... | def function[list_vm_images_sub, parameter[access_token, subscription_id]]:
constant[List VM images in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM i... | keyword[def] identifier[list_vm_images_sub] ( identifier[access_token] , identifier[subscription_id] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ identifier[get_rm_endpoint] (),
literal[string] , identifier[subscription_id] ,
literal[string] ,
literal[strin... | def list_vm_images_sub(access_token, subscription_id):
"""List VM images in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM images.
"""
endpoint = '... |
def _make_c_string(string):
"""Make a 'C' string."""
if isinstance(string, bytes):
try:
_utf_8_decode(string, None, True)
return string + b"\x00"
except UnicodeError:
raise InvalidStringData("strings in documents must be valid "
... | def function[_make_c_string, parameter[string]]:
constant[Make a 'C' string.]
if call[name[isinstance], parameter[name[string], name[bytes]]] begin[:]
<ast.Try object at 0x7da20c6a9ff0> | keyword[def] identifier[_make_c_string] ( identifier[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[string] , identifier[bytes] ):
keyword[try] :
identifier[_utf_8_decode] ( identifier[string] , keyword[None] , keyword[True] )
keyword[return] ... | def _make_c_string(string):
"""Make a 'C' string."""
if isinstance(string, bytes):
try:
_utf_8_decode(string, None, True)
return string + b'\x00' # depends on [control=['try'], data=[]]
except UnicodeError:
raise InvalidStringData('strings in documents must b... |
def flush(self):
"""Delete all entries from the cache"""
keys = self.client.smembers(self.keys_container)
for key in keys:
self.delete_entry(key) | def function[flush, parameter[self]]:
constant[Delete all entries from the cache]
variable[keys] assign[=] call[name[self].client.smembers, parameter[name[self].keys_container]]
for taget[name[key]] in starred[name[keys]] begin[:]
call[name[self].delete_entry, parameter[name[key]... | keyword[def] identifier[flush] ( identifier[self] ):
literal[string]
identifier[keys] = identifier[self] . identifier[client] . identifier[smembers] ( identifier[self] . identifier[keys_container] )
keyword[for] identifier[key] keyword[in] identifier[keys] :
identifier[self... | def flush(self):
"""Delete all entries from the cache"""
keys = self.client.smembers(self.keys_container)
for key in keys:
self.delete_entry(key) # depends on [control=['for'], data=['key']] |
def _create_sagemaker_pipeline_model(self, instance_type):
"""Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type... | def function[_create_sagemaker_pipeline_model, parameter[self, instance_type]]:
constant[Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
... | keyword[def] identifier[_create_sagemaker_pipeline_model] ( identifier[self] , identifier[instance_type] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[sagemaker_session] :
identifier[self] . identifier[sagemaker_session] = identifier[Session] ()
... | def _create_sagemaker_pipeline_model(self, instance_type):
"""Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type (st... |
def _runtime(self, project, base):
''' first runtimes all project type files, like `project/type.vim`, then the specific project file, like
`project/type/name.vim`.
'''
def run(path_suf):
path = '{}/{}'.format(base, path_suf)
err = 'error sourcing {}.vim: {{}}'.fo... | def function[_runtime, parameter[self, project, base]]:
constant[ first runtimes all project type files, like `project/type.vim`, then the specific project file, like
`project/type/name.vim`.
]
def function[run, parameter[path_suf]]:
variable[path] assign[=] call[constant... | keyword[def] identifier[_runtime] ( identifier[self] , identifier[project] , identifier[base] ):
literal[string]
keyword[def] identifier[run] ( identifier[path_suf] ):
identifier[path] = literal[string] . identifier[format] ( identifier[base] , identifier[path_suf] )
iden... | def _runtime(self, project, base):
""" first runtimes all project type files, like `project/type.vim`, then the specific project file, like
`project/type/name.vim`.
"""
def run(path_suf):
path = '{}/{}'.format(base, path_suf)
err = 'error sourcing {}.vim: {{}}'.format(path)
... |
def from_df(cls, df):
"""Convert a Pandas DataFrame into a Table."""
t = cls()
labels = df.columns
for label in df.columns:
t.append_column(label, df[label])
return t | def function[from_df, parameter[cls, df]]:
constant[Convert a Pandas DataFrame into a Table.]
variable[t] assign[=] call[name[cls], parameter[]]
variable[labels] assign[=] name[df].columns
for taget[name[label]] in starred[name[df].columns] begin[:]
call[name[t].append_co... | keyword[def] identifier[from_df] ( identifier[cls] , identifier[df] ):
literal[string]
identifier[t] = identifier[cls] ()
identifier[labels] = identifier[df] . identifier[columns]
keyword[for] identifier[label] keyword[in] identifier[df] . identifier[columns] :
id... | def from_df(cls, df):
"""Convert a Pandas DataFrame into a Table."""
t = cls()
labels = df.columns
for label in df.columns:
t.append_column(label, df[label]) # depends on [control=['for'], data=['label']]
return t |
def is_between(self, low, high):
"""Asserts that val is numeric and is between low and high."""
val_type = type(self.val)
self._validate_between_args(val_type, low, high)
if self.val < low or self.val > high:
if val_type is datetime.datetime:
self._err('Expec... | def function[is_between, parameter[self, low, high]]:
constant[Asserts that val is numeric and is between low and high.]
variable[val_type] assign[=] call[name[type], parameter[name[self].val]]
call[name[self]._validate_between_args, parameter[name[val_type], name[low], name[high]]]
if <... | keyword[def] identifier[is_between] ( identifier[self] , identifier[low] , identifier[high] ):
literal[string]
identifier[val_type] = identifier[type] ( identifier[self] . identifier[val] )
identifier[self] . identifier[_validate_between_args] ( identifier[val_type] , identifier[low] , ide... | def is_between(self, low, high):
"""Asserts that val is numeric and is between low and high."""
val_type = type(self.val)
self._validate_between_args(val_type, low, high)
if self.val < low or self.val > high:
if val_type is datetime.datetime:
self._err('Expected <%s> to be between <%... |
def get_chunk_size(N, n):
"""Given a dimension of size 'N', determine the number of rows or columns
that can fit into memory.
Parameters
----------
N : int
The size of one of the dimension of a two-dimensional array.
n : int
The number of times an 'N' by 'chunks_size' arr... | def function[get_chunk_size, parameter[N, n]]:
constant[Given a dimension of size 'N', determine the number of rows or columns
that can fit into memory.
Parameters
----------
N : int
The size of one of the dimension of a two-dimensional array.
n : int
The number of ti... | keyword[def] identifier[get_chunk_size] ( identifier[N] , identifier[n] ):
literal[string]
identifier[mem_free] = identifier[memory] ()[ literal[string] ]
keyword[if] identifier[mem_free] > literal[int] :
identifier[chunks_size] = identifier[int] ((( identifier[mem_free] - literal[int] )* l... | def get_chunk_size(N, n):
"""Given a dimension of size 'N', determine the number of rows or columns
that can fit into memory.
Parameters
----------
N : int
The size of one of the dimension of a two-dimensional array.
n : int
The number of times an 'N' by 'chunks_size' arr... |
def update_config(new_config):
""" Update config options with the provided dictionary of options.
"""
flask_app.base_config.update(new_config)
# Check for changed working directory.
if new_config.has_key('working_directory'):
wd = os.path.abspath(new_config['working_directory'])
if ... | def function[update_config, parameter[new_config]]:
constant[ Update config options with the provided dictionary of options.
]
call[name[flask_app].base_config.update, parameter[name[new_config]]]
if call[name[new_config].has_key, parameter[constant[working_directory]]] begin[:]
... | keyword[def] identifier[update_config] ( identifier[new_config] ):
literal[string]
identifier[flask_app] . identifier[base_config] . identifier[update] ( identifier[new_config] )
keyword[if] identifier[new_config] . identifier[has_key] ( literal[string] ):
identifier[wd] = identifier[o... | def update_config(new_config):
""" Update config options with the provided dictionary of options.
"""
flask_app.base_config.update(new_config)
# Check for changed working directory.
if new_config.has_key('working_directory'):
wd = os.path.abspath(new_config['working_directory'])
if n... |
def _set_dynamic_bypass(self, v, load=False):
"""
Setter method for dynamic_bypass, mapped from YANG variable /mpls_state/dynamic_bypass (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dynamic_bypass is considered as a private
method. Backends looking to ... | def function[_set_dynamic_bypass, parameter[self, v, load]]:
constant[
Setter method for dynamic_bypass, mapped from YANG variable /mpls_state/dynamic_bypass (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dynamic_bypass is considered as a private
met... | keyword[def] identifier[_set_dynamic_bypass] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_dynamic_bypass(self, v, load=False):
"""
Setter method for dynamic_bypass, mapped from YANG variable /mpls_state/dynamic_bypass (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dynamic_bypass is considered as a private
method. Backends looking to ... |
def set_empty_for_all(self, row_column_list):
"""Keep all specified subplots completely empty.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
"""
for row... | def function[set_empty_for_all, parameter[self, row_column_list]]:
constant[Keep all specified subplots completely empty.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
... | keyword[def] identifier[set_empty_for_all] ( identifier[self] , identifier[row_column_list] ):
literal[string]
keyword[for] identifier[row] , identifier[column] keyword[in] identifier[row_column_list] :
identifier[self] . identifier[set_empty] ( identifier[row] , identifier[column] ... | def set_empty_for_all(self, row_column_list):
"""Keep all specified subplots completely empty.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
"""
for (row, colum... |
def movies_opening(self, **kwargs):
"""Gets the current opening movies from the API.
Args:
limit (optional): limits the number of movies returned, default=10
country (optional): localized data for selected country, default="us"
Returns:
A dict respresentation of t... | def function[movies_opening, parameter[self]]:
constant[Gets the current opening movies from the API.
Args:
limit (optional): limits the number of movies returned, default=10
country (optional): localized data for selected country, default="us"
Returns:
A dict res... | keyword[def] identifier[movies_opening] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[path] = identifier[self] . identifier[_get_path] ( literal[string] )
identifier[response] = identifier[self] . identifier[_GET] ( identifier[path] , identifier[kwargs] )
... | def movies_opening(self, **kwargs):
"""Gets the current opening movies from the API.
Args:
limit (optional): limits the number of movies returned, default=10
country (optional): localized data for selected country, default="us"
Returns:
A dict respresentation of the J... |
def process(args):
"""Run the function in args.name given arguments in args.argfile.
"""
# Set environment to standard to use periods for decimals and avoid localization
os.environ["LC_ALL"] = "C"
os.environ["LC"] = "C"
os.environ["LANG"] = "C"
setpath.prepend_bcbiopath()
try:
fn... | def function[process, parameter[args]]:
constant[Run the function in args.name given arguments in args.argfile.
]
call[name[os].environ][constant[LC_ALL]] assign[=] constant[C]
call[name[os].environ][constant[LC]] assign[=] constant[C]
call[name[os].environ][constant[LANG]] assign[=]... | keyword[def] identifier[process] ( identifier[args] ):
literal[string]
identifier[os] . identifier[environ] [ literal[string] ]= literal[string]
identifier[os] . identifier[environ] [ literal[string] ]= literal[string]
identifier[os] . identifier[environ] [ literal[string] ]= literal[strin... | def process(args):
"""Run the function in args.name given arguments in args.argfile.
"""
# Set environment to standard to use periods for decimals and avoid localization
os.environ['LC_ALL'] = 'C'
os.environ['LC'] = 'C'
os.environ['LANG'] = 'C'
setpath.prepend_bcbiopath()
try:
fn... |
async def _readline(self, timeout: NumType = None):
"""
Wraps reader.readuntil() with error handling.
"""
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
read_task = asyncio.Task(
self._s... | <ast.AsyncFunctionDef object at 0x7da2049621d0> | keyword[async] keyword[def] identifier[_readline] ( identifier[self] , identifier[timeout] : identifier[NumType] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_stream_reader] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[_stream_writer] ke... | async def _readline(self, timeout: NumType=None):
"""
Wraps reader.readuntil() with error handling.
"""
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected('Client not connected') # depends on [control=['if'], data=[]]
read_task = asyncio.Task... |
def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) | def function[Lookup, parameter[self, x]]:
constant[Looks up x and returns the corresponding value of y.]
return[call[name[self]._Bisect, parameter[name[x], name[self].xs, name[self].ys]]] | keyword[def] identifier[Lookup] ( identifier[self] , identifier[x] ):
literal[string]
keyword[return] identifier[self] . identifier[_Bisect] ( identifier[x] , identifier[self] . identifier[xs] , identifier[self] . identifier[ys] ) | def Lookup(self, x):
"""Looks up x and returns the corresponding value of y."""
return self._Bisect(x, self.xs, self.ys) |
def getUserContact(master, contact_types, uid):
"""
This is a simple getter function that returns a user attribute
that matches the contact_types argument, or returns None if no
uid/match is found.
@param master: BuildMaster used to query the database
@type master: BuildMaster instance
@pa... | def function[getUserContact, parameter[master, contact_types, uid]]:
constant[
This is a simple getter function that returns a user attribute
that matches the contact_types argument, or returns None if no
uid/match is found.
@param master: BuildMaster used to query the database
@type master... | keyword[def] identifier[getUserContact] ( identifier[master] , identifier[contact_types] , identifier[uid] ):
literal[string]
identifier[d] = identifier[master] . identifier[db] . identifier[users] . identifier[getUser] ( identifier[uid] )
identifier[d] . identifier[addCallback] ( identifier[_extractC... | def getUserContact(master, contact_types, uid):
"""
This is a simple getter function that returns a user attribute
that matches the contact_types argument, or returns None if no
uid/match is found.
@param master: BuildMaster used to query the database
@type master: BuildMaster instance
@pa... |
def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simu... | def function[watt_m, parameter[simulated_array, observed_array, replace_nan, replace_inf, remove_neg, remove_zero]]:
constant[Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simula... | keyword[def] identifier[watt_m] ( identifier[simulated_array] , identifier[observed_array] , identifier[replace_nan] = keyword[None] , identifier[replace_inf] = keyword[None] ,
identifier[remove_neg] = keyword[False] , identifier[remove_zero] = keyword[False] ):
literal[string]
identifier[simulated_... | def watt_m(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False):
"""Compute Watterson's M (M).
.. image:: /pictures/M.png
**Range:** -1 ≤ M < 1, does not indicate bias, larger is better.
**Notes:**
Parameters
----------
simulated_array... |
def _access_token(self, request: Request=None, page_id: Text=''):
"""
Guess the access token for that specific request.
"""
if not page_id:
msg = request.message # type: FacebookMessage
page_id = msg.get_page_id()
page = self.settings()
if page... | def function[_access_token, parameter[self, request, page_id]]:
constant[
Guess the access token for that specific request.
]
if <ast.UnaryOp object at 0x7da18dc07610> begin[:]
variable[msg] assign[=] name[request].message
variable[page_id] assign[=] call[... | keyword[def] identifier[_access_token] ( identifier[self] , identifier[request] : identifier[Request] = keyword[None] , identifier[page_id] : identifier[Text] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[page_id] :
identifier[msg] = identifier[request] . ... | def _access_token(self, request: Request=None, page_id: Text=''):
"""
Guess the access token for that specific request.
"""
if not page_id:
msg = request.message # type: FacebookMessage
page_id = msg.get_page_id() # depends on [control=['if'], data=[]]
page = self.settings(... |
def draw_rect(self, bbox, cell_val):
"""
Fills the bbox with the content values
Float bbox values are normalized to have non-zero area
"""
new_x0 = int(bbox[x0])
new_y0 = int(bbox[y0])
new_x1 = max(new_x0 + 1, int(bbox[x1]))
new_y1 = max(new_y0 + 1, int(bb... | def function[draw_rect, parameter[self, bbox, cell_val]]:
constant[
Fills the bbox with the content values
Float bbox values are normalized to have non-zero area
]
variable[new_x0] assign[=] call[name[int], parameter[call[name[bbox]][name[x0]]]]
variable[new_y0] assign[=]... | keyword[def] identifier[draw_rect] ( identifier[self] , identifier[bbox] , identifier[cell_val] ):
literal[string]
identifier[new_x0] = identifier[int] ( identifier[bbox] [ identifier[x0] ])
identifier[new_y0] = identifier[int] ( identifier[bbox] [ identifier[y0] ])
identifier[new... | def draw_rect(self, bbox, cell_val):
"""
Fills the bbox with the content values
Float bbox values are normalized to have non-zero area
"""
new_x0 = int(bbox[x0])
new_y0 = int(bbox[y0])
new_x1 = max(new_x0 + 1, int(bbox[x1]))
new_y1 = max(new_y0 + 1, int(bbox[y1]))
self.gr... |
def set_sampling_interval(self, interval):
"""
This method sets the sampling interval for the Firmata loop method
:param interval: time in milliseconds
:returns: No return value
"""
task = asyncio.ensure_future(self.core.set_sampling_interval(interval))
self.loo... | def function[set_sampling_interval, parameter[self, interval]]:
constant[
This method sets the sampling interval for the Firmata loop method
:param interval: time in milliseconds
:returns: No return value
]
variable[task] assign[=] call[name[asyncio].ensure_future, para... | keyword[def] identifier[set_sampling_interval] ( identifier[self] , identifier[interval] ):
literal[string]
identifier[task] = identifier[asyncio] . identifier[ensure_future] ( identifier[self] . identifier[core] . identifier[set_sampling_interval] ( identifier[interval] ))
identifier[self... | def set_sampling_interval(self, interval):
"""
This method sets the sampling interval for the Firmata loop method
:param interval: time in milliseconds
:returns: No return value
"""
task = asyncio.ensure_future(self.core.set_sampling_interval(interval))
self.loop.run_until_... |
def handle_logging(self):
"""
To allow devs to log as early as possible, logging will already be
handled here
"""
configure_logging(self.get_scrapy_options())
# Disable duplicates
self.__scrapy_options["LOG_ENABLED"] = False
# Now, after log-level is co... | def function[handle_logging, parameter[self]]:
constant[
To allow devs to log as early as possible, logging will already be
handled here
]
call[name[configure_logging], parameter[call[name[self].get_scrapy_options, parameter[]]]]
call[name[self].__scrapy_options][constant... | keyword[def] identifier[handle_logging] ( identifier[self] ):
literal[string]
identifier[configure_logging] ( identifier[self] . identifier[get_scrapy_options] ())
identifier[self] . identifier[__scrapy_options] [ literal[string] ]= keyword[False]
keyword[for... | def handle_logging(self):
"""
To allow devs to log as early as possible, logging will already be
handled here
"""
configure_logging(self.get_scrapy_options())
# Disable duplicates
self.__scrapy_options['LOG_ENABLED'] = False
# Now, after log-level is correctly set, lets log t... |
def receives(self, idA, idB):
""" Returns the dignities where A receives B.
A receives B when (1) B aspects A and (2) B is in
dignities of A.
"""
objA = self.chart.get(idA)
objB = self.chart.get(idB)
asp = aspects.isAspecting(objB, objA, const.MAJOR_ASPECTS)
... | def function[receives, parameter[self, idA, idB]]:
constant[ Returns the dignities where A receives B.
A receives B when (1) B aspects A and (2) B is in
dignities of A.
]
variable[objA] assign[=] call[name[self].chart.get, parameter[name[idA]]]
variable[objB] assign[=] ... | keyword[def] identifier[receives] ( identifier[self] , identifier[idA] , identifier[idB] ):
literal[string]
identifier[objA] = identifier[self] . identifier[chart] . identifier[get] ( identifier[idA] )
identifier[objB] = identifier[self] . identifier[chart] . identifier[get] ( identifier[i... | def receives(self, idA, idB):
""" Returns the dignities where A receives B.
A receives B when (1) B aspects A and (2) B is in
dignities of A.
"""
objA = self.chart.get(idA)
objB = self.chart.get(idB)
asp = aspects.isAspecting(objB, objA, const.MAJOR_ASPECTS)
return self.inD... |
def Expand(self):
"""Reads the contents of the current node and the full
subtree. It then makes the subtree available until the next
xmlTextReaderRead() call """
ret = libxml2mod.xmlTextReaderExpand(self._o)
if ret is None:raise treeError('xmlTextReaderExpand() failed')
... | def function[Expand, parameter[self]]:
constant[Reads the contents of the current node and the full
subtree. It then makes the subtree available until the next
xmlTextReaderRead() call ]
variable[ret] assign[=] call[name[libxml2mod].xmlTextReaderExpand, parameter[name[self]._o]]
... | keyword[def] identifier[Expand] ( identifier[self] ):
literal[string]
identifier[ret] = identifier[libxml2mod] . identifier[xmlTextReaderExpand] ( identifier[self] . identifier[_o] )
keyword[if] identifier[ret] keyword[is] keyword[None] : keyword[raise] identifier[treeError] ( literal[... | def Expand(self):
"""Reads the contents of the current node and the full
subtree. It then makes the subtree available until the next
xmlTextReaderRead() call """
ret = libxml2mod.xmlTextReaderExpand(self._o)
if ret is None:
raise treeError('xmlTextReaderExpand() failed') # depe... |
def events_for_secretreveal(
transfers_pair: List[MediationPairState],
secret: Secret,
pseudo_random_generator: random.Random,
) -> List[Event]:
""" Reveal the secret off-chain.
The secret is revealed off-chain even if there is a pending transaction to
reveal it on-chain, this allow... | def function[events_for_secretreveal, parameter[transfers_pair, secret, pseudo_random_generator]]:
constant[ Reveal the secret off-chain.
The secret is revealed off-chain even if there is a pending transaction to
reveal it on-chain, this allows the unlock to happen off-chain, which is
faster.
... | keyword[def] identifier[events_for_secretreveal] (
identifier[transfers_pair] : identifier[List] [ identifier[MediationPairState] ],
identifier[secret] : identifier[Secret] ,
identifier[pseudo_random_generator] : identifier[random] . identifier[Random] ,
)-> identifier[List] [ identifier[Event] ]:
literal[str... | def events_for_secretreveal(transfers_pair: List[MediationPairState], secret: Secret, pseudo_random_generator: random.Random) -> List[Event]:
""" Reveal the secret off-chain.
The secret is revealed off-chain even if there is a pending transaction to
reveal it on-chain, this allows the unlock to happen off-... |
def expect_column_values_to_match_regex_list(self,
column,
regex_list,
match_on="any",
mostly=None,
... | def function[expect_column_values_to_match_regex_list, parameter[self, column, regex_list, match_on, mostly, result_format, include_config, catch_exceptions, meta]]:
constant[Expect the column entries to be strings that can be matched to either any of or all of a list of regular expressions.
Matches can... | keyword[def] identifier[expect_column_values_to_match_regex_list] ( identifier[self] ,
identifier[column] ,
identifier[regex_list] ,
identifier[match_on] = literal[string] ,
identifier[mostly] = keyword[None] ,
identifier[result_format] = keyword[None] , identifier[include_config] = keyword[False] , identifier[c... | def expect_column_values_to_match_regex_list(self, column, regex_list, match_on='any', mostly=None, result_format=None, include_config=False, catch_exceptions=None, meta=None):
"""Expect the column entries to be strings that can be matched to either any of or all of a list of regular expressions.
Matches ca... |
def assert_ordered(iterable, key=lambda x: x, comp=operator.le):
"""
Assert that for all items in the iterable, they're in order based on comp
>>> list(assert_ordered(range(5)))
[0, 1, 2, 3, 4]
>>> list(assert_ordered(range(5), comp=operator.ge))
Traceback (most recent call last):
...
AssertionError: 0 < 1
>>... | def function[assert_ordered, parameter[iterable, key, comp]]:
constant[
Assert that for all items in the iterable, they're in order based on comp
>>> list(assert_ordered(range(5)))
[0, 1, 2, 3, 4]
>>> list(assert_ordered(range(5), comp=operator.ge))
Traceback (most recent call last):
...
AssertionError:... | keyword[def] identifier[assert_ordered] ( identifier[iterable] , identifier[key] = keyword[lambda] identifier[x] : identifier[x] , identifier[comp] = identifier[operator] . identifier[le] ):
literal[string]
identifier[err_tmpl] =(
literal[string] keyword[if] identifier[comp] keyword[is] identifier[operato... | def assert_ordered(iterable, key=lambda x: x, comp=operator.le):
"""
Assert that for all items in the iterable, they're in order based on comp
>>> list(assert_ordered(range(5)))
[0, 1, 2, 3, 4]
>>> list(assert_ordered(range(5), comp=operator.ge))
Traceback (most recent call last):
...
AssertionError: 0 < 1
... |
async def _send_text(self, request: Request, stack: Stack):
"""
Send text layers to the user. Each layer will go in its own bubble.
Also, Facebook limits messages to 320 chars, so if any message is
longer than that it will be split into as many messages as needed to
be accepted ... | <ast.AsyncFunctionDef object at 0x7da20c6c70d0> | keyword[async] keyword[def] identifier[_send_text] ( identifier[self] , identifier[request] : identifier[Request] , identifier[stack] : identifier[Stack] ):
literal[string]
identifier[parts] =[]
keyword[for] identifier[layer] keyword[in] identifier[stack] . identifier[layers] :
... | async def _send_text(self, request: Request, stack: Stack):
"""
Send text layers to the user. Each layer will go in its own bubble.
Also, Facebook limits messages to 320 chars, so if any message is
longer than that it will be split into as many messages as needed to
be accepted by F... |
def getRaw(self, instance, **kwargs):
"""Returns raw field value (possible wrapped in BaseUnit)
"""
value = ObjectField.get(self, instance, **kwargs)
# getattr(instance, "Remarks") returns a BaseUnit
if callable(value):
value = value()
return value | def function[getRaw, parameter[self, instance]]:
constant[Returns raw field value (possible wrapped in BaseUnit)
]
variable[value] assign[=] call[name[ObjectField].get, parameter[name[self], name[instance]]]
if call[name[callable], parameter[name[value]]] begin[:]
variabl... | keyword[def] identifier[getRaw] ( identifier[self] , identifier[instance] ,** identifier[kwargs] ):
literal[string]
identifier[value] = identifier[ObjectField] . identifier[get] ( identifier[self] , identifier[instance] ,** identifier[kwargs] )
keyword[if] identifier[callable] ( ... | def getRaw(self, instance, **kwargs):
"""Returns raw field value (possible wrapped in BaseUnit)
"""
value = ObjectField.get(self, instance, **kwargs)
# getattr(instance, "Remarks") returns a BaseUnit
if callable(value):
value = value() # depends on [control=['if'], data=[]]
return v... |
def geigh(H,S):
"Solve the generalized eigensystem Hc = ESc"
A = cholorth(S)
E,U = np.linalg.eigh(simx(H,A))
return E,np.dot(A,U) | def function[geigh, parameter[H, S]]:
constant[Solve the generalized eigensystem Hc = ESc]
variable[A] assign[=] call[name[cholorth], parameter[name[S]]]
<ast.Tuple object at 0x7da20c6e5030> assign[=] call[name[np].linalg.eigh, parameter[call[name[simx], parameter[name[H], name[A]]]]]
return... | keyword[def] identifier[geigh] ( identifier[H] , identifier[S] ):
literal[string]
identifier[A] = identifier[cholorth] ( identifier[S] )
identifier[E] , identifier[U] = identifier[np] . identifier[linalg] . identifier[eigh] ( identifier[simx] ( identifier[H] , identifier[A] ))
keyword[return] id... | def geigh(H, S):
"""Solve the generalized eigensystem Hc = ESc"""
A = cholorth(S)
(E, U) = np.linalg.eigh(simx(H, A))
return (E, np.dot(A, U)) |
def git_commit(repo_dir, message=None, amend=False, stage=True):
"""Commit any changes, optionally staging all changes beforehand."""
if stage:
git_add_all(repo_dir)
command = ['git', 'commit', '--allow-empty']
if amend:
command.append('--amend')
if not message:
comma... | def function[git_commit, parameter[repo_dir, message, amend, stage]]:
constant[Commit any changes, optionally staging all changes beforehand.]
if name[stage] begin[:]
call[name[git_add_all], parameter[name[repo_dir]]]
variable[command] assign[=] list[[<ast.Constant object at 0x7d... | keyword[def] identifier[git_commit] ( identifier[repo_dir] , identifier[message] = keyword[None] , identifier[amend] = keyword[False] , identifier[stage] = keyword[True] ):
literal[string]
keyword[if] identifier[stage] :
identifier[git_add_all] ( identifier[repo_dir] )
identifier[command] =[... | def git_commit(repo_dir, message=None, amend=False, stage=True):
"""Commit any changes, optionally staging all changes beforehand."""
if stage:
git_add_all(repo_dir) # depends on [control=['if'], data=[]]
command = ['git', 'commit', '--allow-empty']
if amend:
command.append('--amend')
... |
def apply(self, macro):
"""
Show what a macro would do
Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/macros#show-changes-to-ticket>`__.
:param macro: Macro object or id.
"""
return self._query_zendesk(self.endpoint.apply, 'result', id=macro) | def function[apply, parameter[self, macro]]:
constant[
Show what a macro would do
Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/macros#show-changes-to-ticket>`__.
:param macro: Macro object or id.
]
return[call[name[self]._query_zendesk, parameter[... | keyword[def] identifier[apply] ( identifier[self] , identifier[macro] ):
literal[string]
keyword[return] identifier[self] . identifier[_query_zendesk] ( identifier[self] . identifier[endpoint] . identifier[apply] , literal[string] , identifier[id] = identifier[macro] ) | def apply(self, macro):
"""
Show what a macro would do
Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/macros#show-changes-to-ticket>`__.
:param macro: Macro object or id.
"""
return self._query_zendesk(self.endpoint.apply, 'result', id=macro) |
def rsdl_sn(self, U):
"""Compute dual residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
return self.rho * np.linalg.norm(self.cnst_AT(U)) | def function[rsdl_sn, parameter[self, U]]:
constant[Compute dual residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
]
return[binary_operation[name[self].rho * call... | keyword[def] identifier[rsdl_sn] ( identifier[self] , identifier[U] ):
literal[string]
keyword[return] identifier[self] . identifier[rho] * identifier[np] . identifier[linalg] . identifier[norm] ( identifier[self] . identifier[cnst_AT] ( identifier[U] )) | def rsdl_sn(self, U):
"""Compute dual residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
return self.rho * np.linalg.norm(self.cnst_AT(U)) |
def _set_network(self, v, load=False):
"""
Setter method for network, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/network (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_network is considered as a private
... | def function[_set_network, parameter[self, v, load]]:
constant[
Setter method for network, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/network (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_network is c... | keyword[def] identifier[_set_network] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identi... | def _set_network(self, v, load=False):
"""
Setter method for network, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/network (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_network is considered as a private
... |
def eval_str_to_list(input_str: str) -> List[str]:
"""Turn str into str or tuple."""
inner_cast = ast.literal_eval(input_str) # type: List[str]
if isinstance(inner_cast, list):
return inner_cast
else:
raise ValueError | def function[eval_str_to_list, parameter[input_str]]:
constant[Turn str into str or tuple.]
variable[inner_cast] assign[=] call[name[ast].literal_eval, parameter[name[input_str]]]
if call[name[isinstance], parameter[name[inner_cast], name[list]]] begin[:]
return[name[inner_cast]] | keyword[def] identifier[eval_str_to_list] ( identifier[input_str] : identifier[str] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[inner_cast] = identifier[ast] . identifier[literal_eval] ( identifier[input_str] )
keyword[if] identifier[isinstance] ( identifier[inner_cast] , ide... | def eval_str_to_list(input_str: str) -> List[str]:
"""Turn str into str or tuple."""
inner_cast = ast.literal_eval(input_str) # type: List[str]
if isinstance(inner_cast, list):
return inner_cast # depends on [control=['if'], data=[]]
else:
raise ValueError |
def open_filezip(file_path, find_str):
"""
Open the wrapped file.
Read directly from the zip without extracting its content.
"""
if zipfile.is_zipfile(file_path):
zipf = zipfile.ZipFile(file_path)
interesting_files = [f for f in zipf.infolist() if find_str in f]
for inside_f... | def function[open_filezip, parameter[file_path, find_str]]:
constant[
Open the wrapped file.
Read directly from the zip without extracting its content.
]
if call[name[zipfile].is_zipfile, parameter[name[file_path]]] begin[:]
variable[zipf] assign[=] call[name[zipfile].ZipFile... | keyword[def] identifier[open_filezip] ( identifier[file_path] , identifier[find_str] ):
literal[string]
keyword[if] identifier[zipfile] . identifier[is_zipfile] ( identifier[file_path] ):
identifier[zipf] = identifier[zipfile] . identifier[ZipFile] ( identifier[file_path] )
identifier[in... | def open_filezip(file_path, find_str):
"""
Open the wrapped file.
Read directly from the zip without extracting its content.
"""
if zipfile.is_zipfile(file_path):
zipf = zipfile.ZipFile(file_path)
interesting_files = [f for f in zipf.infolist() if find_str in f]
for inside_fi... |
def addPathway(
self, pathway_id, pathway_label, pathway_type=None,
pathway_description=None):
"""
Adds a pathway as a class. If no specific type is specified, it will
default to a subclass of "GO:cellular_process" and "PW:pathway".
:param pathway_id:
:pa... | def function[addPathway, parameter[self, pathway_id, pathway_label, pathway_type, pathway_description]]:
constant[
Adds a pathway as a class. If no specific type is specified, it will
default to a subclass of "GO:cellular_process" and "PW:pathway".
:param pathway_id:
:param path... | keyword[def] identifier[addPathway] (
identifier[self] , identifier[pathway_id] , identifier[pathway_label] , identifier[pathway_type] = keyword[None] ,
identifier[pathway_description] = keyword[None] ):
literal[string]
keyword[if] identifier[pathway_type] keyword[is] keyword[None] :
... | def addPathway(self, pathway_id, pathway_label, pathway_type=None, pathway_description=None):
"""
Adds a pathway as a class. If no specific type is specified, it will
default to a subclass of "GO:cellular_process" and "PW:pathway".
:param pathway_id:
:param pathway_label:
:p... |
def resample(grid, wl, flux):
""" Resample spectrum onto desired grid """
flux_rs = (interpolate.interp1d(wl, flux))(grid)
return flux_rs | def function[resample, parameter[grid, wl, flux]]:
constant[ Resample spectrum onto desired grid ]
variable[flux_rs] assign[=] call[call[name[interpolate].interp1d, parameter[name[wl], name[flux]]], parameter[name[grid]]]
return[name[flux_rs]] | keyword[def] identifier[resample] ( identifier[grid] , identifier[wl] , identifier[flux] ):
literal[string]
identifier[flux_rs] =( identifier[interpolate] . identifier[interp1d] ( identifier[wl] , identifier[flux] ))( identifier[grid] )
keyword[return] identifier[flux_rs] | def resample(grid, wl, flux):
""" Resample spectrum onto desired grid """
flux_rs = interpolate.interp1d(wl, flux)(grid)
return flux_rs |
def infer_newX(model, Y_new, optimize=True, init='L2'):
"""
Infer the distribution of X for the new observed data *Y_new*.
:param model: the GPy model used in inference
:type model: GPy.core.Model
:param Y_new: the new observed data for inference
:type Y_new: numpy.ndarray
:param optimize: ... | def function[infer_newX, parameter[model, Y_new, optimize, init]]:
constant[
Infer the distribution of X for the new observed data *Y_new*.
:param model: the GPy model used in inference
:type model: GPy.core.Model
:param Y_new: the new observed data for inference
:type Y_new: numpy.ndarray
... | keyword[def] identifier[infer_newX] ( identifier[model] , identifier[Y_new] , identifier[optimize] = keyword[True] , identifier[init] = literal[string] ):
literal[string]
identifier[infr_m] = identifier[InferenceX] ( identifier[model] , identifier[Y_new] , identifier[init] = identifier[init] )
keywor... | def infer_newX(model, Y_new, optimize=True, init='L2'):
"""
Infer the distribution of X for the new observed data *Y_new*.
:param model: the GPy model used in inference
:type model: GPy.core.Model
:param Y_new: the new observed data for inference
:type Y_new: numpy.ndarray
:param optimize: ... |
def check_platform(self, dataset):
'''
int platform_variable; //............................................ RECOMMENDED - a container variable storing information about the platform. If more than one, can expand each attribute into a variable. For example, platform_call_sign and platform_nodc_code. See... | def function[check_platform, parameter[self, dataset]]:
constant[
int platform_variable; //............................................ RECOMMENDED - a container variable storing information about the platform. If more than one, can expand each attribute into a variable. For example, platform_call_sign ... | keyword[def] identifier[check_platform] ( identifier[self] , identifier[dataset] ):
literal[string]
identifier[platforms] = identifier[util] . identifier[get_platform_variables] ( identifier[dataset] )
keyword[if] keyword[not] identifier[platforms] :
keyword[return]... | def check_platform(self, dataset):
"""
int platform_variable; //............................................ RECOMMENDED - a container variable storing information about the platform. If more than one, can expand each attribute into a variable. For example, platform_call_sign and platform_nodc_code. See ins... |
def _check_symbols(self, symbols):
"""the size must be the same as the length of the array numbers and all elements must be strings"""
if len(symbols) != self.size:
raise TypeError("The number of symbols in the graph does not "
"match the length of the atomic numbers array.")... | def function[_check_symbols, parameter[self, symbols]]:
constant[the size must be the same as the length of the array numbers and all elements must be strings]
if compare[call[name[len], parameter[name[symbols]]] not_equal[!=] name[self].size] begin[:]
<ast.Raise object at 0x7da207f01900>
... | keyword[def] identifier[_check_symbols] ( identifier[self] , identifier[symbols] ):
literal[string]
keyword[if] identifier[len] ( identifier[symbols] )!= identifier[self] . identifier[size] :
keyword[raise] identifier[TypeError] ( literal[string]
literal[string] )
... | def _check_symbols(self, symbols):
"""the size must be the same as the length of the array numbers and all elements must be strings"""
if len(symbols) != self.size:
raise TypeError('The number of symbols in the graph does not match the length of the atomic numbers array.') # depends on [control=['if'],... |
def warm_spell_duration_index(tasmax, tx90, window=6, freq='YS'):
r"""Warm spell duration index
Number of days with at least six consecutive days where the daily maximum temperature is above the 90th
percentile. The 90th percentile should be computed for a 5-day window centred on each calendar day in the
... | def function[warm_spell_duration_index, parameter[tasmax, tx90, window, freq]]:
constant[Warm spell duration index
Number of days with at least six consecutive days where the daily maximum temperature is above the 90th
percentile. The 90th percentile should be computed for a 5-day window centred on eac... | keyword[def] identifier[warm_spell_duration_index] ( identifier[tasmax] , identifier[tx90] , identifier[window] = literal[int] , identifier[freq] = literal[string] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[tx90] . identifier[coords] . identifier[keys] ():
... | def warm_spell_duration_index(tasmax, tx90, window=6, freq='YS'):
"""Warm spell duration index
Number of days with at least six consecutive days where the daily maximum temperature is above the 90th
percentile. The 90th percentile should be computed for a 5-day window centred on each calendar day in the
... |
def _encrypt_data_key(self, data_key, algorithm, encryption_context=None):
"""Encrypts a data key and returns the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
... | def function[_encrypt_data_key, parameter[self, data_key, algorithm, encryption_context]]:
constant[Encrypts a data key and returns the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.s... | keyword[def] identifier[_encrypt_data_key] ( identifier[self] , identifier[data_key] , identifier[algorithm] , identifier[encryption_context] = keyword[None] ):
literal[string]
identifier[kms_params] ={ literal[string] : identifier[self] . identifier[_key_id] , literal[string] : identifier[data_key... | def _encrypt_data_key(self, data_key, algorithm, encryption_context=None):
"""Encrypts a data key and returns the ciphertext.
:param data_key: Unencrypted data key
:type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`
or :class:`aws_encryption_sdk.structures.DataKey`
... |
def find_function_by_name(self, name):
"""Return the cfg of the requested function by name.
"""
cfg_rv = None
for cfg in self._cfgs:
if cfg.name == name:
cfg_rv = cfg
break
return cfg_rv | def function[find_function_by_name, parameter[self, name]]:
constant[Return the cfg of the requested function by name.
]
variable[cfg_rv] assign[=] constant[None]
for taget[name[cfg]] in starred[name[self]._cfgs] begin[:]
if compare[name[cfg].name equal[==] name[name]] be... | keyword[def] identifier[find_function_by_name] ( identifier[self] , identifier[name] ):
literal[string]
identifier[cfg_rv] = keyword[None]
keyword[for] identifier[cfg] keyword[in] identifier[self] . identifier[_cfgs] :
keyword[if] identifier[cfg] . identifier[name] == ide... | def find_function_by_name(self, name):
"""Return the cfg of the requested function by name.
"""
cfg_rv = None
for cfg in self._cfgs:
if cfg.name == name:
cfg_rv = cfg
break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['cfg']]
retur... |
def _save_one(self, model, ctx):
"""
Saves the created instance.
"""
assert isinstance(ctx, ResourceQueryContext)
self._orm.add(model)
self._orm.flush() | def function[_save_one, parameter[self, model, ctx]]:
constant[
Saves the created instance.
]
assert[call[name[isinstance], parameter[name[ctx], name[ResourceQueryContext]]]]
call[name[self]._orm.add, parameter[name[model]]]
call[name[self]._orm.flush, parameter[]] | keyword[def] identifier[_save_one] ( identifier[self] , identifier[model] , identifier[ctx] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[ctx] , identifier[ResourceQueryContext] )
identifier[self] . identifier[_orm] . identifier[add] ( identifier[model] )
... | def _save_one(self, model, ctx):
"""
Saves the created instance.
"""
assert isinstance(ctx, ResourceQueryContext)
self._orm.add(model)
self._orm.flush() |
def coerce_quotes(quotes):
"""Coerce a quote type into an acceptable value, or raise an error."""
orig, quotes = quotes, str(quotes) if quotes else None
if quotes not in [None, '"', "'"]:
raise ValueError("{!r} is not a valid quote type".format(orig))
return quotes | def function[coerce_quotes, parameter[quotes]]:
constant[Coerce a quote type into an acceptable value, or raise an error.]
<ast.Tuple object at 0x7da1b12ca320> assign[=] tuple[[<ast.Name object at 0x7da1b12c8df0>, <ast.IfExp object at 0x7da1b12c9840>]]
if compare[name[quotes] <ast.NotIn object a... | keyword[def] identifier[coerce_quotes] ( identifier[quotes] ):
literal[string]
identifier[orig] , identifier[quotes] = identifier[quotes] , identifier[str] ( identifier[quotes] ) keyword[if] identifier[quotes] keyword[else] keyword[None]
keyword[if] identifier[quotes] keyword[not] k... | def coerce_quotes(quotes):
"""Coerce a quote type into an acceptable value, or raise an error."""
(orig, quotes) = (quotes, str(quotes) if quotes else None)
if quotes not in [None, '"', "'"]:
raise ValueError('{!r} is not a valid quote type'.format(orig)) # depends on [control=['if'], data=[]]
... |
def group_info(name):
'''
.. versionadded:: 2016.11.0
Lists all packages in the specified group
CLI Example:
.. code-block:: bash
salt '*' pkg.group_info 'xorg'
'''
pkgtypes = ('mandatory', 'optional', 'default', 'conditional')
ret = {}
for pkgtype in pkgtypes:
r... | def function[group_info, parameter[name]]:
constant[
.. versionadded:: 2016.11.0
Lists all packages in the specified group
CLI Example:
.. code-block:: bash
salt '*' pkg.group_info 'xorg'
]
variable[pkgtypes] assign[=] tuple[[<ast.Constant object at 0x7da1b21f9960>, <ast.... | keyword[def] identifier[group_info] ( identifier[name] ):
literal[string]
identifier[pkgtypes] =( literal[string] , literal[string] , literal[string] , literal[string] )
identifier[ret] ={}
keyword[for] identifier[pkgtype] keyword[in] identifier[pkgtypes] :
identifier[ret] [ identifi... | def group_info(name):
"""
.. versionadded:: 2016.11.0
Lists all packages in the specified group
CLI Example:
.. code-block:: bash
salt '*' pkg.group_info 'xorg'
"""
pkgtypes = ('mandatory', 'optional', 'default', 'conditional')
ret = {}
for pkgtype in pkgtypes:
re... |
def _get_imsize(self, im_name):
"""
get image size info
Returns:
----------
tuple of (height, width)
"""
img = cv2.imread(im_name)
return (img.shape[0], img.shape[1]) | def function[_get_imsize, parameter[self, im_name]]:
constant[
get image size info
Returns:
----------
tuple of (height, width)
]
variable[img] assign[=] call[name[cv2].imread, parameter[name[im_name]]]
return[tuple[[<ast.Subscript object at 0x7da20c76f820>, <... | keyword[def] identifier[_get_imsize] ( identifier[self] , identifier[im_name] ):
literal[string]
identifier[img] = identifier[cv2] . identifier[imread] ( identifier[im_name] )
keyword[return] ( identifier[img] . identifier[shape] [ literal[int] ], identifier[img] . identifier[shape] [ lite... | def _get_imsize(self, im_name):
"""
get image size info
Returns:
----------
tuple of (height, width)
"""
img = cv2.imread(im_name)
return (img.shape[0], img.shape[1]) |
def map(self, func, iterable, chunksize=None):
"""A parallel equivalent of the map() builtin function. It
blocks till the result is ready.
This method chops the iterable into a number of chunks which
it submits to the process pool as separate tasks. The
(approximate) size of the... | def function[map, parameter[self, func, iterable, chunksize]]:
constant[A parallel equivalent of the map() builtin function. It
blocks till the result is ready.
This method chops the iterable into a number of chunks which
it submits to the process pool as separate tasks. The
(ap... | keyword[def] identifier[map] ( identifier[self] , identifier[func] , identifier[iterable] , identifier[chunksize] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[map_async] ( identifier[func] , identifier[iterable] , identifier[chunksize] ). identifier[get] () | def map(self, func, iterable, chunksize=None):
"""A parallel equivalent of the map() builtin function. It
blocks till the result is ready.
This method chops the iterable into a number of chunks which
it submits to the process pool as separate tasks. The
(approximate) size of these c... |
def some(args):
"""
%prog some fastafile listfile outfastafile
generate a subset of fastafile, based on a list
"""
p = OptionParser(some.__doc__)
p.add_option("--exclude", default=False, action="store_true",
help="Output sequences not in the list file [default: %default]")
p.add... | def function[some, parameter[args]]:
constant[
%prog some fastafile listfile outfastafile
generate a subset of fastafile, based on a list
]
variable[p] assign[=] call[name[OptionParser], parameter[name[some].__doc__]]
call[name[p].add_option, parameter[constant[--exclude]]]
... | keyword[def] identifier[some] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[some] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = keyword[False] , identifier[action] = literal[string] ,
identifi... | def some(args):
"""
%prog some fastafile listfile outfastafile
generate a subset of fastafile, based on a list
"""
p = OptionParser(some.__doc__)
p.add_option('--exclude', default=False, action='store_true', help='Output sequences not in the list file [default: %default]')
p.add_option('--u... |
def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if t... | def function[_normalize, parameter[self, address]]:
constant[
Normalize prefixes, suffixes and other to make matching original to returned easier.
]
variable[normalized_address] assign[=] list[[]]
if name[self].logger begin[:]
call[name[self].logger.debug, paramet... | keyword[def] identifier[_normalize] ( identifier[self] , identifier[address] ):
literal[string]
identifier[normalized_address] =[]
keyword[if] identifier[self] . identifier[logger] : identifier[self] . identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identif... | def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger:
self.logger.debug('Normalizing Address: {0}'.format(address)) # depends on [control=['if'], data=[]]
for token in a... |
def verify_compact_verbose(self, jws=None, keys=None, allow_none=False,
sigalg=None):
"""
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the... | def function[verify_compact_verbose, parameter[self, jws, keys, allow_none, sigalg]]:
constant[
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
... | keyword[def] identifier[verify_compact_verbose] ( identifier[self] , identifier[jws] = keyword[None] , identifier[keys] = keyword[None] , identifier[allow_none] = keyword[False] ,
identifier[sigalg] = keyword[None] ):
literal[string]
keyword[if] identifier[jws] :
identifier[jwt] = id... | def verify_compact_verbose(self, jws=None, keys=None, allow_none=False, sigalg=None):
"""
Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:par... |
def followers(self):
"""获取话题关注者
:return: 话题关注者,返回生成器
:rtype: Author.Iterable
"""
from .author import Author, ANONYMOUS
self._make_soup()
gotten_data_num = 20
data = {
'_xsrf': self.xsrf,
'start': '',
'offset': 0
... | def function[followers, parameter[self]]:
constant[获取话题关注者
:return: 话题关注者,返回生成器
:rtype: Author.Iterable
]
from relative_module[author] import module[Author], module[ANONYMOUS]
call[name[self]._make_soup, parameter[]]
variable[gotten_data_num] assign[=] constant[20]
... | keyword[def] identifier[followers] ( identifier[self] ):
literal[string]
keyword[from] . identifier[author] keyword[import] identifier[Author] , identifier[ANONYMOUS]
identifier[self] . identifier[_make_soup] ()
identifier[gotten_data_num] = literal[int]
identifier[da... | def followers(self):
"""获取话题关注者
:return: 话题关注者,返回生成器
:rtype: Author.Iterable
"""
from .author import Author, ANONYMOUS
self._make_soup()
gotten_data_num = 20
data = {'_xsrf': self.xsrf, 'start': '', 'offset': 0}
while gotten_data_num == 20:
res = self._session.po... |
def get_ips(self, instance_id):
"""Retrieves the private and public ip addresses for a given instance.
Note: Azure normally provides access to vms from a shared load
balancer IP and
mapping of ssh ports on the vms. So by default, the Azure provider
returns strings
of the ... | def function[get_ips, parameter[self, instance_id]]:
constant[Retrieves the private and public ip addresses for a given instance.
Note: Azure normally provides access to vms from a shared load
balancer IP and
mapping of ssh ports on the vms. So by default, the Azure provider
retu... | keyword[def] identifier[get_ips] ( identifier[self] , identifier[instance_id] ):
literal[string]
identifier[self] . identifier[_restore_from_storage] ( identifier[instance_id] )
keyword[if] identifier[self] . identifier[_start_failed] :
keyword[raise] identifier[Exception] (... | def get_ips(self, instance_id):
"""Retrieves the private and public ip addresses for a given instance.
Note: Azure normally provides access to vms from a shared load
balancer IP and
mapping of ssh ports on the vms. So by default, the Azure provider
returns strings
of the form... |
def valid_max_age(number):
"Validate a cookie Max-Age"
if isinstance(number, basestring):
try:
number = long(number)
except (ValueError, TypeError):
return False
if number >= 0 and number % 1 == 0:
return True
return False | def function[valid_max_age, parameter[number]]:
constant[Validate a cookie Max-Age]
if call[name[isinstance], parameter[name[number], name[basestring]]] begin[:]
<ast.Try object at 0x7da18f00ca90>
if <ast.BoolOp object at 0x7da18f00f790> begin[:]
return[constant[True]]
return... | keyword[def] identifier[valid_max_age] ( identifier[number] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[number] , identifier[basestring] ):
keyword[try] :
identifier[number] = identifier[long] ( identifier[number] )
keyword[except] ( identifier[ValueEr... | def valid_max_age(number):
"""Validate a cookie Max-Age"""
if isinstance(number, basestring):
try:
number = long(number) # depends on [control=['try'], data=[]]
except (ValueError, TypeError):
return False # depends on [control=['except'], data=[]] # depends on [contro... |
def uniform(self, key, min_value=0., max_value=1.):
"""Returns a random number between min_value and max_value"""
return min_value + self._random(key) * (max_value - min_value) | def function[uniform, parameter[self, key, min_value, max_value]]:
constant[Returns a random number between min_value and max_value]
return[binary_operation[name[min_value] + binary_operation[call[name[self]._random, parameter[name[key]]] * binary_operation[name[max_value] - name[min_value]]]]] | keyword[def] identifier[uniform] ( identifier[self] , identifier[key] , identifier[min_value] = literal[int] , identifier[max_value] = literal[int] ):
literal[string]
keyword[return] identifier[min_value] + identifier[self] . identifier[_random] ( identifier[key] )*( identifier[max_value] - identi... | def uniform(self, key, min_value=0.0, max_value=1.0):
"""Returns a random number between min_value and max_value"""
return min_value + self._random(key) * (max_value - min_value) |
def haversine_distance(origin, destination):
"""
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
--------
>>> munich = (... | def function[haversine_distance, parameter[origin, destination]]:
constant[
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
... | keyword[def] identifier[haversine_distance] ( identifier[origin] , identifier[destination] ):
literal[string]
identifier[lat1] , identifier[lon1] = identifier[origin]
identifier[lat2] , identifier[lon2] = identifier[destination]
keyword[if] keyword[not] (- literal[int] <= identifier[lat1] <= l... | def haversine_distance(origin, destination):
"""
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
--------
>>> munich = (... |
def post(self, request, *args, **kwargs):
""" Handles POST requests. """
return self.lock(request, *args, **kwargs) | def function[post, parameter[self, request]]:
constant[ Handles POST requests. ]
return[call[name[self].lock, parameter[name[request], <ast.Starred object at 0x7da18ede6470>]]] | keyword[def] identifier[post] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[lock] ( identifier[request] ,* identifier[args] ,** identifier[kwargs] ) | def post(self, request, *args, **kwargs):
""" Handles POST requests. """
return self.lock(request, *args, **kwargs) |
def set_cache_dir(directory):
"""Set the directory to cache JSON responses from most API endpoints.
"""
global cache_dir
if directory is None:
cache_dir = None
return
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise... | def function[set_cache_dir, parameter[directory]]:
constant[Set the directory to cache JSON responses from most API endpoints.
]
<ast.Global object at 0x7da1b274a2c0>
if compare[name[directory] is constant[None]] begin[:]
variable[cache_dir] assign[=] constant[None]
retur... | keyword[def] identifier[set_cache_dir] ( identifier[directory] ):
literal[string]
keyword[global] identifier[cache_dir]
keyword[if] identifier[directory] keyword[is] keyword[None] :
identifier[cache_dir] = keyword[None]
keyword[return]
keyword[if] keyword[not] identif... | def set_cache_dir(directory):
"""Set the directory to cache JSON responses from most API endpoints.
"""
global cache_dir
if directory is None:
cache_dir = None
return # depends on [control=['if'], data=[]]
if not os.path.exists(directory):
os.makedirs(directory) # depends o... |
def get_mmcif(code, outfile=None):
""" Get mmcif file associated with code from PDBE.
Parameters
----------
code : str
PDB code.
outfile : str
Filepath. Writes returned value to this file.
Returns
-------
mmcif_file : str
Filepath to the mmcif file.
"""
... | def function[get_mmcif, parameter[code, outfile]]:
constant[ Get mmcif file associated with code from PDBE.
Parameters
----------
code : str
PDB code.
outfile : str
Filepath. Writes returned value to this file.
Returns
-------
mmcif_file : str
Filepath to th... | keyword[def] identifier[get_mmcif] ( identifier[code] , identifier[outfile] = keyword[None] ):
literal[string]
identifier[pdbe_url] = literal[string] . identifier[format] ( identifier[code] )
identifier[r] = identifier[requests] . identifier[get] ( identifier[pdbe_url] )
keyword[if] identifier[r... | def get_mmcif(code, outfile=None):
""" Get mmcif file associated with code from PDBE.
Parameters
----------
code : str
PDB code.
outfile : str
Filepath. Writes returned value to this file.
Returns
-------
mmcif_file : str
Filepath to the mmcif file.
"""
... |
def splitpath(self):
""" p.splitpath() -> Return ``(p.parent, p.name)``.
.. seealso:: :attr:`parent`, :attr:`name`, :func:`os.path.split`
"""
parent, child = self.module.split(self)
return self._next_class(parent), child | def function[splitpath, parameter[self]]:
constant[ p.splitpath() -> Return ``(p.parent, p.name)``.
.. seealso:: :attr:`parent`, :attr:`name`, :func:`os.path.split`
]
<ast.Tuple object at 0x7da18f09eaa0> assign[=] call[name[self].module.split, parameter[name[self]]]
return[tuple[[<a... | keyword[def] identifier[splitpath] ( identifier[self] ):
literal[string]
identifier[parent] , identifier[child] = identifier[self] . identifier[module] . identifier[split] ( identifier[self] )
keyword[return] identifier[self] . identifier[_next_class] ( identifier[parent] ), identifier[ch... | def splitpath(self):
""" p.splitpath() -> Return ``(p.parent, p.name)``.
.. seealso:: :attr:`parent`, :attr:`name`, :func:`os.path.split`
"""
(parent, child) = self.module.split(self)
return (self._next_class(parent), child) |
def tally(self, chain):
"""Adds current value to trace."""
try:
# I changed str(x) to '%f'%x to solve a bug appearing due to
# locale settings. In french for instance, str prints a comma
# instead of a colon to indicate the decimal, which confuses
# the d... | def function[tally, parameter[self, chain]]:
constant[Adds current value to trace.]
<ast.Try object at 0x7da18c4cd690>
variable[query] assign[=] binary_operation[constant[INSERT INTO [%s] (recid, trace, %s) values (NULL, %s, %s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7... | keyword[def] identifier[tally] ( identifier[self] , identifier[chain] ):
literal[string]
keyword[try] :
identifier[valstring] = literal[string] . identifier[join] (
[ literal[string] %
identifier[x] keywor... | def tally(self, chain):
"""Adds current value to trace."""
try:
# I changed str(x) to '%f'%x to solve a bug appearing due to
# locale settings. In french for instance, str prints a comma
# instead of a colon to indicate the decimal, which confuses
# the database into thinking tha... |
def _add_scalar(self, scalar):
"""Returns E(a + b), given self=E(a) and b.
Args:
scalar: an int or float b, to be added to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~P... | def function[_add_scalar, parameter[self, scalar]]:
constant[Returns E(a + b), given self=E(a) and b.
Args:
scalar: an int or float b, to be added to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) m... | keyword[def] identifier[_add_scalar] ( identifier[self] , identifier[scalar] ):
literal[string]
identifier[encoded] = identifier[EncodedNumber] . identifier[encode] ( identifier[self] . identifier[public_key] , identifier[scalar] ,
identifier[max_exponent] = identifier[self] . identifier[e... | def _add_scalar(self, scalar):
"""Returns E(a + b), given self=E(a) and b.
Args:
scalar: an int or float b, to be added to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~Paill... |
def find_by_ids(self, _ids, projection=None, **kwargs):
"""
Does a big _id:$in query on any iterator
"""
id_list = [ObjectId(_id) for _id in _ids]
if len(_ids) == 0:
return [] # FIXME : this should be an empty cursor !
# Optimized path when only fetchi... | def function[find_by_ids, parameter[self, _ids, projection]]:
constant[
Does a big _id:$in query on any iterator
]
variable[id_list] assign[=] <ast.ListComp object at 0x7da1b26d6440>
if compare[call[name[len], parameter[name[_ids]]] equal[==] constant[0]] begin[:]
ret... | keyword[def] identifier[find_by_ids] ( identifier[self] , identifier[_ids] , identifier[projection] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[id_list] =[ identifier[ObjectId] ( identifier[_id] ) keyword[for] identifier[_id] keyword[in] identifier[_ids] ]
key... | def find_by_ids(self, _ids, projection=None, **kwargs):
"""
Does a big _id:$in query on any iterator
"""
id_list = [ObjectId(_id) for _id in _ids]
if len(_ids) == 0:
return [] # FIXME : this should be an empty cursor ! # depends on [control=['if'], data=[]]
# Optimized path... |
def save_file(filename, source, folder="Downloads"):
"""
Download and save a file at path
:param filename: The name of the file
:param source: The location of the resource online
:param folder: The directory the file will be saved in
:return: None
"""
r = requests.get(source,... | def function[save_file, parameter[filename, source, folder]]:
constant[
Download and save a file at path
:param filename: The name of the file
:param source: The location of the resource online
:param folder: The directory the file will be saved in
:return: None
]
variable[r] as... | keyword[def] identifier[save_file] ( identifier[filename] , identifier[source] , identifier[folder] = literal[string] ):
literal[string]
identifier[r] = identifier[requests] . identifier[get] ( identifier[source] , identifier[stream] = keyword[True] )
keyword[if] identifier[r] . identifier[statu... | def save_file(filename, source, folder='Downloads'):
"""
Download and save a file at path
:param filename: The name of the file
:param source: The location of the resource online
:param folder: The directory the file will be saved in
:return: None
"""
r = requests.get(source, stream=Tru... |
def get_subjects(self):
"""
Returns the list of subject names present in the schema registry.
"""
res = requests.get(self._url('/subjects'))
raise_if_failed(res)
return res.json() | def function[get_subjects, parameter[self]]:
constant[
Returns the list of subject names present in the schema registry.
]
variable[res] assign[=] call[name[requests].get, parameter[call[name[self]._url, parameter[constant[/subjects]]]]]
call[name[raise_if_failed], parameter[name... | keyword[def] identifier[get_subjects] ( identifier[self] ):
literal[string]
identifier[res] = identifier[requests] . identifier[get] ( identifier[self] . identifier[_url] ( literal[string] ))
identifier[raise_if_failed] ( identifier[res] )
keyword[return] identifier[res] . identi... | def get_subjects(self):
"""
Returns the list of subject names present in the schema registry.
"""
res = requests.get(self._url('/subjects'))
raise_if_failed(res)
return res.json() |
def calculate(self, batch_info):
""" Calculate value of a metric """
value = self._value_function(batch_info['data'], batch_info['target'], batch_info['output'])
self.storage.append(value) | def function[calculate, parameter[self, batch_info]]:
constant[ Calculate value of a metric ]
variable[value] assign[=] call[name[self]._value_function, parameter[call[name[batch_info]][constant[data]], call[name[batch_info]][constant[target]], call[name[batch_info]][constant[output]]]]
call[nam... | keyword[def] identifier[calculate] ( identifier[self] , identifier[batch_info] ):
literal[string]
identifier[value] = identifier[self] . identifier[_value_function] ( identifier[batch_info] [ literal[string] ], identifier[batch_info] [ literal[string] ], identifier[batch_info] [ literal[string] ])
... | def calculate(self, batch_info):
""" Calculate value of a metric """
value = self._value_function(batch_info['data'], batch_info['target'], batch_info['output'])
self.storage.append(value) |
def run_command_orig(cmd):
""" No idea how th f to get this to work """
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode == 0:
os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
else:
... | def function[run_command_orig, parameter[cmd]]:
constant[ No idea how th f to get this to work ]
variable[process] assign[=] call[name[subprocess].Popen, parameter[name[cmd]]]
<ast.Tuple object at 0x7da2054a7550> assign[=] call[name[process].communicate, parameter[]]
if compare[name[proc... | keyword[def] identifier[run_command_orig] ( identifier[cmd] ):
literal[string]
identifier[process] = identifier[subprocess] . identifier[Popen] ( identifier[cmd] , identifier[shell] = keyword[True] , identifier[stdout] = identifier[subprocess] . identifier[PIPE] , identifier[stderr] = identifier[subprocess... | def run_command_orig(cmd):
""" No idea how th f to get this to work """
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = process.communicate()
if process.returncode == 0:
os.killpg(os.getpgid(pro.pid), signal.SIGTERM) # depends on [c... |
def cables_from_source(path, predicate=None):
"""\
Returns a generator with ``ICable`` instances.
`path`
Either a directory or a CSV file.
`predicate`
A predicate that is invoked for each cable reference identifier.
If the predicate evaluates to ``False`` the cable is ignored.
... | def function[cables_from_source, parameter[path, predicate]]:
constant[ Returns a generator with ``ICable`` instances.
`path`
Either a directory or a CSV file.
`predicate`
A predicate that is invoked for each cable reference identifier.
If the predicate evaluates to ``False``... | keyword[def] identifier[cables_from_source] ( identifier[path] , identifier[predicate] = keyword[None] ):
literal[string]
keyword[return] identifier[cables_from_directory] ( identifier[path] , identifier[predicate] ) keyword[if] identifier[os] . identifier[path] . identifier[isdir] ( identifier[path] ) k... | def cables_from_source(path, predicate=None):
""" Returns a generator with ``ICable`` instances.
`path`
Either a directory or a CSV file.
`predicate`
A predicate that is invoked for each cable reference identifier.
If the predicate evaluates to ``False`` the cable is ignored.
... |
def init(self, back=None):
'''
Initialize the backend, only do so if the fs supports an init function
'''
back = self.backends(back)
for fsb in back:
fstr = '{0}.init'.format(fsb)
if fstr in self.servers:
self.servers[fstr]() | def function[init, parameter[self, back]]:
constant[
Initialize the backend, only do so if the fs supports an init function
]
variable[back] assign[=] call[name[self].backends, parameter[name[back]]]
for taget[name[fsb]] in starred[name[back]] begin[:]
variable[fs... | keyword[def] identifier[init] ( identifier[self] , identifier[back] = keyword[None] ):
literal[string]
identifier[back] = identifier[self] . identifier[backends] ( identifier[back] )
keyword[for] identifier[fsb] keyword[in] identifier[back] :
identifier[fstr] = literal[stri... | def init(self, back=None):
"""
Initialize the backend, only do so if the fs supports an init function
"""
back = self.backends(back)
for fsb in back:
fstr = '{0}.init'.format(fsb)
if fstr in self.servers:
self.servers[fstr]() # depends on [control=['if'], data=['... |
def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pymssql.
"""
return create_engine(
_create_mssql_pymssql(username, password, host, port, database),
**kwargs
) | def function[create_mssql_pymssql, parameter[username, password, host, port, database]]:
constant[
create an engine connected to a mssql database using pymssql.
]
return[call[name[create_engine], parameter[call[name[_create_mssql_pymssql], parameter[name[username], name[password], name[host], name[p... | keyword[def] identifier[create_mssql_pymssql] ( identifier[username] , identifier[password] , identifier[host] , identifier[port] , identifier[database] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[create_engine] (
identifier[_create_mssql_pymssql] ( identifier[username] , ide... | def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
'\n create an engine connected to a mssql database using pymssql.\n '
return create_engine(_create_mssql_pymssql(username, password, host, port, database), **kwargs) |
def prefix_add(self, prefix, next_hop=None, route_dist=None):
""" This method adds a new prefix to be advertised.
``prefix`` must be the string representation of an IP network
(e.g., 10.1.1.0/24).
``next_hop`` specifies the next hop address for this
prefix. This parameter is ne... | def function[prefix_add, parameter[self, prefix, next_hop, route_dist]]:
constant[ This method adds a new prefix to be advertised.
``prefix`` must be the string representation of an IP network
(e.g., 10.1.1.0/24).
``next_hop`` specifies the next hop address for this
prefix. Thi... | keyword[def] identifier[prefix_add] ( identifier[self] , identifier[prefix] , identifier[next_hop] = keyword[None] , identifier[route_dist] = keyword[None] ):
literal[string]
identifier[func_name] = literal[string]
identifier[networks] ={
identifier[PREFIX] : identifier[prefix] ,... | def prefix_add(self, prefix, next_hop=None, route_dist=None):
""" This method adds a new prefix to be advertised.
``prefix`` must be the string representation of an IP network
(e.g., 10.1.1.0/24).
``next_hop`` specifies the next hop address for this
prefix. This parameter is necess... |
def _delete_cells(self, column_family_id, columns, time_range=None, state=None):
"""Helper for :meth:`delete_cell` and :meth:`delete_cells`.
``state`` is unused by :class:`DirectRow` but is used by
subclasses.
:type column_family_id: str
:param column_family_id: The column fami... | def function[_delete_cells, parameter[self, column_family_id, columns, time_range, state]]:
constant[Helper for :meth:`delete_cell` and :meth:`delete_cells`.
``state`` is unused by :class:`DirectRow` but is used by
subclasses.
:type column_family_id: str
:param column_family_id... | keyword[def] identifier[_delete_cells] ( identifier[self] , identifier[column_family_id] , identifier[columns] , identifier[time_range] = keyword[None] , identifier[state] = keyword[None] ):
literal[string]
identifier[mutations_list] = identifier[self] . identifier[_get_mutations] ( identifier[stat... | def _delete_cells(self, column_family_id, columns, time_range=None, state=None):
"""Helper for :meth:`delete_cell` and :meth:`delete_cells`.
``state`` is unused by :class:`DirectRow` but is used by
subclasses.
:type column_family_id: str
:param column_family_id: The column family t... |
def localopt(self, forcefield='mmff94', steps=500):
"""
A wrapper to pybel's localopt method to optimize a Molecule.
Args:
forcefield: Default is mmff94. Options are 'gaff', 'ghemical',
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500.
"""
... | def function[localopt, parameter[self, forcefield, steps]]:
constant[
A wrapper to pybel's localopt method to optimize a Molecule.
Args:
forcefield: Default is mmff94. Options are 'gaff', 'ghemical',
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500.
... | keyword[def] identifier[localopt] ( identifier[self] , identifier[forcefield] = literal[string] , identifier[steps] = literal[int] ):
literal[string]
identifier[pbmol] = identifier[pb] . identifier[Molecule] ( identifier[self] . identifier[_obmol] )
identifier[pbmol] . identifier[localopt]... | def localopt(self, forcefield='mmff94', steps=500):
"""
A wrapper to pybel's localopt method to optimize a Molecule.
Args:
forcefield: Default is mmff94. Options are 'gaff', 'ghemical',
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500.
"""
pb... |
def from_range(cls, data, name=None, dtype=None, **kwargs):
""" Create RangeIndex from a range object. """
if not isinstance(data, range):
raise TypeError(
'{0}(...) must be called with object coercible to a '
'range, {1} was passed'.format(cls.__name__, repr(... | def function[from_range, parameter[cls, data, name, dtype]]:
constant[ Create RangeIndex from a range object. ]
if <ast.UnaryOp object at 0x7da18f813e80> begin[:]
<ast.Raise object at 0x7da18f812aa0>
<ast.Tuple object at 0x7da2045676d0> assign[=] tuple[[<ast.Attribute object at 0x7da2045... | keyword[def] identifier[from_range] ( identifier[cls] , identifier[data] , identifier[name] = keyword[None] , identifier[dtype] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[data] , identifier[range] ):
keyword[... | def from_range(cls, data, name=None, dtype=None, **kwargs):
""" Create RangeIndex from a range object. """
if not isinstance(data, range):
raise TypeError('{0}(...) must be called with object coercible to a range, {1} was passed'.format(cls.__name__, repr(data))) # depends on [control=['if'], data=[]]
... |
def iterfields(klass):
"""Iterate over the input class members and yield its TypedFields.
Args:
klass: A class (usually an Entity subclass).
Yields:
(class attribute name, TypedField instance) tuples.
"""
is_field = lambda x: isinstance(x, TypedField)
for name, field in inspec... | def function[iterfields, parameter[klass]]:
constant[Iterate over the input class members and yield its TypedFields.
Args:
klass: A class (usually an Entity subclass).
Yields:
(class attribute name, TypedField instance) tuples.
]
variable[is_field] assign[=] <ast.Lambda obj... | keyword[def] identifier[iterfields] ( identifier[klass] ):
literal[string]
identifier[is_field] = keyword[lambda] identifier[x] : identifier[isinstance] ( identifier[x] , identifier[TypedField] )
keyword[for] identifier[name] , identifier[field] keyword[in] identifier[inspect] . identifier[getmem... | def iterfields(klass):
"""Iterate over the input class members and yield its TypedFields.
Args:
klass: A class (usually an Entity subclass).
Yields:
(class attribute name, TypedField instance) tuples.
"""
is_field = lambda x: isinstance(x, TypedField)
for (name, field) in inspe... |
def _load_old_defaults(self, old_version):
"""Read old defaults"""
old_defaults = cp.ConfigParser()
if check_version(old_version, '3.0.0', '<='):
path = get_module_source_path('spyder')
else:
path = osp.dirname(self.filename())
path = osp.join(path,... | def function[_load_old_defaults, parameter[self, old_version]]:
constant[Read old defaults]
variable[old_defaults] assign[=] call[name[cp].ConfigParser, parameter[]]
if call[name[check_version], parameter[name[old_version], constant[3.0.0], constant[<=]]] begin[:]
variable[path] ... | keyword[def] identifier[_load_old_defaults] ( identifier[self] , identifier[old_version] ):
literal[string]
identifier[old_defaults] = identifier[cp] . identifier[ConfigParser] ()
keyword[if] identifier[check_version] ( identifier[old_version] , literal[string] , literal[string] ):
... | def _load_old_defaults(self, old_version):
"""Read old defaults"""
old_defaults = cp.ConfigParser()
if check_version(old_version, '3.0.0', '<='):
path = get_module_source_path('spyder') # depends on [control=['if'], data=[]]
else:
path = osp.dirname(self.filename())
path = osp.join(... |
def __checkIfBestCompletedModel(self):
"""
Reads the current "best model" for the job and returns whether or not the
current model is better than the "best model" stored for the job
Returns: (isBetter, storedBest, origResultsStr)
isBetter:
True if the current model is better than the stored ... | def function[__checkIfBestCompletedModel, parameter[self]]:
constant[
Reads the current "best model" for the job and returns whether or not the
current model is better than the "best model" stored for the job
Returns: (isBetter, storedBest, origResultsStr)
isBetter:
True if the current m... | keyword[def] identifier[__checkIfBestCompletedModel] ( identifier[self] ):
literal[string]
identifier[jobResultsStr] = identifier[self] . identifier[_jobsDAO] . identifier[jobGetFields] ( identifier[self] . identifier[_jobID] ,[ literal[string] ])[ literal[int] ]
keyword[if] identifier[jobResultsSt... | def __checkIfBestCompletedModel(self):
"""
Reads the current "best model" for the job and returns whether or not the
current model is better than the "best model" stored for the job
Returns: (isBetter, storedBest, origResultsStr)
isBetter:
True if the current model is better than the stored ... |
def print_stats(genomes):
"""
print substitution rate data to table
genomes[genome][contig][sample] = \
{'bp_stats':{}, 'sub_rates'[locus] = {ref PnPs, consensus PnPs}}
"""
header = ['#genome', 'contig', 'locus', 'position', 'strand', 'length', \
'sample', 'coverage', \
... | def function[print_stats, parameter[genomes]]:
constant[
print substitution rate data to table
genomes[genome][contig][sample] = {'bp_stats':{}, 'sub_rates'[locus] = {ref PnPs, consensus PnPs}}
]
variable[header] assign[=] list[[<ast.Constant object at 0x7da18dc071c0>, <ast.Const... | keyword[def] identifier[print_stats] ( identifier[genomes] ):
literal[string]
identifier[header] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[s... | def print_stats(genomes):
"""
print substitution rate data to table
genomes[genome][contig][sample] = {'bp_stats':{}, 'sub_rates'[locus] = {ref PnPs, consensus PnPs}}
"""
header = ['#genome', 'contig', 'locus', 'position', 'strand', 'length', 'sample', 'coverage', 'ref. Pn/Ps', 'ref SNP ... |
def _install(self, args):
'''
Install a package from a repo
'''
if len(args) < 2:
raise SPMInvocationError('A package must be specified')
caller_opts = self.opts.copy()
caller_opts['file_client'] = 'local'
self.caller = salt.client.Caller(mopts=caller... | def function[_install, parameter[self, args]]:
constant[
Install a package from a repo
]
if compare[call[name[len], parameter[name[args]]] less[<] constant[2]] begin[:]
<ast.Raise object at 0x7da20c6c4e50>
variable[caller_opts] assign[=] call[name[self].opts.copy, paramet... | keyword[def] identifier[_install] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )< literal[int] :
keyword[raise] identifier[SPMInvocationError] ( literal[string] )
identifier[caller_opts] = identifier[self] . identif... | def _install(self, args):
"""
Install a package from a repo
"""
if len(args) < 2:
raise SPMInvocationError('A package must be specified') # depends on [control=['if'], data=[]]
caller_opts = self.opts.copy()
caller_opts['file_client'] = 'local'
self.caller = salt.client.Call... |
def _handle_outliers(self, p_o):
""" Sets observation probabilities of outliers to uniform if ignore_outliers is set.
Parameters
----------
p_o : ndarray((T, N))
output probabilities
"""
if self.ignore_outliers:
outliers = np.where(p_o.sum(axis=1)=... | def function[_handle_outliers, parameter[self, p_o]]:
constant[ Sets observation probabilities of outliers to uniform if ignore_outliers is set.
Parameters
----------
p_o : ndarray((T, N))
output probabilities
]
if name[self].ignore_outliers begin[:]
... | keyword[def] identifier[_handle_outliers] ( identifier[self] , identifier[p_o] ):
literal[string]
keyword[if] identifier[self] . identifier[ignore_outliers] :
identifier[outliers] = identifier[np] . identifier[where] ( identifier[p_o] . identifier[sum] ( identifier[axis] = literal[int... | def _handle_outliers(self, p_o):
""" Sets observation probabilities of outliers to uniform if ignore_outliers is set.
Parameters
----------
p_o : ndarray((T, N))
output probabilities
"""
if self.ignore_outliers:
outliers = np.where(p_o.sum(axis=1) == 0)[0]
... |
def _getsetting(setting, default):
"""Get `setting` if set, fallback to `default` if not
This method tries to return the value of the specified setting from Django's
settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If
this fails for any reason, the value supplied in `default` will... | def function[_getsetting, parameter[setting, default]]:
constant[Get `setting` if set, fallback to `default` if not
This method tries to return the value of the specified setting from Django's
settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If
this fails for any reason, the v... | keyword[def] identifier[_getsetting] ( identifier[setting] , identifier[default] ):
literal[string]
identifier[setting] = identifier[_DJANGO_SETTING_PREFIX] + identifier[setting]
keyword[try] :
keyword[return] identifier[getattr] ( identifier[settings] , identifier[setting] )
keyword... | def _getsetting(setting, default):
"""Get `setting` if set, fallback to `default` if not
This method tries to return the value of the specified setting from Django's
settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If
this fails for any reason, the value supplied in `default` will... |
def set_(key,
value,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Set a key on the memcached server, overwriting the value if it exists.
CLI Example:
.. code-block:: bash
salt '*' memcache... | def function[set_, parameter[key, value, host, port, time, min_compress_len]]:
constant[
Set a key on the memcached server, overwriting the value if it exists.
CLI Example:
.. code-block:: bash
salt '*' memcached.set <key> <value>
]
if <ast.UnaryOp object at 0x7da1b2161d80> be... | keyword[def] identifier[set_] ( identifier[key] ,
identifier[value] ,
identifier[host] = identifier[DEFAULT_HOST] ,
identifier[port] = identifier[DEFAULT_PORT] ,
identifier[time] = identifier[DEFAULT_TIME] ,
identifier[min_compress_len] = identifier[DEFAULT_MIN_COMPRESS_LEN] ):
literal[string]
keyword... | def set_(key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
"""
Set a key on the memcached server, overwriting the value if it exists.
CLI Example:
.. code-block:: bash
salt '*' memcached.set <key> <value>
"""
if not isinst... |
def onecmd_plus_hooks(self, line):
''' Trigger hooks after command. '''
if not line:
return self.emptyline()
return Cmd.onecmd_plus_hooks(self, line) | def function[onecmd_plus_hooks, parameter[self, line]]:
constant[ Trigger hooks after command. ]
if <ast.UnaryOp object at 0x7da1b0745420> begin[:]
return[call[name[self].emptyline, parameter[]]]
return[call[name[Cmd].onecmd_plus_hooks, parameter[name[self], name[line]]]] | keyword[def] identifier[onecmd_plus_hooks] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] keyword[not] identifier[line] :
keyword[return] identifier[self] . identifier[emptyline] ()
keyword[return] identifier[Cmd] . identifier[onecmd_plus_hooks] ( ide... | def onecmd_plus_hooks(self, line):
""" Trigger hooks after command. """
if not line:
return self.emptyline() # depends on [control=['if'], data=[]]
return Cmd.onecmd_plus_hooks(self, line) |
def on_epoch_end(self, last_metrics, **kwargs):
"Put the various losses in the recorder."
return add_metrics(last_metrics, [s.smooth for k,s in self.smootheners.items()]) | def function[on_epoch_end, parameter[self, last_metrics]]:
constant[Put the various losses in the recorder.]
return[call[name[add_metrics], parameter[name[last_metrics], <ast.ListComp object at 0x7da1b1e171c0>]]] | keyword[def] identifier[on_epoch_end] ( identifier[self] , identifier[last_metrics] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[add_metrics] ( identifier[last_metrics] ,[ identifier[s] . identifier[smooth] keyword[for] identifier[k] , identifier[s] keyword[in] identifi... | def on_epoch_end(self, last_metrics, **kwargs):
"""Put the various losses in the recorder."""
return add_metrics(last_metrics, [s.smooth for (k, s) in self.smootheners.items()]) |
def get_partition_names_ps(self, db_name, tbl_name, part_vals, max_parts):
"""
Parameters:
- db_name
- tbl_name
- part_vals
- max_parts
"""
self.send_get_partition_names_ps(db_name, tbl_name, part_vals, max_parts)
return self.recv_get_partition_names_ps() | def function[get_partition_names_ps, parameter[self, db_name, tbl_name, part_vals, max_parts]]:
constant[
Parameters:
- db_name
- tbl_name
- part_vals
- max_parts
]
call[name[self].send_get_partition_names_ps, parameter[name[db_name], name[tbl_name], name[part_vals], name[max... | keyword[def] identifier[get_partition_names_ps] ( identifier[self] , identifier[db_name] , identifier[tbl_name] , identifier[part_vals] , identifier[max_parts] ):
literal[string]
identifier[self] . identifier[send_get_partition_names_ps] ( identifier[db_name] , identifier[tbl_name] , identifier[part_vals] ... | def get_partition_names_ps(self, db_name, tbl_name, part_vals, max_parts):
"""
Parameters:
- db_name
- tbl_name
- part_vals
- max_parts
"""
self.send_get_partition_names_ps(db_name, tbl_name, part_vals, max_parts)
return self.recv_get_partition_names_ps() |
def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False):
"""Opens a new gcs file for writing."""
if use_tmp_bucket:
bucket = cls._get_tmp_gcs_bucket(writer_spec)
account_id = cls._get_tmp_account_id(writer_spec)
else:
bucket = cls._get_gcs_bucket(writer_spec)
account_... | def function[_open_file, parameter[cls, writer_spec, filename_suffix, use_tmp_bucket]]:
constant[Opens a new gcs file for writing.]
if name[use_tmp_bucket] begin[:]
variable[bucket] assign[=] call[name[cls]._get_tmp_gcs_bucket, parameter[name[writer_spec]]]
variable[accou... | keyword[def] identifier[_open_file] ( identifier[cls] , identifier[writer_spec] , identifier[filename_suffix] , identifier[use_tmp_bucket] = keyword[False] ):
literal[string]
keyword[if] identifier[use_tmp_bucket] :
identifier[bucket] = identifier[cls] . identifier[_get_tmp_gcs_bucket] ( identifier... | def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False):
"""Opens a new gcs file for writing."""
if use_tmp_bucket:
bucket = cls._get_tmp_gcs_bucket(writer_spec)
account_id = cls._get_tmp_account_id(writer_spec) # depends on [control=['if'], data=[]]
else:
bucket = c... |
def bar(self,xdata,ydata,disp=True,**kwargs):
'''Displays a bar graph.
xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example.
ydata: list of values associated with categories i... | def function[bar, parameter[self, xdata, ydata, disp]]:
constant[Displays a bar graph.
xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example.
ydata: list of values associated w... | keyword[def] identifier[bar] ( identifier[self] , identifier[xdata] , identifier[ydata] , identifier[disp] = keyword[True] ,** identifier[kwargs] ):
literal[string]
identifier[data] = identifier[combineData] ( identifier[xdata] , identifier[ydata] , identifier[self] . identifier[xlabel] )... | def bar(self, xdata, ydata, disp=True, **kwargs):
"""Displays a bar graph.
xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example.
ydata: list of values associated with categories i... |
def GetPathFromLink(resource_link, resource_type=''):
"""Gets path from resource link with optional resource type
:param str resource_link:
:param str resource_type:
:return:
Path from resource link with resource type appended (if provided).
:rtype: str
"""
resource_link = TrimBegi... | def function[GetPathFromLink, parameter[resource_link, resource_type]]:
constant[Gets path from resource link with optional resource type
:param str resource_link:
:param str resource_type:
:return:
Path from resource link with resource type appended (if provided).
:rtype: str
]
... | keyword[def] identifier[GetPathFromLink] ( identifier[resource_link] , identifier[resource_type] = literal[string] ):
literal[string]
identifier[resource_link] = identifier[TrimBeginningAndEndingSlashes] ( identifier[resource_link] )
keyword[if] identifier[IsNameBased] ( identifier[resource_link] ):... | def GetPathFromLink(resource_link, resource_type=''):
"""Gets path from resource link with optional resource type
:param str resource_link:
:param str resource_type:
:return:
Path from resource link with resource type appended (if provided).
:rtype: str
"""
resource_link = TrimBegi... |
def bytes_block_cast(block,
include_text=True,
include_link_tokens=True,
include_css=True,
include_features=True,
**kwargs):
"""
Converts any string-like items in input Block object to bytes-like values,
... | def function[bytes_block_cast, parameter[block, include_text, include_link_tokens, include_css, include_features]]:
constant[
Converts any string-like items in input Block object to bytes-like values,
with respect to python version
Parameters
----------
block : blocks.Block
any stri... | keyword[def] identifier[bytes_block_cast] ( identifier[block] ,
identifier[include_text] = keyword[True] ,
identifier[include_link_tokens] = keyword[True] ,
identifier[include_css] = keyword[True] ,
identifier[include_features] = keyword[True] ,
** identifier[kwargs] ):
literal[string]
keyword[if] ide... | def bytes_block_cast(block, include_text=True, include_link_tokens=True, include_css=True, include_features=True, **kwargs):
"""
Converts any string-like items in input Block object to bytes-like values,
with respect to python version
Parameters
----------
block : blocks.Block
any strin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.