code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def resolve_function(slither, contract_name, function_name):
"""
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved func... | def function[resolve_function, parameter[slither, contract_name, function_name]]:
constant[
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:re... | keyword[def] identifier[resolve_function] ( identifier[slither] , identifier[contract_name] , identifier[function_name] ):
literal[string]
identifier[contract] = identifier[slither] . identifier[get_contract_from_name] ( identifier[contract_name] )
keyword[if] identifier[contract] keyword... | def resolve_function(slither, contract_name, function_name):
"""
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved func... |
def search_mappings(kb, key=None, value=None, match_type=None,
sortby=None, page=None, per_page=None):
"""Search tags for knowledge."""
if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']:
return pagination.RestfulSQLAlchemyPagination(
api.query_kb_... | def function[search_mappings, parameter[kb, key, value, match_type, sortby, page, per_page]]:
constant[Search tags for knowledge.]
if compare[name[kb].kbtype equal[==] call[name[models].KnwKB.KNWKB_TYPES][constant[written_as]]] begin[:]
return[call[name[pagination].RestfulSQLAlchemyPagination, p... | keyword[def] identifier[search_mappings] ( identifier[kb] , identifier[key] = keyword[None] , identifier[value] = keyword[None] , identifier[match_type] = keyword[None] ,
identifier[sortby] = keyword[None] , identifier[page] = keyword[None] , identifier[per_page] = keyword[None] ):
literal[string]
... | def search_mappings(kb, key=None, value=None, match_type=None, sortby=None, page=None, per_page=None):
"""Search tags for knowledge."""
if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']:
return pagination.RestfulSQLAlchemyPagination(api.query_kb_mappings(kbid=kb.id, key=key or '', value=value or ''... |
def prepare_untran(feat_type, tgt_dir, untran_dir):
""" Preprocesses untranscribed audio."""
org_dir = str(untran_dir)
wav_dir = os.path.join(str(tgt_dir), "wav", "untranscribed")
feat_dir = os.path.join(str(tgt_dir), "feat", "untranscribed")
if not os.path.isdir(wav_dir):
os.makedirs(wav_di... | def function[prepare_untran, parameter[feat_type, tgt_dir, untran_dir]]:
constant[ Preprocesses untranscribed audio.]
variable[org_dir] assign[=] call[name[str], parameter[name[untran_dir]]]
variable[wav_dir] assign[=] call[name[os].path.join, parameter[call[name[str], parameter[name[tgt_dir]]],... | keyword[def] identifier[prepare_untran] ( identifier[feat_type] , identifier[tgt_dir] , identifier[untran_dir] ):
literal[string]
identifier[org_dir] = identifier[str] ( identifier[untran_dir] )
identifier[wav_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[str] ( identifier[t... | def prepare_untran(feat_type, tgt_dir, untran_dir):
""" Preprocesses untranscribed audio."""
org_dir = str(untran_dir)
wav_dir = os.path.join(str(tgt_dir), 'wav', 'untranscribed')
feat_dir = os.path.join(str(tgt_dir), 'feat', 'untranscribed')
if not os.path.isdir(wav_dir):
os.makedirs(wav_di... |
def annotations(obj: BioCCollection or BioCDocument or BioCPassage or BioCSentence,
docid: str = None, level: int = PASSAGE) -> Generator[BioCAnnotation, None, None]:
"""
Get all annotations in document id.
Args:
obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence
... | def function[annotations, parameter[obj, docid, level]]:
constant[
Get all annotations in document id.
Args:
obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence
docid: document id. If None, all documents
level: one of DOCUMENT, PASSAGE, SENTENCE
Yields:
... | keyword[def] identifier[annotations] ( identifier[obj] : identifier[BioCCollection] keyword[or] identifier[BioCDocument] keyword[or] identifier[BioCPassage] keyword[or] identifier[BioCSentence] ,
identifier[docid] : identifier[str] = keyword[None] , identifier[level] : identifier[int] = identifier[PASSAGE] )-... | def annotations(obj: BioCCollection or BioCDocument or BioCPassage or BioCSentence, docid: str=None, level: int=PASSAGE) -> Generator[BioCAnnotation, None, None]:
"""
Get all annotations in document id.
Args:
obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence
docid: document id... |
def loop():
"""Function that gets called again as soon as it finishes (forever)."""
print("Straight")
board.digital_write(L_CTRL_1, 1)
board.digital_write(L_CTRL_2, 0)
board.analog_write(PWM_L, 245)
board.digital_write(R_CTRL_1, 1)
board.digital_write(R_CTRL_2, 0)
board.analog_write(PWM_... | def function[loop, parameter[]]:
constant[Function that gets called again as soon as it finishes (forever).]
call[name[print], parameter[constant[Straight]]]
call[name[board].digital_write, parameter[name[L_CTRL_1], constant[1]]]
call[name[board].digital_write, parameter[name[L_CTRL_2], ... | keyword[def] identifier[loop] ():
literal[string]
identifier[print] ( literal[string] )
identifier[board] . identifier[digital_write] ( identifier[L_CTRL_1] , literal[int] )
identifier[board] . identifier[digital_write] ( identifier[L_CTRL_2] , literal[int] )
identifier[board] . identifier[a... | def loop():
"""Function that gets called again as soon as it finishes (forever)."""
print('Straight')
board.digital_write(L_CTRL_1, 1)
board.digital_write(L_CTRL_2, 0)
board.analog_write(PWM_L, 245)
board.digital_write(R_CTRL_1, 1)
board.digital_write(R_CTRL_2, 0)
board.analog_write(PWM_... |
def batch_entrez(list_of_terms, db="nuccore", retmax=1, rettype="fasta",
batchsize=1, email=myEmail):
"""
Retrieve multiple rather than a single record
"""
for term in list_of_terms:
logging.debug("Search term %s" % term)
success = False
ids = None
if n... | def function[batch_entrez, parameter[list_of_terms, db, retmax, rettype, batchsize, email]]:
constant[
Retrieve multiple rather than a single record
]
for taget[name[term]] in starred[name[list_of_terms]] begin[:]
call[name[logging].debug, parameter[binary_operation[constant[Sear... | keyword[def] identifier[batch_entrez] ( identifier[list_of_terms] , identifier[db] = literal[string] , identifier[retmax] = literal[int] , identifier[rettype] = literal[string] ,
identifier[batchsize] = literal[int] , identifier[email] = identifier[myEmail] ):
literal[string]
keyword[for] identifier[ter... | def batch_entrez(list_of_terms, db='nuccore', retmax=1, rettype='fasta', batchsize=1, email=myEmail):
"""
Retrieve multiple rather than a single record
"""
for term in list_of_terms:
logging.debug('Search term %s' % term)
success = False
ids = None
if not term:
... |
def delete_os_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Deletes the Openstack In network and update the DB. """
ret = True
tenant_name = fw_dict.get('tenant_name')
try:
ret = self._delete_os_nwk(tenant_id, tenant_name, "in",
... | def function[delete_os_in_nwk, parameter[self, tenant_id, fw_dict, is_fw_virt]]:
constant[Deletes the Openstack In network and update the DB. ]
variable[ret] assign[=] constant[True]
variable[tenant_name] assign[=] call[name[fw_dict].get, parameter[constant[tenant_name]]]
<ast.Try object at ... | keyword[def] identifier[delete_os_in_nwk] ( identifier[self] , identifier[tenant_id] , identifier[fw_dict] , identifier[is_fw_virt] = keyword[False] ):
literal[string]
identifier[ret] = keyword[True]
identifier[tenant_name] = identifier[fw_dict] . identifier[get] ( literal[string] )
... | def delete_os_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Deletes the Openstack In network and update the DB. """
ret = True
tenant_name = fw_dict.get('tenant_name')
try:
ret = self._delete_os_nwk(tenant_id, tenant_name, 'in', is_fw_virt=is_fw_virt) # depends on [control=['try'], dat... |
def n_bifurcation_points(neurites, neurite_type=NeuriteType.all):
'''number of bifurcation points in a collection of neurites'''
return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point) | def function[n_bifurcation_points, parameter[neurites, neurite_type]]:
constant[number of bifurcation points in a collection of neurites]
return[call[name[n_sections], parameter[name[neurites]]]] | keyword[def] identifier[n_bifurcation_points] ( identifier[neurites] , identifier[neurite_type] = identifier[NeuriteType] . identifier[all] ):
literal[string]
keyword[return] identifier[n_sections] ( identifier[neurites] , identifier[neurite_type] = identifier[neurite_type] , identifier[iterator_type] = i... | def n_bifurcation_points(neurites, neurite_type=NeuriteType.all):
"""number of bifurcation points in a collection of neurites"""
return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ibifurcation_point) |
def load_config(cls):
""" Load global and local configuration files and update if needed."""
config_file = os.path.expanduser(cls.home_config)
global_conf = cls.load(config_file, 'global')
cls.load(cls.local_config, 'local')
# update global configuration if needed
cls.upd... | def function[load_config, parameter[cls]]:
constant[ Load global and local configuration files and update if needed.]
variable[config_file] assign[=] call[name[os].path.expanduser, parameter[name[cls].home_config]]
variable[global_conf] assign[=] call[name[cls].load, parameter[name[config_file],... | keyword[def] identifier[load_config] ( identifier[cls] ):
literal[string]
identifier[config_file] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[cls] . identifier[home_config] )
identifier[global_conf] = identifier[cls] . identifier[load] ( identifier[config_file... | def load_config(cls):
""" Load global and local configuration files and update if needed."""
config_file = os.path.expanduser(cls.home_config)
global_conf = cls.load(config_file, 'global')
cls.load(cls.local_config, 'local')
# update global configuration if needed
cls.update_config(config_file, ... |
def load_pert(self):
"""
Load perturbation files to ``self.callpert``
Returns
-------
None
"""
system = self.system
if system.files.pert:
try:
sys.path.append(system.files.path)
module = importlib.import_module... | def function[load_pert, parameter[self]]:
constant[
Load perturbation files to ``self.callpert``
Returns
-------
None
]
variable[system] assign[=] name[self].system
if name[system].files.pert begin[:]
<ast.Try object at 0x7da1b23467a0> | keyword[def] identifier[load_pert] ( identifier[self] ):
literal[string]
identifier[system] = identifier[self] . identifier[system]
keyword[if] identifier[system] . identifier[files] . identifier[pert] :
keyword[try] :
identifier[sys] . identifier[path] . i... | def load_pert(self):
"""
Load perturbation files to ``self.callpert``
Returns
-------
None
"""
system = self.system
if system.files.pert:
try:
sys.path.append(system.files.path)
module = importlib.import_module(system.files.pert[:-3])
... |
def _get_bin_dir(self):
"""
Normaly we have a ...env/bin/ dir.
But under Windows we have ...env/Scripts/
But not PyPy2 under Windows, see:
https://bitbucket.org/pypy/pypy/issues/2125/tcl-doesnt-work-inside-a-virtualenv-on#comment-21247266
So just try to test via os.path.... | def function[_get_bin_dir, parameter[self]]:
constant[
Normaly we have a ...env/bin/ dir.
But under Windows we have ...env/Scripts/
But not PyPy2 under Windows, see:
https://bitbucket.org/pypy/pypy/issues/2125/tcl-doesnt-work-inside-a-virtualenv-on#comment-21247266
So ju... | keyword[def] identifier[_get_bin_dir] ( identifier[self] ):
literal[string]
keyword[for] identifier[subdir] keyword[in] ( literal[string] , literal[string] ):
identifier[bin_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[abs_home_dir] , id... | def _get_bin_dir(self):
"""
Normaly we have a ...env/bin/ dir.
But under Windows we have ...env/Scripts/
But not PyPy2 under Windows, see:
https://bitbucket.org/pypy/pypy/issues/2125/tcl-doesnt-work-inside-a-virtualenv-on#comment-21247266
So just try to test via os.path.isdi... |
def _tracing_information():
"""Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
"""
# We'll collate trace information if the B3 headers have been collected:
values = b3.values()
if values[b3.b3... | def function[_tracing_information, parameter[]]:
constant[Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
]
variable[values] assign[=] call[name[b3].values, parameter[]]
if call[name[va... | keyword[def] identifier[_tracing_information] ():
literal[string]
identifier[values] = identifier[b3] . identifier[values] ()
keyword[if] identifier[values] [ identifier[b3] . identifier[b3_trace_id] ]:
keyword[return] [
identifier[current_app] . identifier[nam... | def _tracing_information():
"""Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
"""
# We'll collate trace information if the B3 headers have been collected:
values = b3.values()
if values[b3.b3_... |
def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
"""
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with... | def function[extend_embedder_vocab, parameter[self, embedding_sources_mapping]]:
constant[
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with ori... | keyword[def] identifier[extend_embedder_vocab] ( identifier[self] , identifier[embedding_sources_mapping] : identifier[Dict] [ identifier[str] , identifier[str] ]= keyword[None] )-> keyword[None] :
literal[string]
identifier[embedding_sources_mapping] = identifier[embedding_source... | def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str]=None) -> None:
"""
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with origi... |
def prepare_spec(spec, data=None):
"""Prepare a Vega-Lite spec for sending to the frontend.
This allows data to be passed in either as part of the spec
or separately. If separately, the data is assumed to be a
pandas DataFrame or object that can be converted to to a DataFrame.
Note that if data is... | def function[prepare_spec, parameter[spec, data]]:
constant[Prepare a Vega-Lite spec for sending to the frontend.
This allows data to be passed in either as part of the spec
or separately. If separately, the data is assumed to be a
pandas DataFrame or object that can be converted to to a DataFrame.... | keyword[def] identifier[prepare_spec] ( identifier[spec] , identifier[data] = keyword[None] ):
literal[string]
keyword[import] identifier[pandas] keyword[as] identifier[pd]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[pd] . identifier[DataFrame] ):
identi... | def prepare_spec(spec, data=None):
"""Prepare a Vega-Lite spec for sending to the frontend.
This allows data to be passed in either as part of the spec
or separately. If separately, the data is assumed to be a
pandas DataFrame or object that can be converted to to a DataFrame.
Note that if data is... |
def _traverse_nodes(self):
""" Debugging function (exposes cython nodes as dummy nodes) """
node = self.root
stack = []
while stack or node is not None:
if node is not None:
stack.append(node)
node = node.left
else:
... | def function[_traverse_nodes, parameter[self]]:
constant[ Debugging function (exposes cython nodes as dummy nodes) ]
variable[node] assign[=] name[self].root
variable[stack] assign[=] list[[]]
while <ast.BoolOp object at 0x7da1b24ea1d0> begin[:]
if compare[name[node] is_n... | keyword[def] identifier[_traverse_nodes] ( identifier[self] ):
literal[string]
identifier[node] = identifier[self] . identifier[root]
identifier[stack] =[]
keyword[while] identifier[stack] keyword[or] identifier[node] keyword[is] keyword[not] keyword[None] :
ke... | def _traverse_nodes(self):
""" Debugging function (exposes cython nodes as dummy nodes) """
node = self.root
stack = []
while stack or node is not None:
if node is not None:
stack.append(node)
node = node.left # depends on [control=['if'], data=['node']]
else:
... |
def save(self, file_path):
"""
Write database to a file. If a file with the specified name exists it's backed up
:param file_path: file path
"""
if os.path.isfile(file_path):
with open(self.get_backup_file_name(file_path), 'w') as d:
with open(file_pat... | def function[save, parameter[self, file_path]]:
constant[
Write database to a file. If a file with the specified name exists it's backed up
:param file_path: file path
]
if call[name[os].path.isfile, parameter[name[file_path]]] begin[:]
with call[name[open], param... | keyword[def] identifier[save] ( identifier[self] , identifier[file_path] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[file_path] ):
keyword[with] identifier[open] ( identifier[self] . identifier[get_backup_file_name] ( identifier[... | def save(self, file_path):
"""
Write database to a file. If a file with the specified name exists it's backed up
:param file_path: file path
"""
if os.path.isfile(file_path):
with open(self.get_backup_file_name(file_path), 'w') as d:
with open(file_path, 'r') as o:
... |
def utime(self, path, times=None, ns=None,
dir_fd=None, follow_symlinks=None):
"""Change the access and modified times of a file.
Args:
path: (str) Path to the file.
times: 2-tuple of int or float numbers, of the form (atime, mtime)
which is used to... | def function[utime, parameter[self, path, times, ns, dir_fd, follow_symlinks]]:
constant[Change the access and modified times of a file.
Args:
path: (str) Path to the file.
times: 2-tuple of int or float numbers, of the form (atime, mtime)
which is used to set th... | keyword[def] identifier[utime] ( identifier[self] , identifier[path] , identifier[times] = keyword[None] , identifier[ns] = keyword[None] ,
identifier[dir_fd] = keyword[None] , identifier[follow_symlinks] = keyword[None] ):
literal[string]
keyword[if] identifier[follow_symlinks] keyword[is] key... | def utime(self, path, times=None, ns=None, dir_fd=None, follow_symlinks=None):
"""Change the access and modified times of a file.
Args:
path: (str) Path to the file.
times: 2-tuple of int or float numbers, of the form (atime, mtime)
which is used to set the access an... |
def process_large_file(self, local_file, parent):
"""
Upload a single file using multiple processes to upload multiple chunks at the same time.
Updates local_file with it's remote_id when done.
:param local_file: LocalFile: file we are uploading
:param parent: LocalFolder/LocalPr... | def function[process_large_file, parameter[self, local_file, parent]]:
constant[
Upload a single file using multiple processes to upload multiple chunks at the same time.
Updates local_file with it's remote_id when done.
:param local_file: LocalFile: file we are uploading
:param ... | keyword[def] identifier[process_large_file] ( identifier[self] , identifier[local_file] , identifier[parent] ):
literal[string]
identifier[file_content_sender] = identifier[FileUploader] ( identifier[self] . identifier[settings] . identifier[config] , identifier[self] . identifier[settings] . ident... | def process_large_file(self, local_file, parent):
"""
Upload a single file using multiple processes to upload multiple chunks at the same time.
Updates local_file with it's remote_id when done.
:param local_file: LocalFile: file we are uploading
:param parent: LocalFolder/LocalProjec... |
def capacity_salgado_2008(sl, fd, h_l=0, h_b=0, vertical_load=1, verbose=0, **kwargs):
"""
calculates the capacity according to
THe Engineering of Foundations textbook by Salgado
ISBN: 0072500581
:param sl: Soil object
:param fd: Foundation object
:param h_l: Horizontal load parallel to ... | def function[capacity_salgado_2008, parameter[sl, fd, h_l, h_b, vertical_load, verbose]]:
constant[
calculates the capacity according to
THe Engineering of Foundations textbook by Salgado
ISBN: 0072500581
:param sl: Soil object
:param fd: Foundation object
:param h_l: Horizontal load... | keyword[def] identifier[capacity_salgado_2008] ( identifier[sl] , identifier[fd] , identifier[h_l] = literal[int] , identifier[h_b] = literal[int] , identifier[vertical_load] = literal[int] , identifier[verbose] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] i... | def capacity_salgado_2008(sl, fd, h_l=0, h_b=0, vertical_load=1, verbose=0, **kwargs):
"""
calculates the capacity according to
THe Engineering of Foundations textbook by Salgado
ISBN: 0072500581
:param sl: Soil object
:param fd: Foundation object
:param h_l: Horizontal load parallel to ... |
def to_nullable_boolean(value):
"""
Converts value into boolean or returns None when conversion is not possible.
:param value: the value to convert.
:return: boolean value or None when convertion is not supported.
"""
# Shortcuts
if value == None:
re... | def function[to_nullable_boolean, parameter[value]]:
constant[
Converts value into boolean or returns None when conversion is not possible.
:param value: the value to convert.
:return: boolean value or None when convertion is not supported.
]
if compare[name[value] equa... | keyword[def] identifier[to_nullable_boolean] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] == keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[type] ( identifier[value] )== identifier[type] ( keyword[True] ):
... | def to_nullable_boolean(value):
"""
Converts value into boolean or returns None when conversion is not possible.
:param value: the value to convert.
:return: boolean value or None when convertion is not supported.
"""
# Shortcuts
if value == None:
return None # dep... |
def get_objects_with_object(self, obj_type, *child_types):
"""
:param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types.
"""
return [o for o in self.get_objects_by_ty... | def function[get_objects_with_object, parameter[self, obj_type]]:
constant[
:param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types.
]
return[<ast.ListComp object at 0x7d... | keyword[def] identifier[get_objects_with_object] ( identifier[self] , identifier[obj_type] ,* identifier[child_types] ):
literal[string]
keyword[return] [ identifier[o] keyword[for] identifier[o] keyword[in] identifier[self] . identifier[get_objects_by_type] ( identifier[obj_type] ) keyword[if... | def get_objects_with_object(self, obj_type, *child_types):
"""
:param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types.
"""
return [o for o in self.get_objects_by_type(obj_ty... |
def get_midnight():
"""Return last midnight in localtime as datetime.
@return: Midnight datetime
"""
limit = now()
if settings.USE_TZ:
limit = localtime(limit)
return limit.replace(hour=0, minute=0, second=0, microsecond=0) | def function[get_midnight, parameter[]]:
constant[Return last midnight in localtime as datetime.
@return: Midnight datetime
]
variable[limit] assign[=] call[name[now], parameter[]]
if name[settings].USE_TZ begin[:]
variable[limit] assign[=] call[name[localtime], paramete... | keyword[def] identifier[get_midnight] ():
literal[string]
identifier[limit] = identifier[now] ()
keyword[if] identifier[settings] . identifier[USE_TZ] :
identifier[limit] = identifier[localtime] ( identifier[limit] )
keyword[return] identifier[limit] . identifier[replace] ( identifier[... | def get_midnight():
"""Return last midnight in localtime as datetime.
@return: Midnight datetime
"""
limit = now()
if settings.USE_TZ:
limit = localtime(limit) # depends on [control=['if'], data=[]]
return limit.replace(hour=0, minute=0, second=0, microsecond=0) |
def find_range_in_section_list(start, end, section_list):
"""Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is... | def function[find_range_in_section_list, parameter[start, end, section_list]]:
constant[Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For exam... | keyword[def] identifier[find_range_in_section_list] ( identifier[start] , identifier[end] , identifier[section_list] ):
literal[string]
identifier[ind] = identifier[find_range_ix_in_section_list] ( identifier[start] , identifier[end] , identifier[section_list] )
keyword[return] identifier[section_lis... | def find_range_in_section_list(start, end, section_list):
"""Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is... |
def _is_dirty(dir_path):
"""Check whether a git repository has uncommitted changes."""
try:
subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path)
return False
except subprocess.CalledProcessError:
return True | def function[_is_dirty, parameter[dir_path]]:
constant[Check whether a git repository has uncommitted changes.]
<ast.Try object at 0x7da1b1f72470> | keyword[def] identifier[_is_dirty] ( identifier[dir_path] ):
literal[string]
keyword[try] :
identifier[subprocess] . identifier[check_call] ([ literal[string] , literal[string] , literal[string] ], identifier[cwd] = identifier[dir_path] )
keyword[return] keyword[False]
keyword[exce... | def _is_dirty(dir_path):
"""Check whether a git repository has uncommitted changes."""
try:
subprocess.check_call(['git', 'diff', '--quiet'], cwd=dir_path)
return False # depends on [control=['try'], data=[]]
except subprocess.CalledProcessError:
return True # depends on [control=[... |
def create_floatingip(self, context, floatingip):
"""Create floating IP.
:param context: Neutron request context
:param floatingip: data for the floating IP being created
:returns: A floating IP object on success
As the l3 router plugin asynchronously creates floating IPs
... | def function[create_floatingip, parameter[self, context, floatingip]]:
constant[Create floating IP.
:param context: Neutron request context
:param floatingip: data for the floating IP being created
:returns: A floating IP object on success
As the l3 router plugin asynchronously... | keyword[def] identifier[create_floatingip] ( identifier[self] , identifier[context] , identifier[floatingip] ):
literal[string]
keyword[return] identifier[super] ( identifier[CiscoRouterPlugin] , identifier[self] ). identifier[create_floatingip] (
identifier[context] , identifier[floating... | def create_floatingip(self, context, floatingip):
"""Create floating IP.
:param context: Neutron request context
:param floatingip: data for the floating IP being created
:returns: A floating IP object on success
As the l3 router plugin asynchronously creates floating IPs
l... |
def _choose_scheme(self):
"""Choose color scheme"""
if self.style_cols[self.color] in ('string', 'boolean', ):
self.scheme = antique(10)
elif self.style_cols[self.color] in ('number', ):
self.scheme = mint(5)
elif self.style_cols[self.color] in ('date', 'geometry'... | def function[_choose_scheme, parameter[self]]:
constant[Choose color scheme]
if compare[call[name[self].style_cols][name[self].color] in tuple[[<ast.Constant object at 0x7da20c990f70>, <ast.Constant object at 0x7da20c993850>]]] begin[:]
name[self].scheme assign[=] call[name[antique], par... | keyword[def] identifier[_choose_scheme] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[style_cols] [ identifier[self] . identifier[color] ] keyword[in] ( literal[string] , literal[string] ,):
identifier[self] . identifier[scheme] = identifier[antique] ... | def _choose_scheme(self):
"""Choose color scheme"""
if self.style_cols[self.color] in ('string', 'boolean'):
self.scheme = antique(10) # depends on [control=['if'], data=[]]
elif self.style_cols[self.color] in ('number',):
self.scheme = mint(5) # depends on [control=['if'], data=[]]
el... |
def publish(self):
'''
Immediately shares a single pending update and recalculates times for
updates remaining in the queue.
'''
url = PATHS['PUBLISH'] % self.id
return self.api.post(url=url) | def function[publish, parameter[self]]:
constant[
Immediately shares a single pending update and recalculates times for
updates remaining in the queue.
]
variable[url] assign[=] binary_operation[call[name[PATHS]][constant[PUBLISH]] <ast.Mod object at 0x7da2590d6920> name[self].id]
re... | keyword[def] identifier[publish] ( identifier[self] ):
literal[string]
identifier[url] = identifier[PATHS] [ literal[string] ]% identifier[self] . identifier[id]
keyword[return] identifier[self] . identifier[api] . identifier[post] ( identifier[url] = identifier[url] ) | def publish(self):
"""
Immediately shares a single pending update and recalculates times for
updates remaining in the queue.
"""
url = PATHS['PUBLISH'] % self.id
return self.api.post(url=url) |
def wait(self, build_id, states):
"""
:param build_id: wait for build to finish
:return:
"""
logger.info("watching build '%s'", build_id)
for changetype, obj in self.watch_resource("builds", build_id):
try:
obj_name = obj["metadata"]["name"]
... | def function[wait, parameter[self, build_id, states]]:
constant[
:param build_id: wait for build to finish
:return:
]
call[name[logger].info, parameter[constant[watching build '%s'], name[build_id]]]
for taget[tuple[[<ast.Name object at 0x7da1b0e0f310>, <ast.Name object ... | keyword[def] identifier[wait] ( identifier[self] , identifier[build_id] , identifier[states] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[build_id] )
keyword[for] identifier[changetype] , identifier[obj] keyword[in] identifier[self] . identifie... | def wait(self, build_id, states):
"""
:param build_id: wait for build to finish
:return:
"""
logger.info("watching build '%s'", build_id)
for (changetype, obj) in self.watch_resource('builds', build_id):
try:
obj_name = obj['metadata']['name'] # depends on [cont... |
def json_to_entity(tc_data, value_fields, resource_type, resource_type_parent):
"""Convert ThreatConnect JSON response to a TCEntityArray.
.. Attention:: This method is subject to frequent changes.
Args:
tc_data (dictionary): Array of data returned from TC API call.
val... | def function[json_to_entity, parameter[tc_data, value_fields, resource_type, resource_type_parent]]:
constant[Convert ThreatConnect JSON response to a TCEntityArray.
.. Attention:: This method is subject to frequent changes.
Args:
tc_data (dictionary): Array of data returned from T... | keyword[def] identifier[json_to_entity] ( identifier[tc_data] , identifier[value_fields] , identifier[resource_type] , identifier[resource_type_parent] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[tc_data] , identifier[list] ):
identifier[tc_data] =... | def json_to_entity(tc_data, value_fields, resource_type, resource_type_parent):
"""Convert ThreatConnect JSON response to a TCEntityArray.
.. Attention:: This method is subject to frequent changes.
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_f... |
def get_enterprise_customer_for_running_pipeline(request, pipeline): # pylint: disable=invalid-name
"""
Get the EnterpriseCustomer associated with a running pipeline.
"""
sso_provider_id = request.GET.get('tpa_hint')
if pipeline:
sso_provider_id = Registry.get_from_pipeline(pipeline).provid... | def function[get_enterprise_customer_for_running_pipeline, parameter[request, pipeline]]:
constant[
Get the EnterpriseCustomer associated with a running pipeline.
]
variable[sso_provider_id] assign[=] call[name[request].GET.get, parameter[constant[tpa_hint]]]
if name[pipeline] begin[:]
... | keyword[def] identifier[get_enterprise_customer_for_running_pipeline] ( identifier[request] , identifier[pipeline] ):
literal[string]
identifier[sso_provider_id] = identifier[request] . identifier[GET] . identifier[get] ( literal[string] )
keyword[if] identifier[pipeline] :
identifier[sso_pr... | def get_enterprise_customer_for_running_pipeline(request, pipeline): # pylint: disable=invalid-name
'\n Get the EnterpriseCustomer associated with a running pipeline.\n '
sso_provider_id = request.GET.get('tpa_hint')
if pipeline:
sso_provider_id = Registry.get_from_pipeline(pipeline).provider... |
def generate_error_json_response(error_dict, error_response_context=None):
"""
Intends to build an error json response. If the error_response_context is
None, then we generate this response using data tables format
:param error_dict: str/dict: contains the error message(s)
:param error_response_con... | def function[generate_error_json_response, parameter[error_dict, error_response_context]]:
constant[
Intends to build an error json response. If the error_response_context is
None, then we generate this response using data tables format
:param error_dict: str/dict: contains the error message(s)
... | keyword[def] identifier[generate_error_json_response] ( identifier[error_dict] , identifier[error_response_context] = keyword[None] ):
literal[string]
identifier[response] = identifier[error_dict]
keyword[if] identifier[isinstance] ( identifier[error_dict] , identifier[str] ):
identifier[re... | def generate_error_json_response(error_dict, error_response_context=None):
"""
Intends to build an error json response. If the error_response_context is
None, then we generate this response using data tables format
:param error_dict: str/dict: contains the error message(s)
:param error_response_con... |
def checkerboard_matrix_filtering(similarity_matrix, kernel_width, kernel_type="default", thresh=0.25):
"""
Moving the checkerboard matrix over the main diagonal of the similarity matrix one sample at a time.
:param kernel_type:
:param thresh:
:param similarity_matrix:
:param kernel_width: the... | def function[checkerboard_matrix_filtering, parameter[similarity_matrix, kernel_width, kernel_type, thresh]]:
constant[
Moving the checkerboard matrix over the main diagonal of the similarity matrix one sample at a time.
:param kernel_type:
:param thresh:
:param similarity_matrix:
:param ke... | keyword[def] identifier[checkerboard_matrix_filtering] ( identifier[similarity_matrix] , identifier[kernel_width] , identifier[kernel_type] = literal[string] , identifier[thresh] = literal[int] ):
literal[string]
identifier[checkerboard_matrix] = identifier[get_checkerboard_matrix] ( identifier[kernel_wi... | def checkerboard_matrix_filtering(similarity_matrix, kernel_width, kernel_type='default', thresh=0.25):
"""
Moving the checkerboard matrix over the main diagonal of the similarity matrix one sample at a time.
:param kernel_type:
:param thresh:
:param similarity_matrix:
:param kernel_width: the ... |
def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
pote... | def function[_evaluate, parameter[self, R, z, phi, t]]:
constant[
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
... | keyword[def] identifier[_evaluate] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[isNonAxi] keyword[and] identifier[phi] keyword[is] keyword[None] :
... | def _evaluate(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
po... |
def secure(pdf, user_pw, owner_pw, restrict_permission=True, pdftk=get_pdftk_path(), output=None):
"""
Encrypt a PDF file and restrict permissions to print only.
Utilizes pdftk command line tool.
:param pdf: Path to PDF file
:param user_pw: Password to open and view
:param owner_pw: Password t... | def function[secure, parameter[pdf, user_pw, owner_pw, restrict_permission, pdftk, output]]:
constant[
Encrypt a PDF file and restrict permissions to print only.
Utilizes pdftk command line tool.
:param pdf: Path to PDF file
:param user_pw: Password to open and view
:param owner_pw: Passwo... | keyword[def] identifier[secure] ( identifier[pdf] , identifier[user_pw] , identifier[owner_pw] , identifier[restrict_permission] = keyword[True] , identifier[pdftk] = identifier[get_pdftk_path] (), identifier[output] = keyword[None] ):
literal[string]
keyword[if] identifier[pdftk] :
keyword[... | def secure(pdf, user_pw, owner_pw, restrict_permission=True, pdftk=get_pdftk_path(), output=None):
"""
Encrypt a PDF file and restrict permissions to print only.
Utilizes pdftk command line tool.
:param pdf: Path to PDF file
:param user_pw: Password to open and view
:param owner_pw: Password t... |
def get_zt(self, output='eigs', doping_levels=True, relaxation_time=1e-14,
kl=1.0):
"""
Gives the ZT coefficient (S^2*cond*T/thermal cond) in either a full
3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are... | def function[get_zt, parameter[self, output, doping_levels, relaxation_time, kl]]:
constant[
Gives the ZT coefficient (S^2*cond*T/thermal cond) in either a full
3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
... | keyword[def] identifier[get_zt] ( identifier[self] , identifier[output] = literal[string] , identifier[doping_levels] = keyword[True] , identifier[relaxation_time] = literal[int] ,
identifier[kl] = literal[int] ):
literal[string]
identifier[result] = keyword[None]
identifier[result_dopin... | def get_zt(self, output='eigs', doping_levels=True, relaxation_time=1e-14, kl=1.0):
"""
Gives the ZT coefficient (S^2*cond*T/thermal cond) in either a full
3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
d... |
def _find_export(self, func):
# type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]
"""
Look for an export using the given lookup method
The lookup method must accept a single parameter, which is a tuple
containing a service ins... | def function[_find_export, parameter[self, func]]:
constant[
Look for an export using the given lookup method
The lookup method must accept a single parameter, which is a tuple
containing a service instance and endpoint description.
:param func: A function to look for the excep... | keyword[def] identifier[_find_export] ( identifier[self] , identifier[func] ):
literal[string]
keyword[with] identifier[self] . identifier[_exported_instances_lock] :
keyword[for] identifier[val] keyword[in] identifier[self] . identifier[_exported_services] . identifier[values] ()... | def _find_export(self, func):
# type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]
'\n Look for an export using the given lookup method\n\n The lookup method must accept a single parameter, which is a tuple\n containing a service instance ... |
def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT
"""
Parses all siblings of the provided table first and bundles them into
an AoT.
"""
payload = [first]
self._aot_stack.append(name_first)
while not self.end():
is_aot_next, name_nex... | def function[_parse_aot, parameter[self, first, name_first]]:
constant[
Parses all siblings of the provided table first and bundles them into
an AoT.
]
variable[payload] assign[=] list[[<ast.Name object at 0x7da1b207fe20>]]
call[name[self]._aot_stack.append, parameter[nam... | keyword[def] identifier[_parse_aot] ( identifier[self] , identifier[first] , identifier[name_first] ):
literal[string]
identifier[payload] =[ identifier[first] ]
identifier[self] . identifier[_aot_stack] . identifier[append] ( identifier[name_first] )
keyword[while] keyword[not] ... | def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT
'\n Parses all siblings of the provided table first and bundles them into\n an AoT.\n '
payload = [first]
self._aot_stack.append(name_first)
while not self.end():
(is_aot_next, name_next) = self._peek_tabl... |
def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
"""Creates a generator to perform one or more SNMP GETBULK queries.
On each iteration, new SNMP GETBULK request is send
(:RFC:`1905#section-4.2.3`). The iterator blocks waiting for respon... | def function[bulkCmd, parameter[snmpDispatcher, authData, transportTarget, nonRepeaters, maxRepetitions]]:
constant[Creates a generator to perform one or more SNMP GETBULK queries.
On each iteration, new SNMP GETBULK request is send
(:RFC:`1905#section-4.2.3`). The iterator blocks waiting for response
... | keyword[def] identifier[bulkCmd] ( identifier[snmpDispatcher] , identifier[authData] , identifier[transportTarget] ,
identifier[nonRepeaters] , identifier[maxRepetitions] ,* identifier[varBinds] ,** identifier[options] ):
literal[string]
keyword[def] identifier[cbFun] (* identifier[args] ,** identifier[... | def bulkCmd(snmpDispatcher, authData, transportTarget, nonRepeaters, maxRepetitions, *varBinds, **options):
"""Creates a generator to perform one or more SNMP GETBULK queries.
On each iteration, new SNMP GETBULK request is send
(:RFC:`1905#section-4.2.3`). The iterator blocks waiting for response
to ar... |
def write_temp_file(self, content, filename=None, mode='w'):
"""Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the... | def function[write_temp_file, parameter[self, content, filename, mode]]:
constant[Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to us... | keyword[def] identifier[write_temp_file] ( identifier[self] , identifier[content] , identifier[filename] = keyword[None] , identifier[mode] = literal[string] ):
literal[string]
keyword[if] identifier[filename] keyword[is] keyword[None] :
identifier[filename] = identifier[str] ( iden... | def write_temp_file(self, content, filename=None, mode='w'):
"""Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the fil... |
def escape_velocity(M,R):
"""
escape velocity.
Parameters
----------
M : float
Mass in solar masses.
R : float
Radius in solar radiu.
Returns
-------
v_escape
in km/s.
"""
ve = np.sqrt(2.*grav_const*M*msun_g/(R*rsun_cm))
ve = ve*1.... | def function[escape_velocity, parameter[M, R]]:
constant[
escape velocity.
Parameters
----------
M : float
Mass in solar masses.
R : float
Radius in solar radiu.
Returns
-------
v_escape
in km/s.
]
variable[ve] assign[=] call[na... | keyword[def] identifier[escape_velocity] ( identifier[M] , identifier[R] ):
literal[string]
identifier[ve] = identifier[np] . identifier[sqrt] ( literal[int] * identifier[grav_const] * identifier[M] * identifier[msun_g] /( identifier[R] * identifier[rsun_cm] ))
identifier[ve] = identifier[ve] * liter... | def escape_velocity(M, R):
"""
escape velocity.
Parameters
----------
M : float
Mass in solar masses.
R : float
Radius in solar radiu.
Returns
-------
v_escape
in km/s.
"""
ve = np.sqrt(2.0 * grav_const * M * msun_g / (R * rsun_cm))
... |
def to_unicode_string(string):
"""
Return a Unicode string out of the given string.
On Python 2, it calls ``unicode`` with ``utf-8`` encoding.
On Python 3, it just returns the given string.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to convert to Unicode
... | def function[to_unicode_string, parameter[string]]:
constant[
Return a Unicode string out of the given string.
On Python 2, it calls ``unicode`` with ``utf-8`` encoding.
On Python 3, it just returns the given string.
Return ``None`` if ``string`` is ``None``.
:param str string: the st... | keyword[def] identifier[to_unicode_string] ( identifier[string] ):
literal[string]
keyword[if] identifier[string] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[is_unicode_string] ( identifier[string] ):
keyword[return] identifier[string]
... | def to_unicode_string(string):
"""
Return a Unicode string out of the given string.
On Python 2, it calls ``unicode`` with ``utf-8`` encoding.
On Python 3, it just returns the given string.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to convert to Unicode
... |
def get_dataset(ds,dataDir,removecompressed=1):
"""
A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset.
PARAMETERS
:ds: dataset number of the openfMRI.org dataset (integer) without zero padding. I.e. can just be 212 (doesn't need to be 000212).
:da... | def function[get_dataset, parameter[ds, dataDir, removecompressed]]:
constant[
A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset.
PARAMETERS
:ds: dataset number of the openfMRI.org dataset (integer) without zero padding. I.e. can just be 212 (doesn... | keyword[def] identifier[get_dataset] ( identifier[ds] , identifier[dataDir] , identifier[removecompressed] = literal[int] ):
literal[string]
identifier[ds] = identifier[str] ( identifier[ds] )
identifier[lettersuffix] = literal[string]
keyword[if] identifier[re] . identifier[search] ... | def get_dataset(ds, dataDir, removecompressed=1):
"""
A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset.
PARAMETERS
:ds: dataset number of the openfMRI.org dataset (integer) without zero padding. I.e. can just be 212 (doesn't need to be 000212).
:d... |
def get_element_by_id(self, ident):
"""Get a TocElement element identified by index number from the
container."""
for group in list(self.toc.keys()):
for name in list(self.toc[group].keys()):
if self.toc[group][name].ident == ident:
return self.toc... | def function[get_element_by_id, parameter[self, ident]]:
constant[Get a TocElement element identified by index number from the
container.]
for taget[name[group]] in starred[call[name[list], parameter[call[name[self].toc.keys, parameter[]]]]] begin[:]
for taget[name[name]] in star... | keyword[def] identifier[get_element_by_id] ( identifier[self] , identifier[ident] ):
literal[string]
keyword[for] identifier[group] keyword[in] identifier[list] ( identifier[self] . identifier[toc] . identifier[keys] ()):
keyword[for] identifier[name] keyword[in] identifier[list]... | def get_element_by_id(self, ident):
"""Get a TocElement element identified by index number from the
container."""
for group in list(self.toc.keys()):
for name in list(self.toc[group].keys()):
if self.toc[group][name].ident == ident:
return self.toc[group][name] # dep... |
def create_uo(self, configuration=None, tpl=None, keys=None, obj_type=None):
"""
Create a new UserObject from the given template.
:param configuration: EB configuration to use
:param tpl: CreateUserObject template, contain misc settings
:param keys: dictionary of keys, create_u... | def function[create_uo, parameter[self, configuration, tpl, keys, obj_type]]:
constant[
Create a new UserObject from the given template.
:param configuration: EB configuration to use
:param tpl: CreateUserObject template, contain misc settings
:param keys: dictionary of keys, c... | keyword[def] identifier[create_uo] ( identifier[self] , identifier[configuration] = keyword[None] , identifier[tpl] = keyword[None] , identifier[keys] = keyword[None] , identifier[obj_type] = keyword[None] ):
literal[string]
keyword[if] identifier[configuration] keyword[is] keyword[not] keyword... | def create_uo(self, configuration=None, tpl=None, keys=None, obj_type=None):
"""
Create a new UserObject from the given template.
:param configuration: EB configuration to use
:param tpl: CreateUserObject template, contain misc settings
:param keys: dictionary of keys, create_uo.Ke... |
def endpoint_name(self, endpoint_name):
"""
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: ... | def function[endpoint_name, parameter[self, endpoint_name]]:
constant[
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
... | keyword[def] identifier[endpoint_name] ( identifier[self] , identifier[endpoint_name] ):
literal[string]
keyword[if] identifier[endpoint_name] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[endpoint_name] keyw... | def endpoint_name(self, endpoint_name):
"""
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: The ... |
def _addProteinIdsToGroupMapping(self, proteinIds, groupId):
"""Add a groupId to one or multiple entries of the internal
proteinToGroupId mapping.
:param proteinIds: a proteinId or a list of proteinIds, a proteinId
must be a string.
:param groupId: str, a groupId
"""... | def function[_addProteinIdsToGroupMapping, parameter[self, proteinIds, groupId]]:
constant[Add a groupId to one or multiple entries of the internal
proteinToGroupId mapping.
:param proteinIds: a proteinId or a list of proteinIds, a proteinId
must be a string.
:param groupId:... | keyword[def] identifier[_addProteinIdsToGroupMapping] ( identifier[self] , identifier[proteinIds] , identifier[groupId] ):
literal[string]
keyword[for] identifier[proteinId] keyword[in] identifier[AUX] . identifier[toList] ( identifier[proteinIds] ):
identifier[self] . identifier[_p... | def _addProteinIdsToGroupMapping(self, proteinIds, groupId):
"""Add a groupId to one or multiple entries of the internal
proteinToGroupId mapping.
:param proteinIds: a proteinId or a list of proteinIds, a proteinId
must be a string.
:param groupId: str, a groupId
"""
... |
def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
potential... | def function[_evaluate, parameter[self, R, z, phi, t]]:
constant[
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUT... | keyword[def] identifier[_evaluate] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[_new] :
keyword[if] identifier[nu] . identifier[fabs] ( identifi... | def _evaluate(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
potenti... |
def conditional_probability_alive(self, frequency, recency, T):
"""
Conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From paper:
http://brucehardie.com/notes/009/pareto_nbd_derivations_2005-11... | def function[conditional_probability_alive, parameter[self, frequency, recency, T]]:
constant[
Conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From paper:
http://brucehardie.com/notes/009/par... | keyword[def] identifier[conditional_probability_alive] ( identifier[self] , identifier[frequency] , identifier[recency] , identifier[T] ):
literal[string]
identifier[x] , identifier[t_x] = identifier[frequency] , identifier[recency]
identifier[r] , identifier[alpha] , identifier[s] , iden... | def conditional_probability_alive(self, frequency, recency, T):
"""
Conditional probability alive.
Compute the probability that a customer with history
(frequency, recency, T) is currently alive.
From paper:
http://brucehardie.com/notes/009/pareto_nbd_derivations_2005-11-05.... |
def get_heteroatoms(self, elements=None):
"""
Identify non-H, non-C atoms in the MoleculeGraph, returning a list of
their node indices.
:param elements: List of elements to identify (if only certain
functional groups are of interest).
:return: set of ints representin... | def function[get_heteroatoms, parameter[self, elements]]:
constant[
Identify non-H, non-C atoms in the MoleculeGraph, returning a list of
their node indices.
:param elements: List of elements to identify (if only certain
functional groups are of interest).
:return: s... | keyword[def] identifier[get_heteroatoms] ( identifier[self] , identifier[elements] = keyword[None] ):
literal[string]
identifier[heteroatoms] = identifier[set] ()
keyword[for] identifier[node] keyword[in] identifier[self] . identifier[molgraph] . identifier[graph] . identifier[nodes] ... | def get_heteroatoms(self, elements=None):
"""
Identify non-H, non-C atoms in the MoleculeGraph, returning a list of
their node indices.
:param elements: List of elements to identify (if only certain
functional groups are of interest).
:return: set of ints representing no... |
def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
if self._isN... | def function[setInstrumentParameters, parameter[self, instrpars]]:
constant[ This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
]
variable[pri_header] assign[=] call[name[self]._image][constant[0]].header
... | keyword[def] identifier[setInstrumentParameters] ( identifier[self] , identifier[instrpars] ):
literal[string]
identifier[pri_header] = identifier[self] . identifier[_image] [ literal[int] ]. identifier[header]
identifier[self] . identifier[proc_unit] = identifier[instrpars] [ literal[str... | def setInstrumentParameters(self, instrpars):
""" This method overrides the superclass to set default values into
the parameter dictionary, in case empty entries are provided.
"""
pri_header = self._image[0].header
self.proc_unit = instrpars['proc_unit']
if self._isNotValid(instrpars... |
def composition(mol):
"""Molecular composition in dict format
(ex. Glucose {'C': 6, 'H': 12, 'O': 6}).
"""
mol.require("Valence")
c = Counter()
for _, a in mol.atoms_iter():
c += a.composition()
return c | def function[composition, parameter[mol]]:
constant[Molecular composition in dict format
(ex. Glucose {'C': 6, 'H': 12, 'O': 6}).
]
call[name[mol].require, parameter[constant[Valence]]]
variable[c] assign[=] call[name[Counter], parameter[]]
for taget[tuple[[<ast.Name object at 0x... | keyword[def] identifier[composition] ( identifier[mol] ):
literal[string]
identifier[mol] . identifier[require] ( literal[string] )
identifier[c] = identifier[Counter] ()
keyword[for] identifier[_] , identifier[a] keyword[in] identifier[mol] . identifier[atoms_iter] ():
identifier[c] ... | def composition(mol):
"""Molecular composition in dict format
(ex. Glucose {'C': 6, 'H': 12, 'O': 6}).
"""
mol.require('Valence')
c = Counter()
for (_, a) in mol.atoms_iter():
c += a.composition() # depends on [control=['for'], data=[]]
return c |
def plot4(self, num):
"""
Plots the abundances of H-1, He-4, C-12 and O-16.
"""
self.plot_prof_1(num,'H-1',0.,5.,-5,0.)
self.plot_prof_1(num,'He-4',0.,5.,-5,0.)
self.plot_prof_1(num,'C-12',0.,5.,-5,0.)
self.plot_prof_1(num,'O-16',0.,5.,-5,0.)
pyl.legend... | def function[plot4, parameter[self, num]]:
constant[
Plots the abundances of H-1, He-4, C-12 and O-16.
]
call[name[self].plot_prof_1, parameter[name[num], constant[H-1], constant[0.0], constant[5.0], <ast.UnaryOp object at 0x7da20c6aa800>, constant[0.0]]]
call[name[self].plot_... | keyword[def] identifier[plot4] ( identifier[self] , identifier[num] ):
literal[string]
identifier[self] . identifier[plot_prof_1] ( identifier[num] , literal[string] , literal[int] , literal[int] ,- literal[int] , literal[int] )
identifier[self] . identifier[plot_prof_1] ( identifier[num] ... | def plot4(self, num):
"""
Plots the abundances of H-1, He-4, C-12 and O-16.
"""
self.plot_prof_1(num, 'H-1', 0.0, 5.0, -5, 0.0)
self.plot_prof_1(num, 'He-4', 0.0, 5.0, -5, 0.0)
self.plot_prof_1(num, 'C-12', 0.0, 5.0, -5, 0.0)
self.plot_prof_1(num, 'O-16', 0.0, 5.0, -5, 0.0)
py... |
def define_sub_network_cycle_constraints( subnetwork, snapshots, passive_branch_p, attribute):
""" Constructs cycle_constraints for a particular subnetwork
"""
sub_network_cycle_constraints = {}
sub_network_cycle_index = []
matrix = subnetwork.C.tocsc()
branches = subnetwork.branches()
fo... | def function[define_sub_network_cycle_constraints, parameter[subnetwork, snapshots, passive_branch_p, attribute]]:
constant[ Constructs cycle_constraints for a particular subnetwork
]
variable[sub_network_cycle_constraints] assign[=] dictionary[[], []]
variable[sub_network_cycle_index] assig... | keyword[def] identifier[define_sub_network_cycle_constraints] ( identifier[subnetwork] , identifier[snapshots] , identifier[passive_branch_p] , identifier[attribute] ):
literal[string]
identifier[sub_network_cycle_constraints] ={}
identifier[sub_network_cycle_index] =[]
identifier[matrix] = ide... | def define_sub_network_cycle_constraints(subnetwork, snapshots, passive_branch_p, attribute):
""" Constructs cycle_constraints for a particular subnetwork
"""
sub_network_cycle_constraints = {}
sub_network_cycle_index = []
matrix = subnetwork.C.tocsc()
branches = subnetwork.branches()
for co... |
def clear_vdp_vsi(self, port_uuid):
"""Stores the vNIC specific info for VDP Refresh.
:param uuid: vNIC UUID
"""
try:
LOG.debug("Clearing VDP VSI MAC %(mac)s UUID %(uuid)s",
{'mac': self.vdp_vif_map[port_uuid].get('mac'),
'uuid': ... | def function[clear_vdp_vsi, parameter[self, port_uuid]]:
constant[Stores the vNIC specific info for VDP Refresh.
:param uuid: vNIC UUID
]
<ast.Try object at 0x7da2041dbeb0>
call[name[self].clear_oui, parameter[name[port_uuid]]] | keyword[def] identifier[clear_vdp_vsi] ( identifier[self] , identifier[port_uuid] ):
literal[string]
keyword[try] :
identifier[LOG] . identifier[debug] ( literal[string] ,
{ literal[string] : identifier[self] . identifier[vdp_vif_map] [ identifier[port_uuid] ]. identifier[g... | def clear_vdp_vsi(self, port_uuid):
"""Stores the vNIC specific info for VDP Refresh.
:param uuid: vNIC UUID
"""
try:
LOG.debug('Clearing VDP VSI MAC %(mac)s UUID %(uuid)s', {'mac': self.vdp_vif_map[port_uuid].get('mac'), 'uuid': self.vdp_vif_map[port_uuid].get('vsiid')})
del se... |
def _validate_type_scalar(self, value):
""" Is not a list or a dict """
if isinstance(
value, _int_types + (_str_type, float, date, datetime, bool)
):
return True | def function[_validate_type_scalar, parameter[self, value]]:
constant[ Is not a list or a dict ]
if call[name[isinstance], parameter[name[value], binary_operation[name[_int_types] + tuple[[<ast.Name object at 0x7da1b1712260>, <ast.Name object at 0x7da1b17128f0>, <ast.Name object at 0x7da1b1712200>, <ast... | keyword[def] identifier[_validate_type_scalar] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] (
identifier[value] , identifier[_int_types] +( identifier[_str_type] , identifier[float] , identifier[date] , identifier[datetime] , identifier[bool... | def _validate_type_scalar(self, value):
""" Is not a list or a dict """
if isinstance(value, _int_types + (_str_type, float, date, datetime, bool)):
return True # depends on [control=['if'], data=[]] |
def save_model(self, net):
"""Save the model.
This function saves some or all of the following:
- model parameters;
- optimizer state;
- training history;
- entire model object.
"""
if self.f_params is not None:
f = self._format_targe... | def function[save_model, parameter[self, net]]:
constant[Save the model.
This function saves some or all of the following:
- model parameters;
- optimizer state;
- training history;
- entire model object.
]
if compare[name[self].f_params is_not c... | keyword[def] identifier[save_model] ( identifier[self] , identifier[net] ):
literal[string]
keyword[if] identifier[self] . identifier[f_params] keyword[is] keyword[not] keyword[None] :
identifier[f] = identifier[self] . identifier[_format_target] ( identifier[net] , identifier[self... | def save_model(self, net):
"""Save the model.
This function saves some or all of the following:
- model parameters;
- optimizer state;
- training history;
- entire model object.
"""
if self.f_params is not None:
f = self._format_target(net, self.... |
def prepare(self, variables):
"""Initialize all steps in this recipe using their parameters.
Args:
variables (dict): A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each step.
Returns:
... | def function[prepare, parameter[self, variables]]:
constant[Initialize all steps in this recipe using their parameters.
Args:
variables (dict): A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each ste... | keyword[def] identifier[prepare] ( identifier[self] , identifier[variables] ):
literal[string]
identifier[initializedsteps] =[]
keyword[if] identifier[variables] keyword[is] keyword[None] :
identifier[variables] = identifier[dict] ()
keyword[for] identifier[step] ... | def prepare(self, variables):
"""Initialize all steps in this recipe using their parameters.
Args:
variables (dict): A dictionary of global variable definitions
that may be used to replace or augment the parameters given
to each step.
Returns:
... |
def get_mnist(sc, data_type="train", location="/tmp/mnist"):
"""
Get mnist dataset and parallelize into RDDs.
Data would be downloaded automatically if it doesn't present at the specific location.
:param sc: SparkContext.
:param data_type: "train" for training data and "test" for testing data.
... | def function[get_mnist, parameter[sc, data_type, location]]:
constant[
Get mnist dataset and parallelize into RDDs.
Data would be downloaded automatically if it doesn't present at the specific location.
:param sc: SparkContext.
:param data_type: "train" for training data and "test" for testing ... | keyword[def] identifier[get_mnist] ( identifier[sc] , identifier[data_type] = literal[string] , identifier[location] = literal[string] ):
literal[string]
( identifier[images] , identifier[labels] )= identifier[mnist] . identifier[read_data_sets] ( identifier[location] , identifier[data_type] )
identifi... | def get_mnist(sc, data_type='train', location='/tmp/mnist'):
"""
Get mnist dataset and parallelize into RDDs.
Data would be downloaded automatically if it doesn't present at the specific location.
:param sc: SparkContext.
:param data_type: "train" for training data and "test" for testing data.
... |
def hacking_python3x_except_compatible(logical_line, noqa):
r"""Check for except statements to be Python 3.x compatible
As of Python 3.x, the construct 'except x,y:' has been removed.
Use 'except x as y:' instead.
Okay: try:\n pass\nexcept Exception:\n pass
Okay: try:\n pass\nexcept (Exc... | def function[hacking_python3x_except_compatible, parameter[logical_line, noqa]]:
constant[Check for except statements to be Python 3.x compatible
As of Python 3.x, the construct 'except x,y:' has been removed.
Use 'except x as y:' instead.
Okay: try:\n pass\nexcept Exception:\n pass
Oka... | keyword[def] identifier[hacking_python3x_except_compatible] ( identifier[logical_line] , identifier[noqa] ):
literal[string]
keyword[if] identifier[noqa] :
keyword[return]
keyword[def] identifier[is_old_style_except] ( identifier[logical_line] ):
keyword[return] ( literal[string]... | def hacking_python3x_except_compatible(logical_line, noqa):
"""Check for except statements to be Python 3.x compatible
As of Python 3.x, the construct 'except x,y:' has been removed.
Use 'except x as y:' instead.
Okay: try:\\n pass\\nexcept Exception:\\n pass
Okay: try:\\n pass\\nexcept ... |
def community_topic_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/topics#create-topic"
api_path = "/api/v2/community/topics.json"
return self.call(api_path, method="POST", data=data, **kwargs) | def function[community_topic_create, parameter[self, data]]:
constant[https://developer.zendesk.com/rest_api/docs/help_center/topics#create-topic]
variable[api_path] assign[=] constant[/api/v2/community/topics.json]
return[call[name[self].call, parameter[name[api_path]]]] | keyword[def] identifier[community_topic_create] ( identifier[self] , identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
keyword[return] identifier[self] . identifier[call] ( identifier[api_path] , identifier[method] = literal[string] , ident... | def community_topic_create(self, data, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/help_center/topics#create-topic"""
api_path = '/api/v2/community/topics.json'
return self.call(api_path, method='POST', data=data, **kwargs) |
def get_path(self, prefix=None, filename=None):
"""Compose data location path."""
prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR']
path = os.path.join(prefix, self.subpath)
if filename:
path = os.path.join(path, filename)
return path | def function[get_path, parameter[self, prefix, filename]]:
constant[Compose data location path.]
variable[prefix] assign[=] <ast.BoolOp object at 0x7da18c4cdf30>
variable[path] assign[=] call[name[os].path.join, parameter[name[prefix], name[self].subpath]]
if name[filename] begin[:]
... | keyword[def] identifier[get_path] ( identifier[self] , identifier[prefix] = keyword[None] , identifier[filename] = keyword[None] ):
literal[string]
identifier[prefix] = identifier[prefix] keyword[or] identifier[settings] . identifier[FLOW_EXECUTOR] [ literal[string] ]
identifier[path] =... | def get_path(self, prefix=None, filename=None):
"""Compose data location path."""
prefix = prefix or settings.FLOW_EXECUTOR['DATA_DIR']
path = os.path.join(prefix, self.subpath)
if filename:
path = os.path.join(path, filename) # depends on [control=['if'], data=[]]
return path |
def pickFilepath( self ):
"""
Prompts the user to select a filepath from the system based on the \
current filepath mode.
"""
mode = self.filepathMode()
filepath = ''
filepaths = []
curr_dir = nativestring(self._filepathEdit.text())
if (... | def function[pickFilepath, parameter[self]]:
constant[
Prompts the user to select a filepath from the system based on the current filepath mode.
]
variable[mode] assign[=] call[name[self].filepathMode, parameter[]]
variable[filepath] assign[=] constant[]
variable[... | keyword[def] identifier[pickFilepath] ( identifier[self] ):
literal[string]
identifier[mode] = identifier[self] . identifier[filepathMode] ()
identifier[filepath] = literal[string]
identifier[filepaths] =[]
identifier[curr_dir] = identifier[nativestring] ( identifier[... | def pickFilepath(self):
"""
Prompts the user to select a filepath from the system based on the current filepath mode.
"""
mode = self.filepathMode()
filepath = ''
filepaths = []
curr_dir = nativestring(self._filepathEdit.text())
if not curr_dir:
curr_dir = QDir.cu... |
def exact_cftime_datetime_difference(a, b):
"""Exact computation of b - a
Assumes:
a = a_0 + a_m
b = b_0 + b_m
Here a_0, and b_0 represent the input dates rounded
down to the nearest second, and a_m, and b_m represent
the remaining microseconds associated with date a and
date ... | def function[exact_cftime_datetime_difference, parameter[a, b]]:
constant[Exact computation of b - a
Assumes:
a = a_0 + a_m
b = b_0 + b_m
Here a_0, and b_0 represent the input dates rounded
down to the nearest second, and a_m, and b_m represent
the remaining microseconds assoc... | keyword[def] identifier[exact_cftime_datetime_difference] ( identifier[a] , identifier[b] ):
literal[string]
identifier[seconds] = identifier[b] . identifier[replace] ( identifier[microsecond] = literal[int] )- identifier[a] . identifier[replace] ( identifier[microsecond] = literal[int] )
identifier[s... | def exact_cftime_datetime_difference(a, b):
"""Exact computation of b - a
Assumes:
a = a_0 + a_m
b = b_0 + b_m
Here a_0, and b_0 represent the input dates rounded
down to the nearest second, and a_m, and b_m represent
the remaining microseconds associated with date a and
date ... |
def set_primary_keys_auto(self, tables=None):
"""
Create primary keys for every table in the connected database.
Checks that each table has a primary key. If a table does not have a key
then each column is analyzed to determine if it contains only unique values.
If no columns e... | def function[set_primary_keys_auto, parameter[self, tables]]:
constant[
Create primary keys for every table in the connected database.
Checks that each table has a primary key. If a table does not have a key
then each column is analyzed to determine if it contains only unique values.
... | keyword[def] identifier[set_primary_keys_auto] ( identifier[self] , identifier[tables] = keyword[None] ):
literal[string]
identifier[tables] = identifier[tables] keyword[if] identifier[tables] keyword[else] identifier[self] . identifier[tables]
keyword[return] [( id... | def set_primary_keys_auto(self, tables=None):
"""
Create primary keys for every table in the connected database.
Checks that each table has a primary key. If a table does not have a key
then each column is analyzed to determine if it contains only unique values.
If no columns exist... |
def row_dict(self, row):
"""returns dictionary version of row using keys from self.field_map"""
d = {}
for field_name,index in self.field_map.items():
d[field_name] = self.field_value(row, field_name)
return d | def function[row_dict, parameter[self, row]]:
constant[returns dictionary version of row using keys from self.field_map]
variable[d] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b0fc71f0>, <ast.Name object at 0x7da1b0fc5210>]]] in starred[call[name[self].field_map.item... | keyword[def] identifier[row_dict] ( identifier[self] , identifier[row] ):
literal[string]
identifier[d] ={}
keyword[for] identifier[field_name] , identifier[index] keyword[in] identifier[self] . identifier[field_map] . identifier[items] ():
identifier[d] [ identifier[field_... | def row_dict(self, row):
"""returns dictionary version of row using keys from self.field_map"""
d = {}
for (field_name, index) in self.field_map.items():
d[field_name] = self.field_value(row, field_name) # depends on [control=['for'], data=[]]
return d |
def _write(self, session, openFile, replaceParamFile=None):
"""
ProjectFileEvent Write to File Method
"""
openFile.write(
text(
yaml.dump([evt.as_yml() for evt in
self.events.order_by(ProjectFileEvent.name,
... | def function[_write, parameter[self, session, openFile, replaceParamFile]]:
constant[
ProjectFileEvent Write to File Method
]
call[name[openFile].write, parameter[call[name[text], parameter[call[name[yaml].dump, parameter[<ast.ListComp object at 0x7da18f09d4b0>]]]]]] | keyword[def] identifier[_write] ( identifier[self] , identifier[session] , identifier[openFile] , identifier[replaceParamFile] = keyword[None] ):
literal[string]
identifier[openFile] . identifier[write] (
identifier[text] (
identifier[yaml] . identifier[dump] ([ identifier[evt] . ... | def _write(self, session, openFile, replaceParamFile=None):
"""
ProjectFileEvent Write to File Method
"""
openFile.write(text(yaml.dump([evt.as_yml() for evt in self.events.order_by(ProjectFileEvent.name, ProjectFileEvent.subfolder)]))) |
def find_expectations(self,
expectation_type=None,
column=None,
expectation_kwargs=None,
discard_result_format_kwargs=True,
discard_include_configs_kwargs=True,
dis... | def function[find_expectations, parameter[self, expectation_type, column, expectation_kwargs, discard_result_format_kwargs, discard_include_configs_kwargs, discard_catch_exceptions_kwargs]]:
constant[Find matching expectations within _expectation_config.
Args:
expectation_type=None ... | keyword[def] identifier[find_expectations] ( identifier[self] ,
identifier[expectation_type] = keyword[None] ,
identifier[column] = keyword[None] ,
identifier[expectation_kwargs] = keyword[None] ,
identifier[discard_result_format_kwargs] = keyword[True] ,
identifier[discard_include_configs_kwargs] = keyword[True... | def find_expectations(self, expectation_type=None, column=None, expectation_kwargs=None, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True):
"""Find matching expectations within _expectation_config.
Args:
expectation_type=None ... |
def convert_date(value, parameter):
'''
Converts to datetime.date:
'', '-', None convert to parameter default
The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
'''
value = _check_default(value, parameter, ( '', '-', None ))
if value is None or isinstance(v... | def function[convert_date, parameter[value, parameter]]:
constant[
Converts to datetime.date:
'', '-', None convert to parameter default
The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
]
variable[value] assign[=] call[name[_check_default], parameter[... | keyword[def] identifier[convert_date] ( identifier[value] , identifier[parameter] ):
literal[string]
identifier[value] = identifier[_check_default] ( identifier[value] , identifier[parameter] ,( literal[string] , literal[string] , keyword[None] ))
keyword[if] identifier[value] keyword[is] keyword[N... | def convert_date(value, parameter):
"""
Converts to datetime.date:
'', '-', None convert to parameter default
The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
"""
value = _check_default(value, parameter, ('', '-', None))
if value is None or isinstance(val... |
def json(self):
"""Custom JSON encoder"""
attributes = {
'type': self.type,
'filename': self.filename,
'line_number': self.lineno,
'hashed_secret': self.secret_hash,
}
if self.is_secret is not None:
attributes['is_secret'] = se... | def function[json, parameter[self]]:
constant[Custom JSON encoder]
variable[attributes] assign[=] dictionary[[<ast.Constant object at 0x7da20c6e7ca0>, <ast.Constant object at 0x7da20c6e7130>, <ast.Constant object at 0x7da20c6e66b0>, <ast.Constant object at 0x7da20c6e5ea0>], [<ast.Attribute object at 0x7... | keyword[def] identifier[json] ( identifier[self] ):
literal[string]
identifier[attributes] ={
literal[string] : identifier[self] . identifier[type] ,
literal[string] : identifier[self] . identifier[filename] ,
literal[string] : identifier[self] . identifier[lineno] ,
... | def json(self):
"""Custom JSON encoder"""
attributes = {'type': self.type, 'filename': self.filename, 'line_number': self.lineno, 'hashed_secret': self.secret_hash}
if self.is_secret is not None:
attributes['is_secret'] = self.is_secret # depends on [control=['if'], data=[]]
return attributes |
def read_oplog_progress(self):
"""Reads oplog progress from file provided by user.
This method is only called once before any threads are spanwed.
"""
if self.oplog_checkpoint is None:
return None
# Check for empty file
try:
if os.stat(self.oplog... | def function[read_oplog_progress, parameter[self]]:
constant[Reads oplog progress from file provided by user.
This method is only called once before any threads are spanwed.
]
if compare[name[self].oplog_checkpoint is constant[None]] begin[:]
return[constant[None]]
<ast.Try o... | keyword[def] identifier[read_oplog_progress] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[oplog_checkpoint] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[try] :
keyword[if] identifier[os] ... | def read_oplog_progress(self):
"""Reads oplog progress from file provided by user.
This method is only called once before any threads are spanwed.
"""
if self.oplog_checkpoint is None:
return None # depends on [control=['if'], data=[]]
# Check for empty file
try:
if os.s... |
def postProcess(self, images_data, new_format, new_size):
""" Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data. """
if len(images_data) == 1:
in_bytes = io.BytesIO(images_data[0])
img = PIL.Image.open(in_bytes)
if img.mode !... | def function[postProcess, parameter[self, images_data, new_format, new_size]]:
constant[ Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data. ]
if compare[call[name[len], parameter[name[images_data]]] equal[==] constant[1]] begin[:]
... | keyword[def] identifier[postProcess] ( identifier[self] , identifier[images_data] , identifier[new_format] , identifier[new_size] ):
literal[string]
keyword[if] identifier[len] ( identifier[images_data] )== literal[int] :
identifier[in_bytes] = identifier[io] . identifier[BytesIO] ( identifier[imag... | def postProcess(self, images_data, new_format, new_size):
""" Convert image binary data to a target format and/or size (None if no conversion needed), and return the processed data. """
if len(images_data) == 1:
in_bytes = io.BytesIO(images_data[0])
img = PIL.Image.open(in_bytes)
if img.... |
def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
re... | def function[on_result, parameter[self, task, result]]:
constant[Called every result]
if <ast.UnaryOp object at 0x7da1b1f61690> begin[:]
return[None]
if <ast.BoolOp object at 0x7da1b1f62e60> begin[:]
call[name[logger].info, parameter[binary_operation[constant[result %s:%s... | keyword[def] identifier[on_result] ( identifier[self] , identifier[task] , identifier[result] ):
literal[string]
keyword[if] keyword[not] identifier[result] :
keyword[return]
keyword[if] literal[string] keyword[in] identifier[task] keyword[and] literal[string] keyword... | def on_result(self, task, result):
"""Called every result"""
if not result:
return # depends on [control=['if'], data=[]]
if 'taskid' in task and 'project' in task and ('url' in task):
logger.info('result %s:%s %s -> %.30r' % (task['project'], task['taskid'], task['url'], result))
r... |
def dual(ABF):
"""Plot two channels of current sweep (top/bottom)."""
new(ABF)
pylab.subplot(211)
pylab.title("Input A (channel 0)")
ABF.channel=0
sweep(ABF)
pylab.subplot(212)
pylab.title("Input B (channel 1)")
ABF.channel=1
sweep(ABF) | def function[dual, parameter[ABF]]:
constant[Plot two channels of current sweep (top/bottom).]
call[name[new], parameter[name[ABF]]]
call[name[pylab].subplot, parameter[constant[211]]]
call[name[pylab].title, parameter[constant[Input A (channel 0)]]]
name[ABF].channel assign[=] c... | keyword[def] identifier[dual] ( identifier[ABF] ):
literal[string]
identifier[new] ( identifier[ABF] )
identifier[pylab] . identifier[subplot] ( literal[int] )
identifier[pylab] . identifier[title] ( literal[string] )
identifier[ABF] . identifier[channel] = literal[int]
identifier[swee... | def dual(ABF):
"""Plot two channels of current sweep (top/bottom)."""
new(ABF)
pylab.subplot(211)
pylab.title('Input A (channel 0)')
ABF.channel = 0
sweep(ABF)
pylab.subplot(212)
pylab.title('Input B (channel 1)')
ABF.channel = 1
sweep(ABF) |
def first_return():
"""Generate a random walk and return its length upto the moment
that the walker first returns to the origin.
It is mathematically provable that the walker will eventually return,
meaning that the function call will halt, although it may take
a *very* long time and your computer may run out of ... | def function[first_return, parameter[]]:
constant[Generate a random walk and return its length upto the moment
that the walker first returns to the origin.
It is mathematically provable that the walker will eventually return,
meaning that the function call will halt, although it may take
a *very* long time... | keyword[def] identifier[first_return] ():
literal[string]
identifier[walk] = identifier[randwalk] ()>> identifier[drop] ( literal[int] )>> identifier[takewhile] ( keyword[lambda] identifier[v] : identifier[v] != identifier[Origin] )>> identifier[list]
keyword[return] identifier[len] ( identifier[walk] ) | def first_return():
"""Generate a random walk and return its length upto the moment
that the walker first returns to the origin.
It is mathematically provable that the walker will eventually return,
meaning that the function call will halt, although it may take
a *very* long time and your computer may run out ... |
def supervisor_events(stdin, stdout):
"""
An event stream from Supervisor.
"""
while True:
stdout.write('READY\n')
stdout.flush()
line = stdin.readline()
headers = get_headers(line)
payload = stdin.read(int(headers['len']))
event_headers, event_data = e... | def function[supervisor_events, parameter[stdin, stdout]]:
constant[
An event stream from Supervisor.
]
while constant[True] begin[:]
call[name[stdout].write, parameter[constant[READY
]]]
call[name[stdout].flush, parameter[]]
variable[line] assign[... | keyword[def] identifier[supervisor_events] ( identifier[stdin] , identifier[stdout] ):
literal[string]
keyword[while] keyword[True] :
identifier[stdout] . identifier[write] ( literal[string] )
identifier[stdout] . identifier[flush] ()
identifier[line] = identifier[stdin] . ide... | def supervisor_events(stdin, stdout):
"""
An event stream from Supervisor.
"""
while True:
stdout.write('READY\n')
stdout.flush()
line = stdin.readline()
headers = get_headers(line)
payload = stdin.read(int(headers['len']))
(event_headers, event_data) = ev... |
def get_assessment_offered_lookup_session(self):
"""Gets the ``OsidSession`` associated with the assessment offered lookup service.
return: (osid.assessment.AssessmentOfferedLookupSession) - an
``AssessmentOfferedLookupSession``
raise: OperationFailed - unable to complete reque... | def function[get_assessment_offered_lookup_session, parameter[self]]:
constant[Gets the ``OsidSession`` associated with the assessment offered lookup service.
return: (osid.assessment.AssessmentOfferedLookupSession) - an
``AssessmentOfferedLookupSession``
raise: OperationFailed... | keyword[def] identifier[get_assessment_offered_lookup_session] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_assessment_offered_lookup] ():
keyword[raise] identifier[errors] . identifier[Unimplemented] ()
... | def get_assessment_offered_lookup_session(self):
"""Gets the ``OsidSession`` associated with the assessment offered lookup service.
return: (osid.assessment.AssessmentOfferedLookupSession) - an
``AssessmentOfferedLookupSession``
raise: OperationFailed - unable to complete request
... |
def _read_syncmap_file(self, path, extension, text=False):
""" Read labels from a SyncMap file """
syncmap = SyncMap(logger=self.logger)
syncmap.read(extension, path, parameters=None)
if text:
return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragmen... | def function[_read_syncmap_file, parameter[self, path, extension, text]]:
constant[ Read labels from a SyncMap file ]
variable[syncmap] assign[=] call[name[SyncMap], parameter[]]
call[name[syncmap].read, parameter[name[extension], name[path]]]
if name[text] begin[:]
return[<ast.L... | keyword[def] identifier[_read_syncmap_file] ( identifier[self] , identifier[path] , identifier[extension] , identifier[text] = keyword[False] ):
literal[string]
identifier[syncmap] = identifier[SyncMap] ( identifier[logger] = identifier[self] . identifier[logger] )
identifier[syncmap] . id... | def _read_syncmap_file(self, path, extension, text=False):
""" Read labels from a SyncMap file """
syncmap = SyncMap(logger=self.logger)
syncmap.read(extension, path, parameters=None)
if text:
return [(f.begin, f.end, u' '.join(f.text_fragment.lines)) for f in syncmap.fragments] # depends on [c... |
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit... | def function[_get_param_names, parameter[cls]]:
constant[Get parameter names for the estimator]
variable[init] assign[=] call[name[getattr], parameter[name[cls].__init__, constant[deprecated_original], name[cls].__init__]]
if compare[name[init] is name[object].__init__] begin[:]
return[l... | keyword[def] identifier[_get_param_names] ( identifier[cls] ):
literal[string]
identifier[init] = identifier[getattr] ( identifier[cls] . identifier[__init__] , literal[string] , identifier[cls] . identifier[__init__] )
keyword[if] identifier[init] keyword[is] identif... | def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit constructor to introspec... |
def probeLine(img, p1, p2, res=100):
"""
Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_
"""
line = vtk.vtkLineSource()
line.SetResolution(res)
line.SetPoint1(p1)
line.SetPoint2(p2)
probeFilter = v... | def function[probeLine, parameter[img, p1, p2, res]]:
constant[
Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_
]
variable[line] assign[=] call[name[vtk].vtkLineSource, parameter[]]
call[name[line]... | keyword[def] identifier[probeLine] ( identifier[img] , identifier[p1] , identifier[p2] , identifier[res] = literal[int] ):
literal[string]
identifier[line] = identifier[vtk] . identifier[vtkLineSource] ()
identifier[line] . identifier[SetResolution] ( identifier[res] )
identifier[line] . identifi... | def probeLine(img, p1, p2, res=100):
"""
Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_
"""
line = vtk.vtkLineSource()
line.SetResolution(res)
line.SetPoint1(p1)
line.SetPoint2(p2)
probeFilter = v... |
def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]:
"""
Parses an indexing expression (for a single tensor).
Checks uniqueness of names, checks usage of '...' (allowed only once)
Returns set of all used identifiers and a list of axis groups
"""
identifiers = set()
... | def function[parse_expression, parameter[expression]]:
constant[
Parses an indexing expression (for a single tensor).
Checks uniqueness of names, checks usage of '...' (allowed only once)
Returns set of all used identifiers and a list of axis groups
]
variable[identifiers] assign[=] call... | keyword[def] identifier[parse_expression] ( identifier[expression] : identifier[str] )-> identifier[Tuple] [ identifier[Set] [ identifier[str] ], identifier[List] [ identifier[CompositeAxis] ]]:
literal[string]
identifier[identifiers] = identifier[set] ()
identifier[composite_axes] =[]
keyword[if... | def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]:
"""
Parses an indexing expression (for a single tensor).
Checks uniqueness of names, checks usage of '...' (allowed only once)
Returns set of all used identifiers and a list of axis groups
"""
identifiers = set()
... |
def householder(self):
"""Return Matrices u,b,v with self = ubv and b is in bidiagonal form
The algorithm uses householder transformations.
:return tuple (u,b,v): A tuple with the Matrix u, b and v.
and self = ubv (except some rounding errors)
u is a unitary mat... | def function[householder, parameter[self]]:
constant[Return Matrices u,b,v with self = ubv and b is in bidiagonal form
The algorithm uses householder transformations.
:return tuple (u,b,v): A tuple with the Matrix u, b and v.
and self = ubv (except some rounding errors)
... | keyword[def] identifier[householder] ( identifier[self] ):
literal[string]
identifier[bidiagMatrix] = identifier[Matrix] . identifier[from_two_dim_array] ( identifier[self] . identifier[get_width] (), identifier[self] . identifier[get_height] (), identifier[self] . identifier[matrix] )
... | def householder(self):
"""Return Matrices u,b,v with self = ubv and b is in bidiagonal form
The algorithm uses householder transformations.
:return tuple (u,b,v): A tuple with the Matrix u, b and v.
and self = ubv (except some rounding errors)
u is a unitary matrix
... |
def install(pkg=None,
pkgs=None,
user=None,
install_global=False,
env=None):
'''
Install a cabal package.
pkg
A package name in format accepted by cabal-install. See:
https://wiki.haskell.org/Cabal-Install
pkgs
A list of packages ... | def function[install, parameter[pkg, pkgs, user, install_global, env]]:
constant[
Install a cabal package.
pkg
A package name in format accepted by cabal-install. See:
https://wiki.haskell.org/Cabal-Install
pkgs
A list of packages names in same format as ``pkg``
user
... | keyword[def] identifier[install] ( identifier[pkg] = keyword[None] ,
identifier[pkgs] = keyword[None] ,
identifier[user] = keyword[None] ,
identifier[install_global] = keyword[False] ,
identifier[env] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] ]
keyword[if] identifier... | def install(pkg=None, pkgs=None, user=None, install_global=False, env=None):
"""
Install a cabal package.
pkg
A package name in format accepted by cabal-install. See:
https://wiki.haskell.org/Cabal-Install
pkgs
A list of packages names in same format as ``pkg``
user
... |
def requiredUnlessTable(col_name, arg, dm, df, con=None):
"""
Col_name must be present in df unless
arg (table_name) is present in contribution
"""
table_name = arg
if col_name in df.columns:
return None
elif not con:
return None
elif table_name in con.tables:
ret... | def function[requiredUnlessTable, parameter[col_name, arg, dm, df, con]]:
constant[
Col_name must be present in df unless
arg (table_name) is present in contribution
]
variable[table_name] assign[=] name[arg]
if compare[name[col_name] in name[df].columns] begin[:]
return[cons... | keyword[def] identifier[requiredUnlessTable] ( identifier[col_name] , identifier[arg] , identifier[dm] , identifier[df] , identifier[con] = keyword[None] ):
literal[string]
identifier[table_name] = identifier[arg]
keyword[if] identifier[col_name] keyword[in] identifier[df] . identifier[columns] :
... | def requiredUnlessTable(col_name, arg, dm, df, con=None):
"""
Col_name must be present in df unless
arg (table_name) is present in contribution
"""
table_name = arg
if col_name in df.columns:
return None # depends on [control=['if'], data=[]]
elif not con:
return None # dep... |
def showDraw(self, fignum=1):
""" show the element drawing
:param fignum: define figure number to show element drawing
"""
if self._patches == []:
print("Please setDraw() before showDraw(), then try again.")
return
else:
fig = plt.figure(fignu... | def function[showDraw, parameter[self, fignum]]:
constant[ show the element drawing
:param fignum: define figure number to show element drawing
]
if compare[name[self]._patches equal[==] list[[]]] begin[:]
call[name[print], parameter[constant[Please setDraw() before show... | keyword[def] identifier[showDraw] ( identifier[self] , identifier[fignum] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[_patches] ==[]:
identifier[print] ( literal[string] )
keyword[return]
keyword[else] :
identifier[fi... | def showDraw(self, fignum=1):
""" show the element drawing
:param fignum: define figure number to show element drawing
"""
if self._patches == []:
print('Please setDraw() before showDraw(), then try again.')
return # depends on [control=['if'], data=[]]
else:
fig = ... |
def _generate_regex(self, line):
'''
Generates a regular expression from the magic bytes of a signature.
The regex is used by Magic._analyze.
@line - The first SignatureLine object of the signature.
Returns a compile regular expression.
'''
restr = ""
#... | def function[_generate_regex, parameter[self, line]]:
constant[
Generates a regular expression from the magic bytes of a signature.
The regex is used by Magic._analyze.
@line - The first SignatureLine object of the signature.
Returns a compile regular expression.
]
... | keyword[def] identifier[_generate_regex] ( identifier[self] , identifier[line] ):
literal[string]
identifier[restr] = literal[string]
keyword[if] identifier[line] . identifier[type] == literal[string] :
keyword[return] ... | def _generate_regex(self, line):
"""
Generates a regular expression from the magic bytes of a signature.
The regex is used by Magic._analyze.
@line - The first SignatureLine object of the signature.
Returns a compile regular expression.
"""
restr = ''
# Strings and ... |
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with t... | def function[layers, parameter[self]]:
constant[Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are i... | keyword[def] identifier[layers] ( identifier[self] ):
literal[string]
identifier[graph_layers] = identifier[self] . identifier[multigraph_layers] ()
keyword[try] :
identifier[next] ( identifier[graph_layers] )
keyword[except] identifier[StopIteration] :
... | def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
... |
def create_context(self, message_queue, task_id):
"""
Create values to be used by create_small_file function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly
"""
... | def function[create_context, parameter[self, message_queue, task_id]]:
constant[
Create values to be used by create_small_file function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be rout... | keyword[def] identifier[create_context] ( identifier[self] , identifier[message_queue] , identifier[task_id] ):
literal[string]
identifier[parent_data] = identifier[ParentData] ( identifier[self] . identifier[parent] . identifier[kind] , identifier[self] . identifier[parent] . identifier[remote_id]... | def create_context(self, message_queue, task_id):
"""
Create values to be used by create_small_file function.
:param message_queue: Queue: queue background process can send messages to us on
:param task_id: int: id of this command's task so message will be routed correctly
"""
par... |
def _read_iso_abund_marco(self, mass_range, cycle):
"""
plot the abundance of all the chemical species
Parameters
----------
mass_range : list
A 1x2 array containing the lower and upper mass range. If
None, it will plot over the entire range.
cyc... | def function[_read_iso_abund_marco, parameter[self, mass_range, cycle]]:
constant[
plot the abundance of all the chemical species
Parameters
----------
mass_range : list
A 1x2 array containing the lower and upper mass range. If
None, it will plot over th... | keyword[def] identifier[_read_iso_abund_marco] ( identifier[self] , identifier[mass_range] , identifier[cycle] ):
literal[string]
keyword[import] identifier[nuutils] keyword[as] identifier[u]
identifier[masses] =[]
... | def _read_iso_abund_marco(self, mass_range, cycle):
"""
plot the abundance of all the chemical species
Parameters
----------
mass_range : list
A 1x2 array containing the lower and upper mass range. If
None, it will plot over the entire range.
cycle :... |
def _addItemMultiPart(self,
itemParameters,
filePath):
"""
The secret sauce behind the addByPart workflow
Inputs:
itemParatmers - ItemParamter class
filePath - full disk path location.
Output:
UserItem c... | def function[_addItemMultiPart, parameter[self, itemParameters, filePath]]:
constant[
The secret sauce behind the addByPart workflow
Inputs:
itemParatmers - ItemParamter class
filePath - full disk path location.
Output:
UserItem class
]
va... | keyword[def] identifier[_addItemMultiPart] ( identifier[self] ,
identifier[itemParameters] ,
identifier[filePath] ):
literal[string]
identifier[url] = identifier[self] . identifier[_location] + literal[string]
identifier[params] ={
literal[string] : literal[string] ,
l... | def _addItemMultiPart(self, itemParameters, filePath):
"""
The secret sauce behind the addByPart workflow
Inputs:
itemParatmers - ItemParamter class
filePath - full disk path location.
Output:
UserItem class
"""
url = self._location + '/addItem'
... |
def forward_backward_pd(x, f, g, L, h, tau, sigma, niter,
callback=None, **kwargs):
r"""The forward-backward primal-dual splitting algorithm.
The algorithm minimizes the sum of several convex functionals composed with
linear operators::
min_x f(x) + sum_i g_i(L_i x) + h(x)
... | def function[forward_backward_pd, parameter[x, f, g, L, h, tau, sigma, niter, callback]]:
constant[The forward-backward primal-dual splitting algorithm.
The algorithm minimizes the sum of several convex functionals composed with
linear operators::
min_x f(x) + sum_i g_i(L_i x) + h(x)
wher... | keyword[def] identifier[forward_backward_pd] ( identifier[x] , identifier[f] , identifier[g] , identifier[L] , identifier[h] , identifier[tau] , identifier[sigma] , identifier[niter] ,
identifier[callback] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[m] = identifier[len] ( id... | def forward_backward_pd(x, f, g, L, h, tau, sigma, niter, callback=None, **kwargs):
"""The forward-backward primal-dual splitting algorithm.
The algorithm minimizes the sum of several convex functionals composed with
linear operators::
min_x f(x) + sum_i g_i(L_i x) + h(x)
where ``f``, ``g_i``... |
def local_port_range(self):
"""Tuple of (low_port, high_port) reflecting the local port range
assigned to outbound connections. We use this as part of a heuristic
to determine whether a connection is inbound or outbound.
"""
if self._local_port_range is None:
with ope... | def function[local_port_range, parameter[self]]:
constant[Tuple of (low_port, high_port) reflecting the local port range
assigned to outbound connections. We use this as part of a heuristic
to determine whether a connection is inbound or outbound.
]
if compare[name[self]._local_p... | keyword[def] identifier[local_port_range] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_local_port_range] keyword[is] keyword[None] :
keyword[with] identifier[open] ( literal[string] , literal[string] ) keyword[as] identifier[f] :
... | def local_port_range(self):
"""Tuple of (low_port, high_port) reflecting the local port range
assigned to outbound connections. We use this as part of a heuristic
to determine whether a connection is inbound or outbound.
"""
if self._local_port_range is None:
with open('/proc/sys... |
def serving_input_fn(self, hparams):
"""For serving/predict, assume that only video frames are provided."""
video_input_frames = tf.placeholder(
dtype=tf.float32,
shape=[
None, hparams.video_num_input_frames, self.frame_width,
self.frame_height, self.num_channels
... | def function[serving_input_fn, parameter[self, hparams]]:
constant[For serving/predict, assume that only video frames are provided.]
variable[video_input_frames] assign[=] call[name[tf].placeholder, parameter[]]
return[call[name[tf].estimator.export.ServingInputReceiver, parameter[]]] | keyword[def] identifier[serving_input_fn] ( identifier[self] , identifier[hparams] ):
literal[string]
identifier[video_input_frames] = identifier[tf] . identifier[placeholder] (
identifier[dtype] = identifier[tf] . identifier[float32] ,
identifier[shape] =[
keyword[None] , identifier[hparams... | def serving_input_fn(self, hparams):
"""For serving/predict, assume that only video frames are provided."""
video_input_frames = tf.placeholder(dtype=tf.float32, shape=[None, hparams.video_num_input_frames, self.frame_width, self.frame_height, self.num_channels])
# TODO(michalski): add support for passing i... |
def __get_distribution_tags(self, client, arn):
"""Returns a dict containing the tags for a CloudFront distribution
Args:
client (botocore.client.CloudFront): Boto3 CloudFront client object
arn (str): ARN of the distribution to get tags for
Returns:
`dict`
... | def function[__get_distribution_tags, parameter[self, client, arn]]:
constant[Returns a dict containing the tags for a CloudFront distribution
Args:
client (botocore.client.CloudFront): Boto3 CloudFront client object
arn (str): ARN of the distribution to get tags for
Re... | keyword[def] identifier[__get_distribution_tags] ( identifier[self] , identifier[client] , identifier[arn] ):
literal[string]
keyword[return] {
identifier[t] [ literal[string] ]: identifier[t] [ literal[string] ] keyword[for] identifier[t] keyword[in] identifier[client] . identifier[lis... | def __get_distribution_tags(self, client, arn):
"""Returns a dict containing the tags for a CloudFront distribution
Args:
client (botocore.client.CloudFront): Boto3 CloudFront client object
arn (str): ARN of the distribution to get tags for
Returns:
`dict`
... |
def _Authenticate(self):
"""Save the cookie jar after authentication."""
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
self.cookie_jar.save() | def function[_Authenticate, parameter[self]]:
constant[Save the cookie jar after authentication.]
call[call[name[super], parameter[name[HttpRpcServer], name[self]]]._Authenticate, parameter[]]
if name[self].save_cookies begin[:]
call[name[StatusUpdate], parameter[binary_operation... | keyword[def] identifier[_Authenticate] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[HttpRpcServer] , identifier[self] ). identifier[_Authenticate] ()
keyword[if] identifier[self] . identifier[save_cookies] :
identifier[StatusUpdate] ( literal[string] % identifier[self] . identif... | def _Authenticate(self):
"""Save the cookie jar after authentication."""
super(HttpRpcServer, self)._Authenticate()
if self.save_cookies:
StatusUpdate('Saving authentication cookies to %s' % self.cookie_file)
self.cookie_jar.save() # depends on [control=['if'], data=[]] |
def visit_Name(self, node: ast.Name) -> Any:
"""Load the variable by looking it up in the variable look-up and in the built-ins."""
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format(
no... | def function[visit_Name, parameter[self, node]]:
constant[Load the variable by looking it up in the variable look-up and in the built-ins.]
if <ast.UnaryOp object at 0x7da1b1034100> begin[:]
<ast.Raise object at 0x7da1b1034730>
variable[result] assign[=] constant[None]
if compare... | keyword[def] identifier[visit_Name] ( identifier[self] , identifier[node] : identifier[ast] . identifier[Name] )-> identifier[Any] :
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[node] . identifier[ctx] , identifier[ast] . identifier[Load] ):
keyword[ra... | def visit_Name(self, node: ast.Name) -> Any:
"""Load the variable by looking it up in the variable look-up and in the built-ins."""
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError('Can only compute a value of Load on a name {}, but got context: {}'.format(node.id, node.ctx)) # depends ... |
def dict(self, **kwargs):
"""
Dictionary representation.
"""
return dict(
time = self.timestamp,
address = self.address,
channel = self.channel,
value = self.value,
**... | def function[dict, parameter[self]]:
constant[
Dictionary representation.
]
return[call[name[dict], parameter[]]] | keyword[def] identifier[dict] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[dict] (
identifier[time] = identifier[self] . identifier[timestamp] ,
identifier[address] = identifier[self] . identifier[address] ,
identifier[channel] ... | def dict(self, **kwargs):
"""
Dictionary representation.
"""
return dict(time=self.timestamp, address=self.address, channel=self.channel, value=self.value, **kwargs) |
def _ReadLockAndUpdateCompletedRequests(self, request_keys, response_counts,
cursor):
"""Reads, locks, and updates completed requests."""
condition_template = """
(flow_requests.client_id = %s AND
flow_requests.flow_id = %s AND
flow_requests.request... | def function[_ReadLockAndUpdateCompletedRequests, parameter[self, request_keys, response_counts, cursor]]:
constant[Reads, locks, and updates completed requests.]
variable[condition_template] assign[=] constant[
(flow_requests.client_id = %s AND
flow_requests.flow_id = %s AND
flow_re... | keyword[def] identifier[_ReadLockAndUpdateCompletedRequests] ( identifier[self] , identifier[request_keys] , identifier[response_counts] ,
identifier[cursor] ):
literal[string]
identifier[condition_template] = literal[string]
identifier[args] =[]
identifier[conditions] =[]
identifier[com... | def _ReadLockAndUpdateCompletedRequests(self, request_keys, response_counts, cursor):
"""Reads, locks, and updates completed requests."""
condition_template = '\n (flow_requests.client_id = %s AND\n flow_requests.flow_id = %s AND\n flow_requests.request_id = %s AND\n responses_expected = ... |
def future_exceptions(context, rrevent=None):
"""
Displays a list of all the future exceptions (extra info, cancellations and
postponements) for a recurring event. If the recurring event is not
specified it is assumed to be the current page.
"""
request = context['request']
if rrevent is No... | def function[future_exceptions, parameter[context, rrevent]]:
constant[
Displays a list of all the future exceptions (extra info, cancellations and
postponements) for a recurring event. If the recurring event is not
specified it is assumed to be the current page.
]
variable[request] ass... | keyword[def] identifier[future_exceptions] ( identifier[context] , identifier[rrevent] = keyword[None] ):
literal[string]
identifier[request] = identifier[context] [ literal[string] ]
keyword[if] identifier[rrevent] keyword[is] keyword[None] :
identifier[rrevent] = identifier[context] . id... | def future_exceptions(context, rrevent=None):
"""
Displays a list of all the future exceptions (extra info, cancellations and
postponements) for a recurring event. If the recurring event is not
specified it is assumed to be the current page.
"""
request = context['request']
if rrevent is No... |
def photos(self):
"""Copy photos to the destination user."""
# Reverse because pictures appear in inverse chronological order.
for photo_info in self.dest_user.profile.photo_infos:
self.dest_user.photo.delete(photo_info)
return [self.dest_user.photo.upload_and_confirm(info)
... | def function[photos, parameter[self]]:
constant[Copy photos to the destination user.]
for taget[name[photo_info]] in starred[name[self].dest_user.profile.photo_infos] begin[:]
call[name[self].dest_user.photo.delete, parameter[name[photo_info]]]
return[<ast.ListComp object at 0x7da1b2... | keyword[def] identifier[photos] ( identifier[self] ):
literal[string]
keyword[for] identifier[photo_info] keyword[in] identifier[self] . identifier[dest_user] . identifier[profile] . identifier[photo_infos] :
identifier[self] . identifier[dest_user] . identifier[photo] . id... | def photos(self):
"""Copy photos to the destination user."""
# Reverse because pictures appear in inverse chronological order.
for photo_info in self.dest_user.profile.photo_infos:
self.dest_user.photo.delete(photo_info) # depends on [control=['for'], data=['photo_info']]
return [self.dest_user... |
def const_return(func):
"""
>>> from Redy.Magic.Classic import const_return
>>> @const_return
>>> def f(x):
>>> return x
>>> r1 = f(1)
>>> assert r1 is 1 and r1 is f(2)
"""
result = _undef
def ret_call(*args, **kwargs):
nonlocal result
if result is _undef:
... | def function[const_return, parameter[func]]:
constant[
>>> from Redy.Magic.Classic import const_return
>>> @const_return
>>> def f(x):
>>> return x
>>> r1 = f(1)
>>> assert r1 is 1 and r1 is f(2)
]
variable[result] assign[=] name[_undef]
def function[ret_call, par... | keyword[def] identifier[const_return] ( identifier[func] ):
literal[string]
identifier[result] = identifier[_undef]
keyword[def] identifier[ret_call] (* identifier[args] ,** identifier[kwargs] ):
keyword[nonlocal] identifier[result]
keyword[if] identifier[result] keyword[is] ... | def const_return(func):
"""
>>> from Redy.Magic.Classic import const_return
>>> @const_return
>>> def f(x):
>>> return x
>>> r1 = f(1)
>>> assert r1 is 1 and r1 is f(2)
"""
result = _undef
def ret_call(*args, **kwargs):
nonlocal result
if result is _undef:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.