code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def tileXYZToQuadKey(self, x, y, z):
'''
Computes quadKey value based on tile x, y and z values.
'''
quadKey = ''
for i in range(z, 0, -1):
digit = 0
mask = 1 << (i - 1)
if (x & mask) != 0:
digit += 1
if (y & mask) != 0:
digit += 2
quadKey += str(digit)
return quadKey | def function[tileXYZToQuadKey, parameter[self, x, y, z]]:
constant[
Computes quadKey value based on tile x, y and z values.
]
variable[quadKey] assign[=] constant[]
for taget[name[i]] in starred[call[name[range], parameter[name[z], constant[0], <ast.UnaryOp object at 0x7da1b0f3a920>]]] begin[:]
variable[digit] assign[=] constant[0]
variable[mask] assign[=] binary_operation[constant[1] <ast.LShift object at 0x7da2590d69e0> binary_operation[name[i] - constant[1]]]
if compare[binary_operation[name[x] <ast.BitAnd object at 0x7da2590d6b60> name[mask]] not_equal[!=] constant[0]] begin[:]
<ast.AugAssign object at 0x7da1b0ef51b0>
if compare[binary_operation[name[y] <ast.BitAnd object at 0x7da2590d6b60> name[mask]] not_equal[!=] constant[0]] begin[:]
<ast.AugAssign object at 0x7da1b0f0efe0>
<ast.AugAssign object at 0x7da1b0f0e6e0>
return[name[quadKey]] | keyword[def] identifier[tileXYZToQuadKey] ( identifier[self] , identifier[x] , identifier[y] , identifier[z] ):
literal[string]
identifier[quadKey] = literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[z] , literal[int] ,- literal[int] ):
identifier[digit] = literal[int]
identifier[mask] = literal[int] <<( identifier[i] - literal[int] )
keyword[if] ( identifier[x] & identifier[mask] )!= literal[int] :
identifier[digit] += literal[int]
keyword[if] ( identifier[y] & identifier[mask] )!= literal[int] :
identifier[digit] += literal[int]
identifier[quadKey] += identifier[str] ( identifier[digit] )
keyword[return] identifier[quadKey] | def tileXYZToQuadKey(self, x, y, z):
"""
Computes quadKey value based on tile x, y and z values.
"""
quadKey = ''
for i in range(z, 0, -1):
digit = 0
mask = 1 << i - 1
if x & mask != 0:
digit += 1 # depends on [control=['if'], data=[]]
if y & mask != 0:
digit += 2 # depends on [control=['if'], data=[]]
quadKey += str(digit) # depends on [control=['for'], data=['i']]
return quadKey |
def add_from_raw_data(self, raw_data, data_type_id, name, description):
"""
Upload already serialized raw data as a new dataset.
Parameters
----------
raw_data: bytes
Dataset contents to upload.
data_type_id : str
Serialization format of the raw data.
Supported formats are:
'PlainText'
'GenericCSV'
'GenericTSV'
'GenericCSVNoHeader'
'GenericTSVNoHeader'
'ARFF'
See the azureml.DataTypeIds class for constants.
name : str
Name for the new dataset.
description : str
Description for the new dataset.
Returns
-------
SourceDataset
Dataset that was just created.
Use open(), read_as_binary(), read_as_text() or to_dataframe() on
the dataset object to get its contents as a stream, bytes, str or
pandas DataFrame.
"""
_not_none('raw_data', raw_data)
_not_none_or_empty('data_type_id', data_type_id)
_not_none_or_empty('name', name)
_not_none_or_empty('description', description)
return self._upload(raw_data, data_type_id, name, description) | def function[add_from_raw_data, parameter[self, raw_data, data_type_id, name, description]]:
constant[
Upload already serialized raw data as a new dataset.
Parameters
----------
raw_data: bytes
Dataset contents to upload.
data_type_id : str
Serialization format of the raw data.
Supported formats are:
'PlainText'
'GenericCSV'
'GenericTSV'
'GenericCSVNoHeader'
'GenericTSVNoHeader'
'ARFF'
See the azureml.DataTypeIds class for constants.
name : str
Name for the new dataset.
description : str
Description for the new dataset.
Returns
-------
SourceDataset
Dataset that was just created.
Use open(), read_as_binary(), read_as_text() or to_dataframe() on
the dataset object to get its contents as a stream, bytes, str or
pandas DataFrame.
]
call[name[_not_none], parameter[constant[raw_data], name[raw_data]]]
call[name[_not_none_or_empty], parameter[constant[data_type_id], name[data_type_id]]]
call[name[_not_none_or_empty], parameter[constant[name], name[name]]]
call[name[_not_none_or_empty], parameter[constant[description], name[description]]]
return[call[name[self]._upload, parameter[name[raw_data], name[data_type_id], name[name], name[description]]]] | keyword[def] identifier[add_from_raw_data] ( identifier[self] , identifier[raw_data] , identifier[data_type_id] , identifier[name] , identifier[description] ):
literal[string]
identifier[_not_none] ( literal[string] , identifier[raw_data] )
identifier[_not_none_or_empty] ( literal[string] , identifier[data_type_id] )
identifier[_not_none_or_empty] ( literal[string] , identifier[name] )
identifier[_not_none_or_empty] ( literal[string] , identifier[description] )
keyword[return] identifier[self] . identifier[_upload] ( identifier[raw_data] , identifier[data_type_id] , identifier[name] , identifier[description] ) | def add_from_raw_data(self, raw_data, data_type_id, name, description):
"""
Upload already serialized raw data as a new dataset.
Parameters
----------
raw_data: bytes
Dataset contents to upload.
data_type_id : str
Serialization format of the raw data.
Supported formats are:
'PlainText'
'GenericCSV'
'GenericTSV'
'GenericCSVNoHeader'
'GenericTSVNoHeader'
'ARFF'
See the azureml.DataTypeIds class for constants.
name : str
Name for the new dataset.
description : str
Description for the new dataset.
Returns
-------
SourceDataset
Dataset that was just created.
Use open(), read_as_binary(), read_as_text() or to_dataframe() on
the dataset object to get its contents as a stream, bytes, str or
pandas DataFrame.
"""
_not_none('raw_data', raw_data)
_not_none_or_empty('data_type_id', data_type_id)
_not_none_or_empty('name', name)
_not_none_or_empty('description', description)
return self._upload(raw_data, data_type_id, name, description) |
def addList(self, source_id, dir_path, is_recurcive=False, timestamp_reception=None, training_metadata=[]):
"""Add all profile from a given directory."""
if not path.isdir(dir_path):
raise ValueError(dir_path + ' is not a directory')
files_to_send = _get_files_from_dir(dir_path, is_recurcive)
succeed_upload = {}
failed_upload = {}
for file_path in files_to_send:
try:
resp = self.add(source_id=source_id,
file_path=file_path, profile_reference="",
timestamp_reception=timestamp_reception, training_metadata=training_metadata)
if resp['code'] != 200 and resp['code'] != 201:
failed_upload[file_path] = ValueError('Invalid response: ' + str(resp))
else:
succeed_upload[file_path] = resp
except BaseException as e:
failed_upload[file_path] = e
result = {
'success': succeed_upload,
'fail': failed_upload
}
return result | def function[addList, parameter[self, source_id, dir_path, is_recurcive, timestamp_reception, training_metadata]]:
constant[Add all profile from a given directory.]
if <ast.UnaryOp object at 0x7da18f09d2a0> begin[:]
<ast.Raise object at 0x7da18f09da50>
variable[files_to_send] assign[=] call[name[_get_files_from_dir], parameter[name[dir_path], name[is_recurcive]]]
variable[succeed_upload] assign[=] dictionary[[], []]
variable[failed_upload] assign[=] dictionary[[], []]
for taget[name[file_path]] in starred[name[files_to_send]] begin[:]
<ast.Try object at 0x7da18f09c2b0>
variable[result] assign[=] dictionary[[<ast.Constant object at 0x7da20e9571c0>, <ast.Constant object at 0x7da20e955e40>], [<ast.Name object at 0x7da20e955780>, <ast.Name object at 0x7da20e955090>]]
return[name[result]] | keyword[def] identifier[addList] ( identifier[self] , identifier[source_id] , identifier[dir_path] , identifier[is_recurcive] = keyword[False] , identifier[timestamp_reception] = keyword[None] , identifier[training_metadata] =[]):
literal[string]
keyword[if] keyword[not] identifier[path] . identifier[isdir] ( identifier[dir_path] ):
keyword[raise] identifier[ValueError] ( identifier[dir_path] + literal[string] )
identifier[files_to_send] = identifier[_get_files_from_dir] ( identifier[dir_path] , identifier[is_recurcive] )
identifier[succeed_upload] ={}
identifier[failed_upload] ={}
keyword[for] identifier[file_path] keyword[in] identifier[files_to_send] :
keyword[try] :
identifier[resp] = identifier[self] . identifier[add] ( identifier[source_id] = identifier[source_id] ,
identifier[file_path] = identifier[file_path] , identifier[profile_reference] = literal[string] ,
identifier[timestamp_reception] = identifier[timestamp_reception] , identifier[training_metadata] = identifier[training_metadata] )
keyword[if] identifier[resp] [ literal[string] ]!= literal[int] keyword[and] identifier[resp] [ literal[string] ]!= literal[int] :
identifier[failed_upload] [ identifier[file_path] ]= identifier[ValueError] ( literal[string] + identifier[str] ( identifier[resp] ))
keyword[else] :
identifier[succeed_upload] [ identifier[file_path] ]= identifier[resp]
keyword[except] identifier[BaseException] keyword[as] identifier[e] :
identifier[failed_upload] [ identifier[file_path] ]= identifier[e]
identifier[result] ={
literal[string] : identifier[succeed_upload] ,
literal[string] : identifier[failed_upload]
}
keyword[return] identifier[result] | def addList(self, source_id, dir_path, is_recurcive=False, timestamp_reception=None, training_metadata=[]):
"""Add all profile from a given directory."""
if not path.isdir(dir_path):
raise ValueError(dir_path + ' is not a directory') # depends on [control=['if'], data=[]]
files_to_send = _get_files_from_dir(dir_path, is_recurcive)
succeed_upload = {}
failed_upload = {}
for file_path in files_to_send:
try:
resp = self.add(source_id=source_id, file_path=file_path, profile_reference='', timestamp_reception=timestamp_reception, training_metadata=training_metadata)
if resp['code'] != 200 and resp['code'] != 201:
failed_upload[file_path] = ValueError('Invalid response: ' + str(resp)) # depends on [control=['if'], data=[]]
else:
succeed_upload[file_path] = resp # depends on [control=['try'], data=[]]
except BaseException as e:
failed_upload[file_path] = e # depends on [control=['except'], data=['e']] # depends on [control=['for'], data=['file_path']]
result = {'success': succeed_upload, 'fail': failed_upload}
return result |
def fabric_route_mcast_rbridge_id_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fabric = ET.SubElement(config, "fabric", xmlns="urn:brocade.com:mgmt:brocade-fabric-service")
route = ET.SubElement(fabric, "route")
mcast = ET.SubElement(route, "mcast")
rbridge_id = ET.SubElement(mcast, "rbridge-id")
rbridge_id = ET.SubElement(rbridge_id, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) | def function[fabric_route_mcast_rbridge_id_rbridge_id, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[fabric] assign[=] call[name[ET].SubElement, parameter[name[config], constant[fabric]]]
variable[route] assign[=] call[name[ET].SubElement, parameter[name[fabric], constant[route]]]
variable[mcast] assign[=] call[name[ET].SubElement, parameter[name[route], constant[mcast]]]
variable[rbridge_id] assign[=] call[name[ET].SubElement, parameter[name[mcast], constant[rbridge-id]]]
variable[rbridge_id] assign[=] call[name[ET].SubElement, parameter[name[rbridge_id], constant[rbridge-id]]]
name[rbridge_id].text assign[=] call[name[kwargs].pop, parameter[constant[rbridge_id]]]
variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]]
return[call[name[callback], parameter[name[config]]]] | keyword[def] identifier[fabric_route_mcast_rbridge_id_rbridge_id] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[fabric] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identifier[xmlns] = literal[string] )
identifier[route] = identifier[ET] . identifier[SubElement] ( identifier[fabric] , literal[string] )
identifier[mcast] = identifier[ET] . identifier[SubElement] ( identifier[route] , literal[string] )
identifier[rbridge_id] = identifier[ET] . identifier[SubElement] ( identifier[mcast] , literal[string] )
identifier[rbridge_id] = identifier[ET] . identifier[SubElement] ( identifier[rbridge_id] , literal[string] )
identifier[rbridge_id] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] )
keyword[return] identifier[callback] ( identifier[config] ) | def fabric_route_mcast_rbridge_id_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
fabric = ET.SubElement(config, 'fabric', xmlns='urn:brocade.com:mgmt:brocade-fabric-service')
route = ET.SubElement(fabric, 'route')
mcast = ET.SubElement(route, 'mcast')
rbridge_id = ET.SubElement(mcast, 'rbridge-id')
rbridge_id = ET.SubElement(rbridge_id, 'rbridge-id')
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
def build(args, parser):
"""
Validates workflow source directory and creates a new (global) workflow based on it.
Raises: WorkflowBuilderException if the workflow cannot be created.
"""
if args is None:
raise Exception("arguments not provided")
try:
json_spec = _parse_executable_spec(args.src_dir, "dxworkflow.json", parser)
workflow_id = _build_or_update_workflow(json_spec, args)
_print_output(workflow_id, args)
except WorkflowBuilderException as e:
print("Error: %s" % (e.args,), file=sys.stderr)
sys.exit(3) | def function[build, parameter[args, parser]]:
constant[
Validates workflow source directory and creates a new (global) workflow based on it.
Raises: WorkflowBuilderException if the workflow cannot be created.
]
if compare[name[args] is constant[None]] begin[:]
<ast.Raise object at 0x7da20c6c7640>
<ast.Try object at 0x7da20c6c7b20> | keyword[def] identifier[build] ( identifier[args] , identifier[parser] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[try] :
identifier[json_spec] = identifier[_parse_executable_spec] ( identifier[args] . identifier[src_dir] , literal[string] , identifier[parser] )
identifier[workflow_id] = identifier[_build_or_update_workflow] ( identifier[json_spec] , identifier[args] )
identifier[_print_output] ( identifier[workflow_id] , identifier[args] )
keyword[except] identifier[WorkflowBuilderException] keyword[as] identifier[e] :
identifier[print] ( literal[string] %( identifier[e] . identifier[args] ,), identifier[file] = identifier[sys] . identifier[stderr] )
identifier[sys] . identifier[exit] ( literal[int] ) | def build(args, parser):
"""
Validates workflow source directory and creates a new (global) workflow based on it.
Raises: WorkflowBuilderException if the workflow cannot be created.
"""
if args is None:
raise Exception('arguments not provided') # depends on [control=['if'], data=[]]
try:
json_spec = _parse_executable_spec(args.src_dir, 'dxworkflow.json', parser)
workflow_id = _build_or_update_workflow(json_spec, args)
_print_output(workflow_id, args) # depends on [control=['try'], data=[]]
except WorkflowBuilderException as e:
print('Error: %s' % (e.args,), file=sys.stderr)
sys.exit(3) # depends on [control=['except'], data=['e']] |
def open_model(self, model_path, audit=False):
"""Append a open non-workshared model entry to the journal.
This instructs Revit to open a non-workshared model.
Args:
model_path (str): full path to non-workshared model
audit (bool): if True audits the model when opening
"""
if audit:
self._add_entry(templates.FILE_OPEN_AUDIT
.format(model_path=model_path))
else:
self._add_entry(templates.FILE_OPEN
.format(model_path=model_path)) | def function[open_model, parameter[self, model_path, audit]]:
constant[Append a open non-workshared model entry to the journal.
This instructs Revit to open a non-workshared model.
Args:
model_path (str): full path to non-workshared model
audit (bool): if True audits the model when opening
]
if name[audit] begin[:]
call[name[self]._add_entry, parameter[call[name[templates].FILE_OPEN_AUDIT.format, parameter[]]]] | keyword[def] identifier[open_model] ( identifier[self] , identifier[model_path] , identifier[audit] = keyword[False] ):
literal[string]
keyword[if] identifier[audit] :
identifier[self] . identifier[_add_entry] ( identifier[templates] . identifier[FILE_OPEN_AUDIT]
. identifier[format] ( identifier[model_path] = identifier[model_path] ))
keyword[else] :
identifier[self] . identifier[_add_entry] ( identifier[templates] . identifier[FILE_OPEN]
. identifier[format] ( identifier[model_path] = identifier[model_path] )) | def open_model(self, model_path, audit=False):
"""Append a open non-workshared model entry to the journal.
This instructs Revit to open a non-workshared model.
Args:
model_path (str): full path to non-workshared model
audit (bool): if True audits the model when opening
"""
if audit:
self._add_entry(templates.FILE_OPEN_AUDIT.format(model_path=model_path)) # depends on [control=['if'], data=[]]
else:
self._add_entry(templates.FILE_OPEN.format(model_path=model_path)) |
def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.menu.popup(event.globalPos())
event.accept() | def function[contextMenuEvent, parameter[self, event]]:
constant[Reimplement Qt method]
call[name[self].menu.popup, parameter[call[name[event].globalPos, parameter[]]]]
call[name[event].accept, parameter[]] | keyword[def] identifier[contextMenuEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[self] . identifier[menu] . identifier[popup] ( identifier[event] . identifier[globalPos] ())
identifier[event] . identifier[accept] () | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.menu.popup(event.globalPos())
event.accept() |
def initialize_pop(self):
"""Generates the initial population and assigns fitnesses."""
self.initialize_cma_es(
sigma=self._params['sigma'], weights=self._params['weights'],
lambda_=self._params['popsize'],
centroid=[0] * len(self._params['value_means']))
self.toolbox.register("individual", self.make_individual)
self.toolbox.register("generate", self.generate,
self.toolbox.individual)
self.toolbox.register("population", tools.initRepeat,
list, self.initial_individual)
self.toolbox.register("update", self.update)
self.population = self.toolbox.population(n=self._params['popsize'])
self.assign_fitnesses(self.population)
self._params['model_count'] += len(self.population) | def function[initialize_pop, parameter[self]]:
constant[Generates the initial population and assigns fitnesses.]
call[name[self].initialize_cma_es, parameter[]]
call[name[self].toolbox.register, parameter[constant[individual], name[self].make_individual]]
call[name[self].toolbox.register, parameter[constant[generate], name[self].generate, name[self].toolbox.individual]]
call[name[self].toolbox.register, parameter[constant[population], name[tools].initRepeat, name[list], name[self].initial_individual]]
call[name[self].toolbox.register, parameter[constant[update], name[self].update]]
name[self].population assign[=] call[name[self].toolbox.population, parameter[]]
call[name[self].assign_fitnesses, parameter[name[self].population]]
<ast.AugAssign object at 0x7da1b264a110> | keyword[def] identifier[initialize_pop] ( identifier[self] ):
literal[string]
identifier[self] . identifier[initialize_cma_es] (
identifier[sigma] = identifier[self] . identifier[_params] [ literal[string] ], identifier[weights] = identifier[self] . identifier[_params] [ literal[string] ],
identifier[lambda_] = identifier[self] . identifier[_params] [ literal[string] ],
identifier[centroid] =[ literal[int] ]* identifier[len] ( identifier[self] . identifier[_params] [ literal[string] ]))
identifier[self] . identifier[toolbox] . identifier[register] ( literal[string] , identifier[self] . identifier[make_individual] )
identifier[self] . identifier[toolbox] . identifier[register] ( literal[string] , identifier[self] . identifier[generate] ,
identifier[self] . identifier[toolbox] . identifier[individual] )
identifier[self] . identifier[toolbox] . identifier[register] ( literal[string] , identifier[tools] . identifier[initRepeat] ,
identifier[list] , identifier[self] . identifier[initial_individual] )
identifier[self] . identifier[toolbox] . identifier[register] ( literal[string] , identifier[self] . identifier[update] )
identifier[self] . identifier[population] = identifier[self] . identifier[toolbox] . identifier[population] ( identifier[n] = identifier[self] . identifier[_params] [ literal[string] ])
identifier[self] . identifier[assign_fitnesses] ( identifier[self] . identifier[population] )
identifier[self] . identifier[_params] [ literal[string] ]+= identifier[len] ( identifier[self] . identifier[population] ) | def initialize_pop(self):
"""Generates the initial population and assigns fitnesses."""
self.initialize_cma_es(sigma=self._params['sigma'], weights=self._params['weights'], lambda_=self._params['popsize'], centroid=[0] * len(self._params['value_means']))
self.toolbox.register('individual', self.make_individual)
self.toolbox.register('generate', self.generate, self.toolbox.individual)
self.toolbox.register('population', tools.initRepeat, list, self.initial_individual)
self.toolbox.register('update', self.update)
self.population = self.toolbox.population(n=self._params['popsize'])
self.assign_fitnesses(self.population)
self._params['model_count'] += len(self.population) |
def step_undefined_step_snippet_should_not_exist_for(context, step):
"""
Checks if an undefined-step snippet is provided for a step
in behave command output (last command).
"""
undefined_step_snippet = make_undefined_step_snippet(step)
context.execute_steps(u'''\
Then the command output should not contain:
"""
{undefined_step_snippet}
"""
'''.format(undefined_step_snippet=text_indent(undefined_step_snippet, 4))) | def function[step_undefined_step_snippet_should_not_exist_for, parameter[context, step]]:
constant[
Checks if an undefined-step snippet is provided for a step
in behave command output (last command).
]
variable[undefined_step_snippet] assign[=] call[name[make_undefined_step_snippet], parameter[name[step]]]
call[name[context].execute_steps, parameter[call[constant[Then the command output should not contain:
"""
{undefined_step_snippet}
"""
].format, parameter[]]]] | keyword[def] identifier[step_undefined_step_snippet_should_not_exist_for] ( identifier[context] , identifier[step] ):
literal[string]
identifier[undefined_step_snippet] = identifier[make_undefined_step_snippet] ( identifier[step] )
identifier[context] . identifier[execute_steps] ( literal[string] . identifier[format] ( identifier[undefined_step_snippet] = identifier[text_indent] ( identifier[undefined_step_snippet] , literal[int] ))) | def step_undefined_step_snippet_should_not_exist_for(context, step):
"""
Checks if an undefined-step snippet is provided for a step
in behave command output (last command).
"""
undefined_step_snippet = make_undefined_step_snippet(step)
context.execute_steps(u'Then the command output should not contain:\n """\n {undefined_step_snippet}\n """\n '.format(undefined_step_snippet=text_indent(undefined_step_snippet, 4))) |
def combine_validations(items, vkey="validate"):
"""Combine multiple batch validations into validation outputs.
"""
csvs = set([])
pngs = set([])
for v in [x.get(vkey) for x in items]:
if v and v.get("grading_summary"):
csvs.add(v.get("grading_summary"))
if v and v.get("grading_plots"):
pngs |= set(v.get("grading_plots"))
if len(csvs) == 1:
grading_summary = csvs.pop()
else:
grading_summary = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(items[0]), vkey)),
"grading-summary-combined.csv")
with open(grading_summary, "w") as out_handle:
for i, csv in enumerate(sorted(list(csvs))):
with open(csv) as in_handle:
h = in_handle.readline()
if i == 0:
out_handle.write(h)
for l in in_handle:
out_handle.write(l)
return {"grading_plots": sorted(list(pngs)), "grading_summary": grading_summary} | def function[combine_validations, parameter[items, vkey]]:
constant[Combine multiple batch validations into validation outputs.
]
variable[csvs] assign[=] call[name[set], parameter[list[[]]]]
variable[pngs] assign[=] call[name[set], parameter[list[[]]]]
for taget[name[v]] in starred[<ast.ListComp object at 0x7da1b18a3bb0>] begin[:]
if <ast.BoolOp object at 0x7da1b18a39d0> begin[:]
call[name[csvs].add, parameter[call[name[v].get, parameter[constant[grading_summary]]]]]
if <ast.BoolOp object at 0x7da1b18a36d0> begin[:]
<ast.AugAssign object at 0x7da1b18a35b0>
if compare[call[name[len], parameter[name[csvs]]] equal[==] constant[1]] begin[:]
variable[grading_summary] assign[=] call[name[csvs].pop, parameter[]]
return[dictionary[[<ast.Constant object at 0x7da1b18a0220>, <ast.Constant object at 0x7da1b18a0250>], [<ast.Call object at 0x7da1b18a0280>, <ast.Name object at 0x7da1b18a0370>]]] | keyword[def] identifier[combine_validations] ( identifier[items] , identifier[vkey] = literal[string] ):
literal[string]
identifier[csvs] = identifier[set] ([])
identifier[pngs] = identifier[set] ([])
keyword[for] identifier[v] keyword[in] [ identifier[x] . identifier[get] ( identifier[vkey] ) keyword[for] identifier[x] keyword[in] identifier[items] ]:
keyword[if] identifier[v] keyword[and] identifier[v] . identifier[get] ( literal[string] ):
identifier[csvs] . identifier[add] ( identifier[v] . identifier[get] ( literal[string] ))
keyword[if] identifier[v] keyword[and] identifier[v] . identifier[get] ( literal[string] ):
identifier[pngs] |= identifier[set] ( identifier[v] . identifier[get] ( literal[string] ))
keyword[if] identifier[len] ( identifier[csvs] )== literal[int] :
identifier[grading_summary] = identifier[csvs] . identifier[pop] ()
keyword[else] :
identifier[grading_summary] = identifier[os] . identifier[path] . identifier[join] ( identifier[utils] . identifier[safe_makedir] ( identifier[os] . identifier[path] . identifier[join] ( identifier[dd] . identifier[get_work_dir] ( identifier[items] [ literal[int] ]), identifier[vkey] )),
literal[string] )
keyword[with] identifier[open] ( identifier[grading_summary] , literal[string] ) keyword[as] identifier[out_handle] :
keyword[for] identifier[i] , identifier[csv] keyword[in] identifier[enumerate] ( identifier[sorted] ( identifier[list] ( identifier[csvs] ))):
keyword[with] identifier[open] ( identifier[csv] ) keyword[as] identifier[in_handle] :
identifier[h] = identifier[in_handle] . identifier[readline] ()
keyword[if] identifier[i] == literal[int] :
identifier[out_handle] . identifier[write] ( identifier[h] )
keyword[for] identifier[l] keyword[in] identifier[in_handle] :
identifier[out_handle] . identifier[write] ( identifier[l] )
keyword[return] { literal[string] : identifier[sorted] ( identifier[list] ( identifier[pngs] )), literal[string] : identifier[grading_summary] } | def combine_validations(items, vkey='validate'):
"""Combine multiple batch validations into validation outputs.
"""
csvs = set([])
pngs = set([])
for v in [x.get(vkey) for x in items]:
if v and v.get('grading_summary'):
csvs.add(v.get('grading_summary')) # depends on [control=['if'], data=[]]
if v and v.get('grading_plots'):
pngs |= set(v.get('grading_plots')) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['v']]
if len(csvs) == 1:
grading_summary = csvs.pop() # depends on [control=['if'], data=[]]
else:
grading_summary = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(items[0]), vkey)), 'grading-summary-combined.csv')
with open(grading_summary, 'w') as out_handle:
for (i, csv) in enumerate(sorted(list(csvs))):
with open(csv) as in_handle:
h = in_handle.readline()
if i == 0:
out_handle.write(h) # depends on [control=['if'], data=[]]
for l in in_handle:
out_handle.write(l) # depends on [control=['for'], data=['l']] # depends on [control=['with'], data=['in_handle']] # depends on [control=['for'], data=[]] # depends on [control=['with'], data=['open', 'out_handle']]
return {'grading_plots': sorted(list(pngs)), 'grading_summary': grading_summary} |
def str_def(self):
"""
:term:`string`: The exception as a string in a Python definition-style
format, e.g. for parsing by scripts:
.. code-block:: text
classname={}; operation_timeout={}; message={};
"""
return "classname={!r}; operation_timeout={!r}; message={!r};". \
format(self.__class__.__name__, self.operation_timeout,
self.args[0]) | def function[str_def, parameter[self]]:
constant[
:term:`string`: The exception as a string in a Python definition-style
format, e.g. for parsing by scripts:
.. code-block:: text
classname={}; operation_timeout={}; message={};
]
return[call[constant[classname={!r}; operation_timeout={!r}; message={!r};].format, parameter[name[self].__class__.__name__, name[self].operation_timeout, call[name[self].args][constant[0]]]]] | keyword[def] identifier[str_def] ( identifier[self] ):
literal[string]
keyword[return] literal[string] . identifier[format] ( identifier[self] . identifier[__class__] . identifier[__name__] , identifier[self] . identifier[operation_timeout] ,
identifier[self] . identifier[args] [ literal[int] ]) | def str_def(self):
"""
:term:`string`: The exception as a string in a Python definition-style
format, e.g. for parsing by scripts:
.. code-block:: text
classname={}; operation_timeout={}; message={};
"""
return 'classname={!r}; operation_timeout={!r}; message={!r};'.format(self.__class__.__name__, self.operation_timeout, self.args[0]) |
def _create_in_progress(self):
"""
Creating this service is handled asynchronously so this method will
simply check if the create is in progress. If it is not in progress,
we could probably infer it either failed or succeeded.
"""
instance = self.service.service.get_instance(self.service.name)
if (instance['last_operation']['state'] == 'in progress' and
instance['last_operation']['type'] == 'create'):
return True
return False | def function[_create_in_progress, parameter[self]]:
constant[
Creating this service is handled asynchronously so this method will
simply check if the create is in progress. If it is not in progress,
we could probably infer it either failed or succeeded.
]
variable[instance] assign[=] call[name[self].service.service.get_instance, parameter[name[self].service.name]]
if <ast.BoolOp object at 0x7da18f812440> begin[:]
return[constant[True]]
return[constant[False]] | keyword[def] identifier[_create_in_progress] ( identifier[self] ):
literal[string]
identifier[instance] = identifier[self] . identifier[service] . identifier[service] . identifier[get_instance] ( identifier[self] . identifier[service] . identifier[name] )
keyword[if] ( identifier[instance] [ literal[string] ][ literal[string] ]== literal[string] keyword[and]
identifier[instance] [ literal[string] ][ literal[string] ]== literal[string] ):
keyword[return] keyword[True]
keyword[return] keyword[False] | def _create_in_progress(self):
"""
Creating this service is handled asynchronously so this method will
simply check if the create is in progress. If it is not in progress,
we could probably infer it either failed or succeeded.
"""
instance = self.service.service.get_instance(self.service.name)
if instance['last_operation']['state'] == 'in progress' and instance['last_operation']['type'] == 'create':
return True # depends on [control=['if'], data=[]]
return False |
def process_other_set(hdf5_file, which_set, image_archive, patch_archive,
groundtruth, offset):
"""Process the validation or test set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate images from the patch
archive.
image_archive : str or file-like object
The filename or file-handle for the TAR archive containing images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
groundtruth : iterable
Iterable container containing scalar 0-based class index for each
image, sorted by filename.
offset : int
The offset in the HDF5 datasets at which to start writing.
"""
producer = partial(other_set_producer, image_archive=image_archive,
patch_archive=patch_archive,
groundtruth=groundtruth, which_set=which_set)
consumer = partial(image_consumer, hdf5_file=hdf5_file,
num_expected=len(groundtruth), offset=offset)
producer_consumer(producer, consumer) | def function[process_other_set, parameter[hdf5_file, which_set, image_archive, patch_archive, groundtruth, offset]]:
constant[Process the validation or test set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate images from the patch
archive.
image_archive : str or file-like object
The filename or file-handle for the TAR archive containing images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
groundtruth : iterable
Iterable container containing scalar 0-based class index for each
image, sorted by filename.
offset : int
The offset in the HDF5 datasets at which to start writing.
]
variable[producer] assign[=] call[name[partial], parameter[name[other_set_producer]]]
variable[consumer] assign[=] call[name[partial], parameter[name[image_consumer]]]
call[name[producer_consumer], parameter[name[producer], name[consumer]]] | keyword[def] identifier[process_other_set] ( identifier[hdf5_file] , identifier[which_set] , identifier[image_archive] , identifier[patch_archive] ,
identifier[groundtruth] , identifier[offset] ):
literal[string]
identifier[producer] = identifier[partial] ( identifier[other_set_producer] , identifier[image_archive] = identifier[image_archive] ,
identifier[patch_archive] = identifier[patch_archive] ,
identifier[groundtruth] = identifier[groundtruth] , identifier[which_set] = identifier[which_set] )
identifier[consumer] = identifier[partial] ( identifier[image_consumer] , identifier[hdf5_file] = identifier[hdf5_file] ,
identifier[num_expected] = identifier[len] ( identifier[groundtruth] ), identifier[offset] = identifier[offset] )
identifier[producer_consumer] ( identifier[producer] , identifier[consumer] ) | def process_other_set(hdf5_file, which_set, image_archive, patch_archive, groundtruth, offset):
"""Process the validation or test set.
Parameters
----------
hdf5_file : :class:`h5py.File` instance
HDF5 file handle to which to write. Assumes `features`, `targets`
and `filenames` already exist and have first dimension larger than
`sum(images_per_class)`.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate images from the patch
archive.
image_archive : str or file-like object
The filename or file-handle for the TAR archive containing images.
patch_archive : str or file-like object
Filename or file handle for the TAR archive of patch images.
groundtruth : iterable
Iterable container containing scalar 0-based class index for each
image, sorted by filename.
offset : int
The offset in the HDF5 datasets at which to start writing.
"""
producer = partial(other_set_producer, image_archive=image_archive, patch_archive=patch_archive, groundtruth=groundtruth, which_set=which_set)
consumer = partial(image_consumer, hdf5_file=hdf5_file, num_expected=len(groundtruth), offset=offset)
producer_consumer(producer, consumer) |
def extern_call(self, context_handle, func, args_ptr, args_len):
"""Given a callable, call it."""
c = self._ffi.from_handle(context_handle)
runnable = c.from_value(func[0])
args = tuple(c.from_value(arg[0]) for arg in self._ffi.unpack(args_ptr, args_len))
return self.call(c, runnable, args) | def function[extern_call, parameter[self, context_handle, func, args_ptr, args_len]]:
constant[Given a callable, call it.]
variable[c] assign[=] call[name[self]._ffi.from_handle, parameter[name[context_handle]]]
variable[runnable] assign[=] call[name[c].from_value, parameter[call[name[func]][constant[0]]]]
variable[args] assign[=] call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da1b22d1750>]]
return[call[name[self].call, parameter[name[c], name[runnable], name[args]]]] | keyword[def] identifier[extern_call] ( identifier[self] , identifier[context_handle] , identifier[func] , identifier[args_ptr] , identifier[args_len] ):
literal[string]
identifier[c] = identifier[self] . identifier[_ffi] . identifier[from_handle] ( identifier[context_handle] )
identifier[runnable] = identifier[c] . identifier[from_value] ( identifier[func] [ literal[int] ])
identifier[args] = identifier[tuple] ( identifier[c] . identifier[from_value] ( identifier[arg] [ literal[int] ]) keyword[for] identifier[arg] keyword[in] identifier[self] . identifier[_ffi] . identifier[unpack] ( identifier[args_ptr] , identifier[args_len] ))
keyword[return] identifier[self] . identifier[call] ( identifier[c] , identifier[runnable] , identifier[args] ) | def extern_call(self, context_handle, func, args_ptr, args_len):
"""Given a callable, call it."""
c = self._ffi.from_handle(context_handle)
runnable = c.from_value(func[0])
args = tuple((c.from_value(arg[0]) for arg in self._ffi.unpack(args_ptr, args_len)))
return self.call(c, runnable, args) |
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]:
"""
Generates the final page sequence from the starting number of sheets.
"""
n_pages = calc_n_virtual_pages(n_sheets)
assert n_pages % 4 == 0
half_n_pages = n_pages // 2
firsthalf = list(range(half_n_pages))
secondhalf = list(reversed(range(half_n_pages, n_pages)))
# Seen from the top of an UNFOLDED booklet (e.g. a stack of paper that's
# come out of your printer), "firsthalf" are on the right (from top to
# bottom: recto facing up, then verso facing down, then recto, then verso)
# and "secondhalf" are on the left (from top to bottom: verso facing up,
# then recto facing down, etc.).
sequence = [] # type: List[int]
top = True
for left, right in zip(secondhalf, firsthalf):
if not top:
left, right = right, left
sequence += [left, right]
top = not top
if one_based:
sequence = [x + 1 for x in sequence]
log.debug("{} sheets => page sequence {!r}", n_sheets, sequence)
return sequence | def function[page_sequence, parameter[n_sheets, one_based]]:
constant[
Generates the final page sequence from the starting number of sheets.
]
variable[n_pages] assign[=] call[name[calc_n_virtual_pages], parameter[name[n_sheets]]]
assert[compare[binary_operation[name[n_pages] <ast.Mod object at 0x7da2590d6920> constant[4]] equal[==] constant[0]]]
variable[half_n_pages] assign[=] binary_operation[name[n_pages] <ast.FloorDiv object at 0x7da2590d6bc0> constant[2]]
variable[firsthalf] assign[=] call[name[list], parameter[call[name[range], parameter[name[half_n_pages]]]]]
variable[secondhalf] assign[=] call[name[list], parameter[call[name[reversed], parameter[call[name[range], parameter[name[half_n_pages], name[n_pages]]]]]]]
variable[sequence] assign[=] list[[]]
variable[top] assign[=] constant[True]
for taget[tuple[[<ast.Name object at 0x7da1b18345b0>, <ast.Name object at 0x7da1b1835ff0>]]] in starred[call[name[zip], parameter[name[secondhalf], name[firsthalf]]]] begin[:]
if <ast.UnaryOp object at 0x7da1b1836d70> begin[:]
<ast.Tuple object at 0x7da1b1835b10> assign[=] tuple[[<ast.Name object at 0x7da1b1836440>, <ast.Name object at 0x7da1b1834580>]]
<ast.AugAssign object at 0x7da1b1834a00>
variable[top] assign[=] <ast.UnaryOp object at 0x7da1b1835330>
if name[one_based] begin[:]
variable[sequence] assign[=] <ast.ListComp object at 0x7da1b18376a0>
call[name[log].debug, parameter[constant[{} sheets => page sequence {!r}], name[n_sheets], name[sequence]]]
return[name[sequence]] | keyword[def] identifier[page_sequence] ( identifier[n_sheets] : identifier[int] , identifier[one_based] : identifier[bool] = keyword[True] )-> identifier[List] [ identifier[int] ]:
literal[string]
identifier[n_pages] = identifier[calc_n_virtual_pages] ( identifier[n_sheets] )
keyword[assert] identifier[n_pages] % literal[int] == literal[int]
identifier[half_n_pages] = identifier[n_pages] // literal[int]
identifier[firsthalf] = identifier[list] ( identifier[range] ( identifier[half_n_pages] ))
identifier[secondhalf] = identifier[list] ( identifier[reversed] ( identifier[range] ( identifier[half_n_pages] , identifier[n_pages] )))
identifier[sequence] =[]
identifier[top] = keyword[True]
keyword[for] identifier[left] , identifier[right] keyword[in] identifier[zip] ( identifier[secondhalf] , identifier[firsthalf] ):
keyword[if] keyword[not] identifier[top] :
identifier[left] , identifier[right] = identifier[right] , identifier[left]
identifier[sequence] +=[ identifier[left] , identifier[right] ]
identifier[top] = keyword[not] identifier[top]
keyword[if] identifier[one_based] :
identifier[sequence] =[ identifier[x] + literal[int] keyword[for] identifier[x] keyword[in] identifier[sequence] ]
identifier[log] . identifier[debug] ( literal[string] , identifier[n_sheets] , identifier[sequence] )
keyword[return] identifier[sequence] | def page_sequence(n_sheets: int, one_based: bool=True) -> List[int]:
"""
Generates the final page sequence from the starting number of sheets.
"""
n_pages = calc_n_virtual_pages(n_sheets)
assert n_pages % 4 == 0
half_n_pages = n_pages // 2
firsthalf = list(range(half_n_pages))
secondhalf = list(reversed(range(half_n_pages, n_pages)))
# Seen from the top of an UNFOLDED booklet (e.g. a stack of paper that's
# come out of your printer), "firsthalf" are on the right (from top to
# bottom: recto facing up, then verso facing down, then recto, then verso)
# and "secondhalf" are on the left (from top to bottom: verso facing up,
# then recto facing down, etc.).
sequence = [] # type: List[int]
top = True
for (left, right) in zip(secondhalf, firsthalf):
if not top:
(left, right) = (right, left) # depends on [control=['if'], data=[]]
sequence += [left, right]
top = not top # depends on [control=['for'], data=[]]
if one_based:
sequence = [x + 1 for x in sequence] # depends on [control=['if'], data=[]]
log.debug('{} sheets => page sequence {!r}', n_sheets, sequence)
return sequence |
def update_list_widget(self):
"""Update list widget when radio button is clicked."""
# Get selected radio button
radio_button_checked_id = self.input_button_group.checkedId()
# No radio button checked, then default value = None
if radio_button_checked_id > -1:
selected_dict = list(self._parameter.options.values())[
radio_button_checked_id]
if selected_dict.get('type') == MULTIPLE_DYNAMIC:
for field in selected_dict.get('value'):
# Update list widget
field_item = QListWidgetItem(self.list_widget)
field_item.setFlags(
Qt.ItemIsEnabled
| Qt.ItemIsSelectable
| Qt.ItemIsDragEnabled)
field_item.setData(Qt.UserRole, field)
field_item.setText(field)
self.list_widget.addItem(field_item) | def function[update_list_widget, parameter[self]]:
constant[Update list widget when radio button is clicked.]
variable[radio_button_checked_id] assign[=] call[name[self].input_button_group.checkedId, parameter[]]
if compare[name[radio_button_checked_id] greater[>] <ast.UnaryOp object at 0x7da20c6a83d0>] begin[:]
variable[selected_dict] assign[=] call[call[name[list], parameter[call[name[self]._parameter.options.values, parameter[]]]]][name[radio_button_checked_id]]
if compare[call[name[selected_dict].get, parameter[constant[type]]] equal[==] name[MULTIPLE_DYNAMIC]] begin[:]
for taget[name[field]] in starred[call[name[selected_dict].get, parameter[constant[value]]]] begin[:]
variable[field_item] assign[=] call[name[QListWidgetItem], parameter[name[self].list_widget]]
call[name[field_item].setFlags, parameter[binary_operation[binary_operation[name[Qt].ItemIsEnabled <ast.BitOr object at 0x7da2590d6aa0> name[Qt].ItemIsSelectable] <ast.BitOr object at 0x7da2590d6aa0> name[Qt].ItemIsDragEnabled]]]
call[name[field_item].setData, parameter[name[Qt].UserRole, name[field]]]
call[name[field_item].setText, parameter[name[field]]]
call[name[self].list_widget.addItem, parameter[name[field_item]]] | keyword[def] identifier[update_list_widget] ( identifier[self] ):
literal[string]
identifier[radio_button_checked_id] = identifier[self] . identifier[input_button_group] . identifier[checkedId] ()
keyword[if] identifier[radio_button_checked_id] >- literal[int] :
identifier[selected_dict] = identifier[list] ( identifier[self] . identifier[_parameter] . identifier[options] . identifier[values] ())[
identifier[radio_button_checked_id] ]
keyword[if] identifier[selected_dict] . identifier[get] ( literal[string] )== identifier[MULTIPLE_DYNAMIC] :
keyword[for] identifier[field] keyword[in] identifier[selected_dict] . identifier[get] ( literal[string] ):
identifier[field_item] = identifier[QListWidgetItem] ( identifier[self] . identifier[list_widget] )
identifier[field_item] . identifier[setFlags] (
identifier[Qt] . identifier[ItemIsEnabled]
| identifier[Qt] . identifier[ItemIsSelectable]
| identifier[Qt] . identifier[ItemIsDragEnabled] )
identifier[field_item] . identifier[setData] ( identifier[Qt] . identifier[UserRole] , identifier[field] )
identifier[field_item] . identifier[setText] ( identifier[field] )
identifier[self] . identifier[list_widget] . identifier[addItem] ( identifier[field_item] ) | def update_list_widget(self):
"""Update list widget when radio button is clicked."""
# Get selected radio button
radio_button_checked_id = self.input_button_group.checkedId()
# No radio button checked, then default value = None
if radio_button_checked_id > -1:
selected_dict = list(self._parameter.options.values())[radio_button_checked_id]
if selected_dict.get('type') == MULTIPLE_DYNAMIC:
for field in selected_dict.get('value'):
# Update list widget
field_item = QListWidgetItem(self.list_widget)
field_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
field_item.setData(Qt.UserRole, field)
field_item.setText(field)
self.list_widget.addItem(field_item) # depends on [control=['for'], data=['field']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['radio_button_checked_id']] |
def mask_roi_unique(self):
"""
Assemble a set of unique magnitude tuples for the ROI
"""
# There is no good inherent way in numpy to do this...
# http://stackoverflow.com/q/16970982/
# Also possible and simple:
#return np.unique(zip(self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse))
A = np.vstack([self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse]).T
B = A[np.lexsort(A.T[::-1])]
return B[np.concatenate(([True],np.any(B[1:]!=B[:-1],axis=1)))] | def function[mask_roi_unique, parameter[self]]:
constant[
Assemble a set of unique magnitude tuples for the ROI
]
variable[A] assign[=] call[name[np].vstack, parameter[list[[<ast.Attribute object at 0x7da1b259f7c0>, <ast.Attribute object at 0x7da1b259cee0>]]]].T
variable[B] assign[=] call[name[A]][call[name[np].lexsort, parameter[call[name[A].T][<ast.Slice object at 0x7da2047eb820>]]]]
return[call[name[B]][call[name[np].concatenate, parameter[tuple[[<ast.List object at 0x7da2047ebcd0>, <ast.Call object at 0x7da2047ebe50>]]]]]] | keyword[def] identifier[mask_roi_unique] ( identifier[self] ):
literal[string]
identifier[A] = identifier[np] . identifier[vstack] ([ identifier[self] . identifier[mask_1] . identifier[mask_roi_sparse] , identifier[self] . identifier[mask_2] . identifier[mask_roi_sparse] ]). identifier[T]
identifier[B] = identifier[A] [ identifier[np] . identifier[lexsort] ( identifier[A] . identifier[T] [::- literal[int] ])]
keyword[return] identifier[B] [ identifier[np] . identifier[concatenate] (([ keyword[True] ], identifier[np] . identifier[any] ( identifier[B] [ literal[int] :]!= identifier[B] [:- literal[int] ], identifier[axis] = literal[int] )))] | def mask_roi_unique(self):
"""
Assemble a set of unique magnitude tuples for the ROI
"""
# There is no good inherent way in numpy to do this...
# http://stackoverflow.com/q/16970982/
# Also possible and simple:
#return np.unique(zip(self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse))
A = np.vstack([self.mask_1.mask_roi_sparse, self.mask_2.mask_roi_sparse]).T
B = A[np.lexsort(A.T[::-1])]
return B[np.concatenate(([True], np.any(B[1:] != B[:-1], axis=1)))] |
def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)):
"""Compute cartesian coordinates of the pixels in instrument scan."""
if isinstance(orb, (list, tuple)):
tle1, tle2 = orb
orb = Orbital("mysatellite", line1=tle1, line2=tle2)
# get position and velocity for each time of each pixel
pos, vel = orb.get_position(times, normalize=False)
# now, get the vectors pointing to each pixel
vectors = sgeom.vectors(pos, vel, *rpy)
# compute intersection of lines (directed by vectors and passing through
# (0, 0, 0)) and ellipsoid. Derived from:
# http://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
# do the computation between line and ellipsoid (WGS 84)
# NB: AAPP uses GRS 80...
centre = -pos
a__ = 6378.137 # km
# b__ = 6356.75231414 # km, GRS80
b__ = 6356.752314245 # km, WGS84
radius = np.array([[1 / a__, 1 / a__, 1 / b__]]).T
shape = vectors.shape
xr_ = vectors.reshape([3, -1]) * radius
cr_ = centre.reshape([3, -1]) * radius
ldotc = np.einsum("ij,ij->j", xr_, cr_)
lsq = np.einsum("ij,ij->j", xr_, xr_)
csq = np.einsum("ij,ij->j", cr_, cr_)
d1_ = (ldotc - np.sqrt(ldotc ** 2 - csq * lsq + lsq)) / lsq
# return the actual pixel positions
return vectors * d1_.reshape(shape[1:]) - centre | def function[compute_pixels, parameter[orb, sgeom, times, rpy]]:
constant[Compute cartesian coordinates of the pixels in instrument scan.]
if call[name[isinstance], parameter[name[orb], tuple[[<ast.Name object at 0x7da20c993c70>, <ast.Name object at 0x7da20c992da0>]]]] begin[:]
<ast.Tuple object at 0x7da20c9930a0> assign[=] name[orb]
variable[orb] assign[=] call[name[Orbital], parameter[constant[mysatellite]]]
<ast.Tuple object at 0x7da20c9937f0> assign[=] call[name[orb].get_position, parameter[name[times]]]
variable[vectors] assign[=] call[name[sgeom].vectors, parameter[name[pos], name[vel], <ast.Starred object at 0x7da20c9921d0>]]
variable[centre] assign[=] <ast.UnaryOp object at 0x7da20c9909d0>
variable[a__] assign[=] constant[6378.137]
variable[b__] assign[=] constant[6356.752314245]
variable[radius] assign[=] call[name[np].array, parameter[list[[<ast.List object at 0x7da20c991600>]]]].T
variable[shape] assign[=] name[vectors].shape
variable[xr_] assign[=] binary_operation[call[name[vectors].reshape, parameter[list[[<ast.Constant object at 0x7da20c993190>, <ast.UnaryOp object at 0x7da20c9906d0>]]]] * name[radius]]
variable[cr_] assign[=] binary_operation[call[name[centre].reshape, parameter[list[[<ast.Constant object at 0x7da20c993af0>, <ast.UnaryOp object at 0x7da20c9910f0>]]]] * name[radius]]
variable[ldotc] assign[=] call[name[np].einsum, parameter[constant[ij,ij->j], name[xr_], name[cr_]]]
variable[lsq] assign[=] call[name[np].einsum, parameter[constant[ij,ij->j], name[xr_], name[xr_]]]
variable[csq] assign[=] call[name[np].einsum, parameter[constant[ij,ij->j], name[cr_], name[cr_]]]
variable[d1_] assign[=] binary_operation[binary_operation[name[ldotc] - call[name[np].sqrt, parameter[binary_operation[binary_operation[binary_operation[name[ldotc] ** constant[2]] - binary_operation[name[csq] * name[lsq]]] + name[lsq]]]]] / name[lsq]]
return[binary_operation[binary_operation[name[vectors] * call[name[d1_].reshape, parameter[call[name[shape]][<ast.Slice object at 0x7da20c990a60>]]]] - name[centre]]] | keyword[def] identifier[compute_pixels] ( identifier[orb] , identifier[sgeom] , identifier[times] , identifier[rpy] =( literal[int] , literal[int] , literal[int] )):
literal[string]
keyword[if] identifier[isinstance] ( identifier[orb] ,( identifier[list] , identifier[tuple] )):
identifier[tle1] , identifier[tle2] = identifier[orb]
identifier[orb] = identifier[Orbital] ( literal[string] , identifier[line1] = identifier[tle1] , identifier[line2] = identifier[tle2] )
identifier[pos] , identifier[vel] = identifier[orb] . identifier[get_position] ( identifier[times] , identifier[normalize] = keyword[False] )
identifier[vectors] = identifier[sgeom] . identifier[vectors] ( identifier[pos] , identifier[vel] ,* identifier[rpy] )
identifier[centre] =- identifier[pos]
identifier[a__] = literal[int]
identifier[b__] = literal[int]
identifier[radius] = identifier[np] . identifier[array] ([[ literal[int] / identifier[a__] , literal[int] / identifier[a__] , literal[int] / identifier[b__] ]]). identifier[T]
identifier[shape] = identifier[vectors] . identifier[shape]
identifier[xr_] = identifier[vectors] . identifier[reshape] ([ literal[int] ,- literal[int] ])* identifier[radius]
identifier[cr_] = identifier[centre] . identifier[reshape] ([ literal[int] ,- literal[int] ])* identifier[radius]
identifier[ldotc] = identifier[np] . identifier[einsum] ( literal[string] , identifier[xr_] , identifier[cr_] )
identifier[lsq] = identifier[np] . identifier[einsum] ( literal[string] , identifier[xr_] , identifier[xr_] )
identifier[csq] = identifier[np] . identifier[einsum] ( literal[string] , identifier[cr_] , identifier[cr_] )
identifier[d1_] =( identifier[ldotc] - identifier[np] . identifier[sqrt] ( identifier[ldotc] ** literal[int] - identifier[csq] * identifier[lsq] + identifier[lsq] ))/ identifier[lsq]
keyword[return] identifier[vectors] * identifier[d1_] . identifier[reshape] ( identifier[shape] [ literal[int] :])- identifier[centre] | def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)):
"""Compute cartesian coordinates of the pixels in instrument scan."""
if isinstance(orb, (list, tuple)):
(tle1, tle2) = orb
orb = Orbital('mysatellite', line1=tle1, line2=tle2) # depends on [control=['if'], data=[]]
# get position and velocity for each time of each pixel
(pos, vel) = orb.get_position(times, normalize=False)
# now, get the vectors pointing to each pixel
vectors = sgeom.vectors(pos, vel, *rpy)
# compute intersection of lines (directed by vectors and passing through
# (0, 0, 0)) and ellipsoid. Derived from:
# http://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
# do the computation between line and ellipsoid (WGS 84)
# NB: AAPP uses GRS 80...
centre = -pos
a__ = 6378.137 # km
# b__ = 6356.75231414 # km, GRS80
b__ = 6356.752314245 # km, WGS84
radius = np.array([[1 / a__, 1 / a__, 1 / b__]]).T
shape = vectors.shape
xr_ = vectors.reshape([3, -1]) * radius
cr_ = centre.reshape([3, -1]) * radius
ldotc = np.einsum('ij,ij->j', xr_, cr_)
lsq = np.einsum('ij,ij->j', xr_, xr_)
csq = np.einsum('ij,ij->j', cr_, cr_)
d1_ = (ldotc - np.sqrt(ldotc ** 2 - csq * lsq + lsq)) / lsq
# return the actual pixel positions
return vectors * d1_.reshape(shape[1:]) - centre |
def make_dict(cls, table):
"""Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file
"""
ret_dict = {}
for row in table:
file_handle = cls.create_from_row(row)
ret_dict[file_handle.key] = file_handle
return ret_dict | def function[make_dict, parameter[cls, table]]:
constant[Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file
]
variable[ret_dict] assign[=] dictionary[[], []]
for taget[name[row]] in starred[name[table]] begin[:]
variable[file_handle] assign[=] call[name[cls].create_from_row, parameter[name[row]]]
call[name[ret_dict]][name[file_handle].key] assign[=] name[file_handle]
return[name[ret_dict]] | keyword[def] identifier[make_dict] ( identifier[cls] , identifier[table] ):
literal[string]
identifier[ret_dict] ={}
keyword[for] identifier[row] keyword[in] identifier[table] :
identifier[file_handle] = identifier[cls] . identifier[create_from_row] ( identifier[row] )
identifier[ret_dict] [ identifier[file_handle] . identifier[key] ]= identifier[file_handle]
keyword[return] identifier[ret_dict] | def make_dict(cls, table):
"""Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file
"""
ret_dict = {}
for row in table:
file_handle = cls.create_from_row(row) # depends on [control=['for'], data=['row']]
ret_dict[file_handle.key] = file_handle
return ret_dict |
def display_matrix(self, matrix, interval=2.0, brightness=1.0, fading=False, ignore_duplicates=False):
"""
Displays an LED matrix on Nuimo's LED matrix display.
:param matrix: the matrix to display
:param interval: interval in seconds until the matrix disappears again
:param brightness: led brightness between 0..1
:param fading: if True, the previous matrix fades into the new matrix
:param ignore_duplicates: if True, the matrix is not sent again if already being displayed
"""
self._matrix_writer.write(
matrix=matrix,
interval=interval,
brightness=brightness,
fading=fading,
ignore_duplicates=ignore_duplicates
) | def function[display_matrix, parameter[self, matrix, interval, brightness, fading, ignore_duplicates]]:
constant[
Displays an LED matrix on Nuimo's LED matrix display.
:param matrix: the matrix to display
:param interval: interval in seconds until the matrix disappears again
:param brightness: led brightness between 0..1
:param fading: if True, the previous matrix fades into the new matrix
:param ignore_duplicates: if True, the matrix is not sent again if already being displayed
]
call[name[self]._matrix_writer.write, parameter[]] | keyword[def] identifier[display_matrix] ( identifier[self] , identifier[matrix] , identifier[interval] = literal[int] , identifier[brightness] = literal[int] , identifier[fading] = keyword[False] , identifier[ignore_duplicates] = keyword[False] ):
literal[string]
identifier[self] . identifier[_matrix_writer] . identifier[write] (
identifier[matrix] = identifier[matrix] ,
identifier[interval] = identifier[interval] ,
identifier[brightness] = identifier[brightness] ,
identifier[fading] = identifier[fading] ,
identifier[ignore_duplicates] = identifier[ignore_duplicates]
) | def display_matrix(self, matrix, interval=2.0, brightness=1.0, fading=False, ignore_duplicates=False):
"""
Displays an LED matrix on Nuimo's LED matrix display.
:param matrix: the matrix to display
:param interval: interval in seconds until the matrix disappears again
:param brightness: led brightness between 0..1
:param fading: if True, the previous matrix fades into the new matrix
:param ignore_duplicates: if True, the matrix is not sent again if already being displayed
"""
self._matrix_writer.write(matrix=matrix, interval=interval, brightness=brightness, fading=fading, ignore_duplicates=ignore_duplicates) |
def update(self, sshkeyid, params=None):
''' /v1/sshkey/update
POST - account
Update an existing SSH Key. Note that this will only
update newly installed machines. The key will not be
updated on any existing machines.
Link: https://www.vultr.com/api/#sshkey_update
'''
params = update_params(params, {'SSHKEYID': sshkeyid})
return self.request('/v1/sshkey/update', params, 'POST') | def function[update, parameter[self, sshkeyid, params]]:
constant[ /v1/sshkey/update
POST - account
Update an existing SSH Key. Note that this will only
update newly installed machines. The key will not be
updated on any existing machines.
Link: https://www.vultr.com/api/#sshkey_update
]
variable[params] assign[=] call[name[update_params], parameter[name[params], dictionary[[<ast.Constant object at 0x7da1b13909d0>], [<ast.Name object at 0x7da1b13925f0>]]]]
return[call[name[self].request, parameter[constant[/v1/sshkey/update], name[params], constant[POST]]]] | keyword[def] identifier[update] ( identifier[self] , identifier[sshkeyid] , identifier[params] = keyword[None] ):
literal[string]
identifier[params] = identifier[update_params] ( identifier[params] ,{ literal[string] : identifier[sshkeyid] })
keyword[return] identifier[self] . identifier[request] ( literal[string] , identifier[params] , literal[string] ) | def update(self, sshkeyid, params=None):
""" /v1/sshkey/update
POST - account
Update an existing SSH Key. Note that this will only
update newly installed machines. The key will not be
updated on any existing machines.
Link: https://www.vultr.com/api/#sshkey_update
"""
params = update_params(params, {'SSHKEYID': sshkeyid})
return self.request('/v1/sshkey/update', params, 'POST') |
def wr_txt_nts(self, fout_txt, desc2nts, prtfmt=None):
"""Write grouped and sorted GO IDs to GOs."""
with open(fout_txt, 'w') as prt:
summary_dct = self._prt_txt_desc2nts(prt, desc2nts, prtfmt)
if summary_dct:
print(self.sortobj.grprobj.fmtsum.format(
ACTION="WROTE:", FILE=fout_txt, **summary_dct))
else:
print(" WROTE: {TXT}".format(TXT=fout_txt)) | def function[wr_txt_nts, parameter[self, fout_txt, desc2nts, prtfmt]]:
constant[Write grouped and sorted GO IDs to GOs.]
with call[name[open], parameter[name[fout_txt], constant[w]]] begin[:]
variable[summary_dct] assign[=] call[name[self]._prt_txt_desc2nts, parameter[name[prt], name[desc2nts], name[prtfmt]]]
if name[summary_dct] begin[:]
call[name[print], parameter[call[name[self].sortobj.grprobj.fmtsum.format, parameter[]]]] | keyword[def] identifier[wr_txt_nts] ( identifier[self] , identifier[fout_txt] , identifier[desc2nts] , identifier[prtfmt] = keyword[None] ):
literal[string]
keyword[with] identifier[open] ( identifier[fout_txt] , literal[string] ) keyword[as] identifier[prt] :
identifier[summary_dct] = identifier[self] . identifier[_prt_txt_desc2nts] ( identifier[prt] , identifier[desc2nts] , identifier[prtfmt] )
keyword[if] identifier[summary_dct] :
identifier[print] ( identifier[self] . identifier[sortobj] . identifier[grprobj] . identifier[fmtsum] . identifier[format] (
identifier[ACTION] = literal[string] , identifier[FILE] = identifier[fout_txt] ,** identifier[summary_dct] ))
keyword[else] :
identifier[print] ( literal[string] . identifier[format] ( identifier[TXT] = identifier[fout_txt] )) | def wr_txt_nts(self, fout_txt, desc2nts, prtfmt=None):
"""Write grouped and sorted GO IDs to GOs."""
with open(fout_txt, 'w') as prt:
summary_dct = self._prt_txt_desc2nts(prt, desc2nts, prtfmt)
if summary_dct:
print(self.sortobj.grprobj.fmtsum.format(ACTION='WROTE:', FILE=fout_txt, **summary_dct)) # depends on [control=['if'], data=[]]
else:
print(' WROTE: {TXT}'.format(TXT=fout_txt)) # depends on [control=['with'], data=['prt']] |
async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):
"""
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else dump_field
if isinstance(elem, x.VariantType) or elem_type.WRAPS_VALUE:
return {
elem.variant_elem: await field_archiver(None, getattr(elem, elem.variant_elem), elem.variant_elem_type)
}
else:
fdef = elem_type.find_fdef(elem_type.f_specs(), elem)
return {
fdef[0]: await field_archiver(None, elem, fdef[1])
} | <ast.AsyncFunctionDef object at 0x7da18fe91b70> | keyword[async] keyword[def] identifier[dump_variant] ( identifier[obj] , identifier[elem] , identifier[elem_type] = keyword[None] , identifier[params] = keyword[None] , identifier[field_archiver] = keyword[None] ):
literal[string]
identifier[field_archiver] = identifier[field_archiver] keyword[if] identifier[field_archiver] keyword[else] identifier[dump_field]
keyword[if] identifier[isinstance] ( identifier[elem] , identifier[x] . identifier[VariantType] ) keyword[or] identifier[elem_type] . identifier[WRAPS_VALUE] :
keyword[return] {
identifier[elem] . identifier[variant_elem] : keyword[await] identifier[field_archiver] ( keyword[None] , identifier[getattr] ( identifier[elem] , identifier[elem] . identifier[variant_elem] ), identifier[elem] . identifier[variant_elem_type] )
}
keyword[else] :
identifier[fdef] = identifier[elem_type] . identifier[find_fdef] ( identifier[elem_type] . identifier[f_specs] (), identifier[elem] )
keyword[return] {
identifier[fdef] [ literal[int] ]: keyword[await] identifier[field_archiver] ( keyword[None] , identifier[elem] , identifier[fdef] [ literal[int] ])
} | async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):
"""
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver else dump_field
if isinstance(elem, x.VariantType) or elem_type.WRAPS_VALUE:
return {elem.variant_elem: await field_archiver(None, getattr(elem, elem.variant_elem), elem.variant_elem_type)} # depends on [control=['if'], data=[]]
else:
fdef = elem_type.find_fdef(elem_type.f_specs(), elem)
return {fdef[0]: await field_archiver(None, elem, fdef[1])} |
def from_fits_with_pixel_scale(cls, file_path, hdu, pixel_scale, origin=(0.0, 0.0)):
"""
Loads the image from a .fits file.
Parameters
----------
file_path : str
The full path of the fits file.
hdu : int
The HDU number in the fits file containing the image image.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
"""
return cls(array_util.numpy_array_2d_from_fits(file_path, hdu), pixel_scale, origin) | def function[from_fits_with_pixel_scale, parameter[cls, file_path, hdu, pixel_scale, origin]]:
constant[
Loads the image from a .fits file.
Parameters
----------
file_path : str
The full path of the fits file.
hdu : int
The HDU number in the fits file containing the image image.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
]
return[call[name[cls], parameter[call[name[array_util].numpy_array_2d_from_fits, parameter[name[file_path], name[hdu]]], name[pixel_scale], name[origin]]]] | keyword[def] identifier[from_fits_with_pixel_scale] ( identifier[cls] , identifier[file_path] , identifier[hdu] , identifier[pixel_scale] , identifier[origin] =( literal[int] , literal[int] )):
literal[string]
keyword[return] identifier[cls] ( identifier[array_util] . identifier[numpy_array_2d_from_fits] ( identifier[file_path] , identifier[hdu] ), identifier[pixel_scale] , identifier[origin] ) | def from_fits_with_pixel_scale(cls, file_path, hdu, pixel_scale, origin=(0.0, 0.0)):
"""
Loads the image from a .fits file.
Parameters
----------
file_path : str
The full path of the fits file.
hdu : int
The HDU number in the fits file containing the image image.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
"""
return cls(array_util.numpy_array_2d_from_fits(file_path, hdu), pixel_scale, origin) |
def contents(self, maxlen=70):
"Print the current (unexported) contents of the archive"
lines = []
if len(self._files) == 0:
print("Empty %s" % self.__class__.__name__)
return
fnames = [self._truncate_name(maxlen=maxlen, *k) for k in self._files]
max_len = max([len(f) for f in fnames])
for name,v in zip(fnames, self._files.values()):
mime_type = v[1].get('mime_type', 'no mime type')
lines.append('%s : %s' % (name.ljust(max_len), mime_type))
print('\n'.join(lines)) | def function[contents, parameter[self, maxlen]]:
constant[Print the current (unexported) contents of the archive]
variable[lines] assign[=] list[[]]
if compare[call[name[len], parameter[name[self]._files]] equal[==] constant[0]] begin[:]
call[name[print], parameter[binary_operation[constant[Empty %s] <ast.Mod object at 0x7da2590d6920> name[self].__class__.__name__]]]
return[None]
variable[fnames] assign[=] <ast.ListComp object at 0x7da2046200d0>
variable[max_len] assign[=] call[name[max], parameter[<ast.ListComp object at 0x7da204620370>]]
for taget[tuple[[<ast.Name object at 0x7da1b1cae800>, <ast.Name object at 0x7da1b1caeef0>]]] in starred[call[name[zip], parameter[name[fnames], call[name[self]._files.values, parameter[]]]]] begin[:]
variable[mime_type] assign[=] call[call[name[v]][constant[1]].get, parameter[constant[mime_type], constant[no mime type]]]
call[name[lines].append, parameter[binary_operation[constant[%s : %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b2347e50>, <ast.Name object at 0x7da1b23472e0>]]]]]
call[name[print], parameter[call[constant[
].join, parameter[name[lines]]]]] | keyword[def] identifier[contents] ( identifier[self] , identifier[maxlen] = literal[int] ):
literal[string]
identifier[lines] =[]
keyword[if] identifier[len] ( identifier[self] . identifier[_files] )== literal[int] :
identifier[print] ( literal[string] % identifier[self] . identifier[__class__] . identifier[__name__] )
keyword[return]
identifier[fnames] =[ identifier[self] . identifier[_truncate_name] ( identifier[maxlen] = identifier[maxlen] ,* identifier[k] ) keyword[for] identifier[k] keyword[in] identifier[self] . identifier[_files] ]
identifier[max_len] = identifier[max] ([ identifier[len] ( identifier[f] ) keyword[for] identifier[f] keyword[in] identifier[fnames] ])
keyword[for] identifier[name] , identifier[v] keyword[in] identifier[zip] ( identifier[fnames] , identifier[self] . identifier[_files] . identifier[values] ()):
identifier[mime_type] = identifier[v] [ literal[int] ]. identifier[get] ( literal[string] , literal[string] )
identifier[lines] . identifier[append] ( literal[string] %( identifier[name] . identifier[ljust] ( identifier[max_len] ), identifier[mime_type] ))
identifier[print] ( literal[string] . identifier[join] ( identifier[lines] )) | def contents(self, maxlen=70):
"""Print the current (unexported) contents of the archive"""
lines = []
if len(self._files) == 0:
print('Empty %s' % self.__class__.__name__)
return # depends on [control=['if'], data=[]]
fnames = [self._truncate_name(*k, maxlen=maxlen) for k in self._files]
max_len = max([len(f) for f in fnames])
for (name, v) in zip(fnames, self._files.values()):
mime_type = v[1].get('mime_type', 'no mime type')
lines.append('%s : %s' % (name.ljust(max_len), mime_type)) # depends on [control=['for'], data=[]]
print('\n'.join(lines)) |
def get_activities_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Activities`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.learning.ActivityList) - list of related
activities
raise: NotFound - ``objective_bank_id`` is not found
raise: NullArgument - ``objective_bank_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bin
mgr = self._get_provider_manager('LEARNING', local=True)
lookup_session = mgr.get_activity_lookup_session_for_objective_bank(objective_bank_id, proxy=self._proxy)
lookup_session.use_isolated_objective_bank_view()
return lookup_session.get_activities() | def function[get_activities_by_objective_bank, parameter[self, objective_bank_id]]:
constant[Gets the list of ``Activities`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.learning.ActivityList) - list of related
activities
raise: NotFound - ``objective_bank_id`` is not found
raise: NullArgument - ``objective_bank_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
]
variable[mgr] assign[=] call[name[self]._get_provider_manager, parameter[constant[LEARNING]]]
variable[lookup_session] assign[=] call[name[mgr].get_activity_lookup_session_for_objective_bank, parameter[name[objective_bank_id]]]
call[name[lookup_session].use_isolated_objective_bank_view, parameter[]]
return[call[name[lookup_session].get_activities, parameter[]]] | keyword[def] identifier[get_activities_by_objective_bank] ( identifier[self] , identifier[objective_bank_id] ):
literal[string]
identifier[mgr] = identifier[self] . identifier[_get_provider_manager] ( literal[string] , identifier[local] = keyword[True] )
identifier[lookup_session] = identifier[mgr] . identifier[get_activity_lookup_session_for_objective_bank] ( identifier[objective_bank_id] , identifier[proxy] = identifier[self] . identifier[_proxy] )
identifier[lookup_session] . identifier[use_isolated_objective_bank_view] ()
keyword[return] identifier[lookup_session] . identifier[get_activities] () | def get_activities_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Activities`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.learning.ActivityList) - list of related
activities
raise: NotFound - ``objective_bank_id`` is not found
raise: NullArgument - ``objective_bank_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bin
mgr = self._get_provider_manager('LEARNING', local=True)
lookup_session = mgr.get_activity_lookup_session_for_objective_bank(objective_bank_id, proxy=self._proxy)
lookup_session.use_isolated_objective_bank_view()
return lookup_session.get_activities() |
def main():
"""
Executes the given command. Returns error_message if command is not valid.
Returns:
Output of the given command or error message if command is not valid.
"""
try:
command = sys.argv[1]
except IndexError:
return error_message()
try:
module = importlib.import_module('i18n.%s' % command)
module.main.args = sys.argv[2:]
except (ImportError, AttributeError):
return error_message()
return module.main() | def function[main, parameter[]]:
constant[
Executes the given command. Returns error_message if command is not valid.
Returns:
Output of the given command or error message if command is not valid.
]
<ast.Try object at 0x7da18c4cd780>
<ast.Try object at 0x7da18c4ce680>
return[call[name[module].main, parameter[]]] | keyword[def] identifier[main] ():
literal[string]
keyword[try] :
identifier[command] = identifier[sys] . identifier[argv] [ literal[int] ]
keyword[except] identifier[IndexError] :
keyword[return] identifier[error_message] ()
keyword[try] :
identifier[module] = identifier[importlib] . identifier[import_module] ( literal[string] % identifier[command] )
identifier[module] . identifier[main] . identifier[args] = identifier[sys] . identifier[argv] [ literal[int] :]
keyword[except] ( identifier[ImportError] , identifier[AttributeError] ):
keyword[return] identifier[error_message] ()
keyword[return] identifier[module] . identifier[main] () | def main():
"""
Executes the given command. Returns error_message if command is not valid.
Returns:
Output of the given command or error message if command is not valid.
"""
try:
command = sys.argv[1] # depends on [control=['try'], data=[]]
except IndexError:
return error_message() # depends on [control=['except'], data=[]]
try:
module = importlib.import_module('i18n.%s' % command)
module.main.args = sys.argv[2:] # depends on [control=['try'], data=[]]
except (ImportError, AttributeError):
return error_message() # depends on [control=['except'], data=[]]
return module.main() |
def select_remote_checkpoint_ids(db, user_id):
"""
Get all file ids for a user.
"""
return list(
db.execute(
select([remote_checkpoints.c.id])
.where(remote_checkpoints.c.user_id == user_id)
)
) | def function[select_remote_checkpoint_ids, parameter[db, user_id]]:
constant[
Get all file ids for a user.
]
return[call[name[list], parameter[call[name[db].execute, parameter[call[call[name[select], parameter[list[[<ast.Attribute object at 0x7da18f721f90>]]]].where, parameter[compare[name[remote_checkpoints].c.user_id equal[==] name[user_id]]]]]]]]] | keyword[def] identifier[select_remote_checkpoint_ids] ( identifier[db] , identifier[user_id] ):
literal[string]
keyword[return] identifier[list] (
identifier[db] . identifier[execute] (
identifier[select] ([ identifier[remote_checkpoints] . identifier[c] . identifier[id] ])
. identifier[where] ( identifier[remote_checkpoints] . identifier[c] . identifier[user_id] == identifier[user_id] )
)
) | def select_remote_checkpoint_ids(db, user_id):
"""
Get all file ids for a user.
"""
return list(db.execute(select([remote_checkpoints.c.id]).where(remote_checkpoints.c.user_id == user_id))) |
def get_single_item(d):
"""Get an item from a dict which contains just one item."""
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)
return next(six.iteritems(d)) | def function[get_single_item, parameter[d]]:
constant[Get an item from a dict which contains just one item.]
assert[compare[call[name[len], parameter[name[d]]] equal[==] constant[1]]]
return[call[name[next], parameter[call[name[six].iteritems, parameter[name[d]]]]]] | keyword[def] identifier[get_single_item] ( identifier[d] ):
literal[string]
keyword[assert] identifier[len] ( identifier[d] )== literal[int] , literal[string] % identifier[len] ( identifier[d] )
keyword[return] identifier[next] ( identifier[six] . identifier[iteritems] ( identifier[d] )) | def get_single_item(d):
"""Get an item from a dict which contains just one item."""
assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d)
return next(six.iteritems(d)) |
def get_parsed_context(context_arg):
"""Parse input context string and returns context as dictionary."""
assert context_arg, ("pipeline must be invoked with context arg set. For "
"this json parser you're looking for something "
"like: "
"pypyr pipelinename './myjsonfile.json'")
logger.debug("starting")
# open the json file on disk so that you can initialize the dictionary
logger.debug(f"attempting to open file: {context_arg}")
with open(context_arg) as json_file:
payload = json.load(json_file)
logger.debug(f"json file loaded into context. Count: {len(payload)}")
logger.debug("done")
return payload | def function[get_parsed_context, parameter[context_arg]]:
constant[Parse input context string and returns context as dictionary.]
assert[name[context_arg]]
call[name[logger].debug, parameter[constant[starting]]]
call[name[logger].debug, parameter[<ast.JoinedStr object at 0x7da18f09dcf0>]]
with call[name[open], parameter[name[context_arg]]] begin[:]
variable[payload] assign[=] call[name[json].load, parameter[name[json_file]]]
call[name[logger].debug, parameter[<ast.JoinedStr object at 0x7da18f09e3b0>]]
call[name[logger].debug, parameter[constant[done]]]
return[name[payload]] | keyword[def] identifier[get_parsed_context] ( identifier[context_arg] ):
literal[string]
keyword[assert] identifier[context_arg] ,( literal[string]
literal[string]
literal[string]
literal[string] )
identifier[logger] . identifier[debug] ( literal[string] )
identifier[logger] . identifier[debug] ( literal[string] )
keyword[with] identifier[open] ( identifier[context_arg] ) keyword[as] identifier[json_file] :
identifier[payload] = identifier[json] . identifier[load] ( identifier[json_file] )
identifier[logger] . identifier[debug] ( literal[string] )
identifier[logger] . identifier[debug] ( literal[string] )
keyword[return] identifier[payload] | def get_parsed_context(context_arg):
"""Parse input context string and returns context as dictionary."""
assert context_arg, "pipeline must be invoked with context arg set. For this json parser you're looking for something like: pypyr pipelinename './myjsonfile.json'"
logger.debug('starting')
# open the json file on disk so that you can initialize the dictionary
logger.debug(f'attempting to open file: {context_arg}')
with open(context_arg) as json_file:
payload = json.load(json_file) # depends on [control=['with'], data=['json_file']]
logger.debug(f'json file loaded into context. Count: {len(payload)}')
logger.debug('done')
return payload |
def sign(ctx, file, account):
""" Sign a message with an account
"""
if not file:
print_message("Prompting for message. Terminate with CTRL-D", "info")
file = click.get_text_stream("stdin")
m = Message(file.read(), bitshares_instance=ctx.bitshares)
print_message(m.sign(account), "info") | def function[sign, parameter[ctx, file, account]]:
constant[ Sign a message with an account
]
if <ast.UnaryOp object at 0x7da20c76c3a0> begin[:]
call[name[print_message], parameter[constant[Prompting for message. Terminate with CTRL-D], constant[info]]]
variable[file] assign[=] call[name[click].get_text_stream, parameter[constant[stdin]]]
variable[m] assign[=] call[name[Message], parameter[call[name[file].read, parameter[]]]]
call[name[print_message], parameter[call[name[m].sign, parameter[name[account]]], constant[info]]] | keyword[def] identifier[sign] ( identifier[ctx] , identifier[file] , identifier[account] ):
literal[string]
keyword[if] keyword[not] identifier[file] :
identifier[print_message] ( literal[string] , literal[string] )
identifier[file] = identifier[click] . identifier[get_text_stream] ( literal[string] )
identifier[m] = identifier[Message] ( identifier[file] . identifier[read] (), identifier[bitshares_instance] = identifier[ctx] . identifier[bitshares] )
identifier[print_message] ( identifier[m] . identifier[sign] ( identifier[account] ), literal[string] ) | def sign(ctx, file, account):
""" Sign a message with an account
"""
if not file:
print_message('Prompting for message. Terminate with CTRL-D', 'info')
file = click.get_text_stream('stdin') # depends on [control=['if'], data=[]]
m = Message(file.read(), bitshares_instance=ctx.bitshares)
print_message(m.sign(account), 'info') |
def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoiding
both horizontal and vertical traversing as much as possible.
The way `sedes` is applied depends on the decoded object: If it is a string
`sedes` deserializes it as a whole; if it is a list, each element is
deserialized individually. In both cases, `sedes_kwargs` are passed on.
Note that, if a deserializer is used, only "horizontal" but not
"vertical lazyness" can be preserved.
:param rlp: the RLP string to decode
:param sedes: an object implementing a method ``deserialize(code)`` which
is used as described above, or ``None`` if no
deserialization should be performed
:param \*\*sedes_kwargs: additional keyword arguments that will be passed
to the deserializers
:returns: either the already decoded and deserialized object (if encoded as
a string) or an instance of :class:`rlp.LazyList`
"""
item, end = consume_item_lazy(rlp, 0)
if end != len(rlp):
raise DecodingError('RLP length prefix announced wrong length', rlp)
if isinstance(item, LazyList):
item.sedes = sedes
item.sedes_kwargs = sedes_kwargs
return item
elif sedes:
return sedes.deserialize(item, **sedes_kwargs)
else:
return item | def function[decode_lazy, parameter[rlp, sedes]]:
constant[Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoiding
both horizontal and vertical traversing as much as possible.
The way `sedes` is applied depends on the decoded object: If it is a string
`sedes` deserializes it as a whole; if it is a list, each element is
deserialized individually. In both cases, `sedes_kwargs` are passed on.
Note that, if a deserializer is used, only "horizontal" but not
"vertical lazyness" can be preserved.
:param rlp: the RLP string to decode
:param sedes: an object implementing a method ``deserialize(code)`` which
is used as described above, or ``None`` if no
deserialization should be performed
:param \*\*sedes_kwargs: additional keyword arguments that will be passed
to the deserializers
:returns: either the already decoded and deserialized object (if encoded as
a string) or an instance of :class:`rlp.LazyList`
]
<ast.Tuple object at 0x7da18f00c370> assign[=] call[name[consume_item_lazy], parameter[name[rlp], constant[0]]]
if compare[name[end] not_equal[!=] call[name[len], parameter[name[rlp]]]] begin[:]
<ast.Raise object at 0x7da18f58ebc0>
if call[name[isinstance], parameter[name[item], name[LazyList]]] begin[:]
name[item].sedes assign[=] name[sedes]
name[item].sedes_kwargs assign[=] name[sedes_kwargs]
return[name[item]] | keyword[def] identifier[decode_lazy] ( identifier[rlp] , identifier[sedes] = keyword[None] ,** identifier[sedes_kwargs] ):
literal[string]
identifier[item] , identifier[end] = identifier[consume_item_lazy] ( identifier[rlp] , literal[int] )
keyword[if] identifier[end] != identifier[len] ( identifier[rlp] ):
keyword[raise] identifier[DecodingError] ( literal[string] , identifier[rlp] )
keyword[if] identifier[isinstance] ( identifier[item] , identifier[LazyList] ):
identifier[item] . identifier[sedes] = identifier[sedes]
identifier[item] . identifier[sedes_kwargs] = identifier[sedes_kwargs]
keyword[return] identifier[item]
keyword[elif] identifier[sedes] :
keyword[return] identifier[sedes] . identifier[deserialize] ( identifier[item] ,** identifier[sedes_kwargs] )
keyword[else] :
keyword[return] identifier[item] | def decode_lazy(rlp, sedes=None, **sedes_kwargs):
"""Decode an RLP encoded object in a lazy fashion.
If the encoded object is a bytestring, this function acts similar to
:func:`rlp.decode`. If it is a list however, a :class:`LazyList` is
returned instead. This object will decode the string lazily, avoiding
both horizontal and vertical traversing as much as possible.
The way `sedes` is applied depends on the decoded object: If it is a string
`sedes` deserializes it as a whole; if it is a list, each element is
deserialized individually. In both cases, `sedes_kwargs` are passed on.
Note that, if a deserializer is used, only "horizontal" but not
"vertical lazyness" can be preserved.
:param rlp: the RLP string to decode
:param sedes: an object implementing a method ``deserialize(code)`` which
is used as described above, or ``None`` if no
deserialization should be performed
:param \\*\\*sedes_kwargs: additional keyword arguments that will be passed
to the deserializers
:returns: either the already decoded and deserialized object (if encoded as
a string) or an instance of :class:`rlp.LazyList`
"""
(item, end) = consume_item_lazy(rlp, 0)
if end != len(rlp):
raise DecodingError('RLP length prefix announced wrong length', rlp) # depends on [control=['if'], data=[]]
if isinstance(item, LazyList):
item.sedes = sedes
item.sedes_kwargs = sedes_kwargs
return item # depends on [control=['if'], data=[]]
elif sedes:
return sedes.deserialize(item, **sedes_kwargs) # depends on [control=['if'], data=[]]
else:
return item |
def device_id_from_name(device_name, nodes):
"""
Get the device ID when given a device name
:param str device_name: device name
:param list nodes: list of nodes from :py:meth:`generate_nodes`
:return: device ID
:rtype: int
"""
device_id = None
for node in nodes:
if device_name == node['properties']['name']:
device_id = node['id']
break
return device_id | def function[device_id_from_name, parameter[device_name, nodes]]:
constant[
Get the device ID when given a device name
:param str device_name: device name
:param list nodes: list of nodes from :py:meth:`generate_nodes`
:return: device ID
:rtype: int
]
variable[device_id] assign[=] constant[None]
for taget[name[node]] in starred[name[nodes]] begin[:]
if compare[name[device_name] equal[==] call[call[name[node]][constant[properties]]][constant[name]]] begin[:]
variable[device_id] assign[=] call[name[node]][constant[id]]
break
return[name[device_id]] | keyword[def] identifier[device_id_from_name] ( identifier[device_name] , identifier[nodes] ):
literal[string]
identifier[device_id] = keyword[None]
keyword[for] identifier[node] keyword[in] identifier[nodes] :
keyword[if] identifier[device_name] == identifier[node] [ literal[string] ][ literal[string] ]:
identifier[device_id] = identifier[node] [ literal[string] ]
keyword[break]
keyword[return] identifier[device_id] | def device_id_from_name(device_name, nodes):
"""
Get the device ID when given a device name
:param str device_name: device name
:param list nodes: list of nodes from :py:meth:`generate_nodes`
:return: device ID
:rtype: int
"""
device_id = None
for node in nodes:
if device_name == node['properties']['name']:
device_id = node['id']
break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['node']]
return device_id |
def iter_labels(self, ontology, size=None, sleep=None):
"""Iterates over the labels of terms in the ontology. Automatically wraps the pager returned by the OLS.
:param str ontology: The name of the ontology
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to sleep between pages. Defaults to 0 seconds.
:rtype: iter[str]
"""
for label in _help_iterate_labels(self.iter_terms(ontology=ontology, size=size, sleep=sleep)):
yield label | def function[iter_labels, parameter[self, ontology, size, sleep]]:
constant[Iterates over the labels of terms in the ontology. Automatically wraps the pager returned by the OLS.
:param str ontology: The name of the ontology
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to sleep between pages. Defaults to 0 seconds.
:rtype: iter[str]
]
for taget[name[label]] in starred[call[name[_help_iterate_labels], parameter[call[name[self].iter_terms, parameter[]]]]] begin[:]
<ast.Yield object at 0x7da18f722620> | keyword[def] identifier[iter_labels] ( identifier[self] , identifier[ontology] , identifier[size] = keyword[None] , identifier[sleep] = keyword[None] ):
literal[string]
keyword[for] identifier[label] keyword[in] identifier[_help_iterate_labels] ( identifier[self] . identifier[iter_terms] ( identifier[ontology] = identifier[ontology] , identifier[size] = identifier[size] , identifier[sleep] = identifier[sleep] )):
keyword[yield] identifier[label] | def iter_labels(self, ontology, size=None, sleep=None):
"""Iterates over the labels of terms in the ontology. Automatically wraps the pager returned by the OLS.
:param str ontology: The name of the ontology
:param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI.
:param int sleep: The amount of time to sleep between pages. Defaults to 0 seconds.
:rtype: iter[str]
"""
for label in _help_iterate_labels(self.iter_terms(ontology=ontology, size=size, sleep=sleep)):
yield label # depends on [control=['for'], data=['label']] |
def spd_inv(W, epsilon=1e-10, method='QR'):
"""
Compute matrix inverse of symmetric positive-definite matrix :math:`W`.
by first reducing W to a low-rank approximation that is truly spd
(Moore-Penrose inverse).
Parameters
----------
W : ndarray((m,m), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
Returns
-------
L : ndarray((n, r))
the Moore-Penrose inverse of the symmetric positive-definite matrix :math:`W`
"""
if (_np.shape(W)[0] == 1):
if W[0,0] < epsilon:
raise _ZeroRankError(
'All eigenvalues are smaller than %g, rank reduction would discard all dimensions.' % epsilon)
Winv = 1./W[0,0]
else:
sm, Vm = spd_eig(W, epsilon=epsilon, method=method)
Winv = _np.dot(Vm, _np.diag(1.0 / sm)).dot(Vm.T)
# return split
return Winv | def function[spd_inv, parameter[W, epsilon, method]]:
constant[
Compute matrix inverse of symmetric positive-definite matrix :math:`W`.
by first reducing W to a low-rank approximation that is truly spd
(Moore-Penrose inverse).
Parameters
----------
W : ndarray((m,m), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
Returns
-------
L : ndarray((n, r))
the Moore-Penrose inverse of the symmetric positive-definite matrix :math:`W`
]
if compare[call[call[name[_np].shape, parameter[name[W]]]][constant[0]] equal[==] constant[1]] begin[:]
if compare[call[name[W]][tuple[[<ast.Constant object at 0x7da20c6e6b60>, <ast.Constant object at 0x7da20c6e77f0>]]] less[<] name[epsilon]] begin[:]
<ast.Raise object at 0x7da20c6e5360>
variable[Winv] assign[=] binary_operation[constant[1.0] / call[name[W]][tuple[[<ast.Constant object at 0x7da20c6e7fd0>, <ast.Constant object at 0x7da20c6e52d0>]]]]
return[name[Winv]] | keyword[def] identifier[spd_inv] ( identifier[W] , identifier[epsilon] = literal[int] , identifier[method] = literal[string] ):
literal[string]
keyword[if] ( identifier[_np] . identifier[shape] ( identifier[W] )[ literal[int] ]== literal[int] ):
keyword[if] identifier[W] [ literal[int] , literal[int] ]< identifier[epsilon] :
keyword[raise] identifier[_ZeroRankError] (
literal[string] % identifier[epsilon] )
identifier[Winv] = literal[int] / identifier[W] [ literal[int] , literal[int] ]
keyword[else] :
identifier[sm] , identifier[Vm] = identifier[spd_eig] ( identifier[W] , identifier[epsilon] = identifier[epsilon] , identifier[method] = identifier[method] )
identifier[Winv] = identifier[_np] . identifier[dot] ( identifier[Vm] , identifier[_np] . identifier[diag] ( literal[int] / identifier[sm] )). identifier[dot] ( identifier[Vm] . identifier[T] )
keyword[return] identifier[Winv] | def spd_inv(W, epsilon=1e-10, method='QR'):
"""
Compute matrix inverse of symmetric positive-definite matrix :math:`W`.
by first reducing W to a low-rank approximation that is truly spd
(Moore-Penrose inverse).
Parameters
----------
W : ndarray((m,m), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
Returns
-------
L : ndarray((n, r))
the Moore-Penrose inverse of the symmetric positive-definite matrix :math:`W`
"""
if _np.shape(W)[0] == 1:
if W[0, 0] < epsilon:
raise _ZeroRankError('All eigenvalues are smaller than %g, rank reduction would discard all dimensions.' % epsilon) # depends on [control=['if'], data=['epsilon']]
Winv = 1.0 / W[0, 0] # depends on [control=['if'], data=[]]
else:
(sm, Vm) = spd_eig(W, epsilon=epsilon, method=method)
Winv = _np.dot(Vm, _np.diag(1.0 / sm)).dot(Vm.T)
# return split
return Winv |
def property2parameter(
self,
prop,
name="body",
required=False,
multiple=False,
location=None,
default_in="body",
):
"""Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
"""
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {"in": openapi_location, "name": name}
if openapi_location == "body":
ret["required"] = False
ret["name"] = "body"
ret["schema"] = {
"type": "object",
"properties": {name: prop} if name else {},
}
if name and required:
ret["schema"]["required"] = [name]
else:
ret["required"] = required
if self.openapi_version.major < 3:
if multiple:
ret["collectionFormat"] = "multi"
ret.update(prop)
else:
if multiple:
ret["explode"] = True
ret["style"] = "form"
if prop.get("description", None):
ret["description"] = prop.pop("description")
ret["schema"] = prop
return ret | def function[property2parameter, parameter[self, prop, name, required, multiple, location, default_in]]:
constant[Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
]
variable[openapi_default_in] assign[=] call[name[__location_map__].get, parameter[name[default_in], name[default_in]]]
variable[openapi_location] assign[=] call[name[__location_map__].get, parameter[name[location], name[openapi_default_in]]]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da1b18e5e10>, <ast.Constant object at 0x7da1b18e7370>], [<ast.Name object at 0x7da1b18e6800>, <ast.Name object at 0x7da1b18e4850>]]
if compare[name[openapi_location] equal[==] constant[body]] begin[:]
call[name[ret]][constant[required]] assign[=] constant[False]
call[name[ret]][constant[name]] assign[=] constant[body]
call[name[ret]][constant[schema]] assign[=] dictionary[[<ast.Constant object at 0x7da1b18e70d0>, <ast.Constant object at 0x7da1b18e6020>], [<ast.Constant object at 0x7da1b18e6740>, <ast.IfExp object at 0x7da1b18e6260>]]
if <ast.BoolOp object at 0x7da1b18e7df0> begin[:]
call[call[name[ret]][constant[schema]]][constant[required]] assign[=] list[[<ast.Name object at 0x7da1b18e5db0>]]
return[name[ret]] | keyword[def] identifier[property2parameter] (
identifier[self] ,
identifier[prop] ,
identifier[name] = literal[string] ,
identifier[required] = keyword[False] ,
identifier[multiple] = keyword[False] ,
identifier[location] = keyword[None] ,
identifier[default_in] = literal[string] ,
):
literal[string]
identifier[openapi_default_in] = identifier[__location_map__] . identifier[get] ( identifier[default_in] , identifier[default_in] )
identifier[openapi_location] = identifier[__location_map__] . identifier[get] ( identifier[location] , identifier[openapi_default_in] )
identifier[ret] ={ literal[string] : identifier[openapi_location] , literal[string] : identifier[name] }
keyword[if] identifier[openapi_location] == literal[string] :
identifier[ret] [ literal[string] ]= keyword[False]
identifier[ret] [ literal[string] ]= literal[string]
identifier[ret] [ literal[string] ]={
literal[string] : literal[string] ,
literal[string] :{ identifier[name] : identifier[prop] } keyword[if] identifier[name] keyword[else] {},
}
keyword[if] identifier[name] keyword[and] identifier[required] :
identifier[ret] [ literal[string] ][ literal[string] ]=[ identifier[name] ]
keyword[else] :
identifier[ret] [ literal[string] ]= identifier[required]
keyword[if] identifier[self] . identifier[openapi_version] . identifier[major] < literal[int] :
keyword[if] identifier[multiple] :
identifier[ret] [ literal[string] ]= literal[string]
identifier[ret] . identifier[update] ( identifier[prop] )
keyword[else] :
keyword[if] identifier[multiple] :
identifier[ret] [ literal[string] ]= keyword[True]
identifier[ret] [ literal[string] ]= literal[string]
keyword[if] identifier[prop] . identifier[get] ( literal[string] , keyword[None] ):
identifier[ret] [ literal[string] ]= identifier[prop] . identifier[pop] ( literal[string] )
identifier[ret] [ literal[string] ]= identifier[prop]
keyword[return] identifier[ret] | def property2parameter(self, prop, name='body', required=False, multiple=False, location=None, default_in='body'):
"""Return the Parameter Object definition for a JSON Schema property.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject
:param dict prop: JSON Schema property
:param str name: Field name
:param bool required: Parameter is required
:param bool multiple: Parameter is repeated
:param str location: Location to look for ``name``
:param str default_in: Default location to look for ``name``
:raise: TranslationError if arg object cannot be translated to a Parameter Object schema.
:rtype: dict, a Parameter Object
"""
openapi_default_in = __location_map__.get(default_in, default_in)
openapi_location = __location_map__.get(location, openapi_default_in)
ret = {'in': openapi_location, 'name': name}
if openapi_location == 'body':
ret['required'] = False
ret['name'] = 'body'
ret['schema'] = {'type': 'object', 'properties': {name: prop} if name else {}}
if name and required:
ret['schema']['required'] = [name] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
else:
ret['required'] = required
if self.openapi_version.major < 3:
if multiple:
ret['collectionFormat'] = 'multi' # depends on [control=['if'], data=[]]
ret.update(prop) # depends on [control=['if'], data=[]]
else:
if multiple:
ret['explode'] = True
ret['style'] = 'form' # depends on [control=['if'], data=[]]
if prop.get('description', None):
ret['description'] = prop.pop('description') # depends on [control=['if'], data=[]]
ret['schema'] = prop
return ret |
def _setupAutoDeployment(self, userScript=None):
"""
Determine the user script, save it to the job store and inject a reference to the saved
copy into the batch system such that it can auto-deploy the resource on the worker
nodes.
:param toil.resource.ModuleDescriptor userScript: the module descriptor referencing the
user script. If None, it will be looked up in the job store.
"""
if userScript is not None:
# This branch is hit when a workflow is being started
if userScript.belongsToToil:
logger.debug('User script %s belongs to Toil. No need to auto-deploy it.', userScript)
userScript = None
else:
if (self._batchSystem.supportsAutoDeployment() and
not self.config.disableAutoDeployment):
# Note that by saving the ModuleDescriptor, and not the Resource we allow for
# redeploying a potentially modified user script on workflow restarts.
with self._jobStore.writeSharedFileStream('userScript') as f:
pickle.dump(userScript, f, protocol=pickle.HIGHEST_PROTOCOL)
else:
from toil.batchSystems.singleMachine import SingleMachineBatchSystem
if not isinstance(self._batchSystem, SingleMachineBatchSystem):
logger.warn('Batch system does not support auto-deployment. The user '
'script %s will have to be present at the same location on '
'every worker.', userScript)
userScript = None
else:
# This branch is hit on restarts
from toil.jobStores.abstractJobStore import NoSuchFileException
try:
with self._jobStore.readSharedFileStream('userScript') as f:
userScript = safeUnpickleFromStream(f)
except NoSuchFileException:
logger.debug('User script neither set explicitly nor present in the job store.')
userScript = None
if userScript is None:
logger.debug('No user script to auto-deploy.')
else:
logger.debug('Saving user script %s as a resource', userScript)
userScriptResource = userScript.saveAsResourceTo(self._jobStore)
logger.debug('Injecting user script %s into batch system.', userScriptResource)
self._batchSystem.setUserScript(userScriptResource) | def function[_setupAutoDeployment, parameter[self, userScript]]:
constant[
Determine the user script, save it to the job store and inject a reference to the saved
copy into the batch system such that it can auto-deploy the resource on the worker
nodes.
:param toil.resource.ModuleDescriptor userScript: the module descriptor referencing the
user script. If None, it will be looked up in the job store.
]
if compare[name[userScript] is_not constant[None]] begin[:]
if name[userScript].belongsToToil begin[:]
call[name[logger].debug, parameter[constant[User script %s belongs to Toil. No need to auto-deploy it.], name[userScript]]]
variable[userScript] assign[=] constant[None]
if compare[name[userScript] is constant[None]] begin[:]
call[name[logger].debug, parameter[constant[No user script to auto-deploy.]]] | keyword[def] identifier[_setupAutoDeployment] ( identifier[self] , identifier[userScript] = keyword[None] ):
literal[string]
keyword[if] identifier[userScript] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[userScript] . identifier[belongsToToil] :
identifier[logger] . identifier[debug] ( literal[string] , identifier[userScript] )
identifier[userScript] = keyword[None]
keyword[else] :
keyword[if] ( identifier[self] . identifier[_batchSystem] . identifier[supportsAutoDeployment] () keyword[and]
keyword[not] identifier[self] . identifier[config] . identifier[disableAutoDeployment] ):
keyword[with] identifier[self] . identifier[_jobStore] . identifier[writeSharedFileStream] ( literal[string] ) keyword[as] identifier[f] :
identifier[pickle] . identifier[dump] ( identifier[userScript] , identifier[f] , identifier[protocol] = identifier[pickle] . identifier[HIGHEST_PROTOCOL] )
keyword[else] :
keyword[from] identifier[toil] . identifier[batchSystems] . identifier[singleMachine] keyword[import] identifier[SingleMachineBatchSystem]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[_batchSystem] , identifier[SingleMachineBatchSystem] ):
identifier[logger] . identifier[warn] ( literal[string]
literal[string]
literal[string] , identifier[userScript] )
identifier[userScript] = keyword[None]
keyword[else] :
keyword[from] identifier[toil] . identifier[jobStores] . identifier[abstractJobStore] keyword[import] identifier[NoSuchFileException]
keyword[try] :
keyword[with] identifier[self] . identifier[_jobStore] . identifier[readSharedFileStream] ( literal[string] ) keyword[as] identifier[f] :
identifier[userScript] = identifier[safeUnpickleFromStream] ( identifier[f] )
keyword[except] identifier[NoSuchFileException] :
identifier[logger] . identifier[debug] ( literal[string] )
identifier[userScript] = keyword[None]
keyword[if] identifier[userScript] keyword[is] keyword[None] :
identifier[logger] . identifier[debug] ( literal[string] )
keyword[else] :
identifier[logger] . identifier[debug] ( literal[string] , identifier[userScript] )
identifier[userScriptResource] = identifier[userScript] . identifier[saveAsResourceTo] ( identifier[self] . identifier[_jobStore] )
identifier[logger] . identifier[debug] ( literal[string] , identifier[userScriptResource] )
identifier[self] . identifier[_batchSystem] . identifier[setUserScript] ( identifier[userScriptResource] ) | def _setupAutoDeployment(self, userScript=None):
"""
Determine the user script, save it to the job store and inject a reference to the saved
copy into the batch system such that it can auto-deploy the resource on the worker
nodes.
:param toil.resource.ModuleDescriptor userScript: the module descriptor referencing the
user script. If None, it will be looked up in the job store.
"""
if userScript is not None:
# This branch is hit when a workflow is being started
if userScript.belongsToToil:
logger.debug('User script %s belongs to Toil. No need to auto-deploy it.', userScript)
userScript = None # depends on [control=['if'], data=[]]
elif self._batchSystem.supportsAutoDeployment() and (not self.config.disableAutoDeployment):
# Note that by saving the ModuleDescriptor, and not the Resource we allow for
# redeploying a potentially modified user script on workflow restarts.
with self._jobStore.writeSharedFileStream('userScript') as f:
pickle.dump(userScript, f, protocol=pickle.HIGHEST_PROTOCOL) # depends on [control=['with'], data=['f']] # depends on [control=['if'], data=[]]
else:
from toil.batchSystems.singleMachine import SingleMachineBatchSystem
if not isinstance(self._batchSystem, SingleMachineBatchSystem):
logger.warn('Batch system does not support auto-deployment. The user script %s will have to be present at the same location on every worker.', userScript) # depends on [control=['if'], data=[]]
userScript = None # depends on [control=['if'], data=['userScript']]
else:
# This branch is hit on restarts
from toil.jobStores.abstractJobStore import NoSuchFileException
try:
with self._jobStore.readSharedFileStream('userScript') as f:
userScript = safeUnpickleFromStream(f) # depends on [control=['with'], data=['f']] # depends on [control=['try'], data=[]]
except NoSuchFileException:
logger.debug('User script neither set explicitly nor present in the job store.')
userScript = None # depends on [control=['except'], data=[]]
if userScript is None:
logger.debug('No user script to auto-deploy.') # depends on [control=['if'], data=[]]
else:
logger.debug('Saving user script %s as a resource', userScript)
userScriptResource = userScript.saveAsResourceTo(self._jobStore)
logger.debug('Injecting user script %s into batch system.', userScriptResource)
self._batchSystem.setUserScript(userScriptResource) |
def get_field(brain_or_object, name, default=None):
"""Return the named field
"""
fields = get_fields(brain_or_object)
return fields.get(name, default) | def function[get_field, parameter[brain_or_object, name, default]]:
constant[Return the named field
]
variable[fields] assign[=] call[name[get_fields], parameter[name[brain_or_object]]]
return[call[name[fields].get, parameter[name[name], name[default]]]] | keyword[def] identifier[get_field] ( identifier[brain_or_object] , identifier[name] , identifier[default] = keyword[None] ):
literal[string]
identifier[fields] = identifier[get_fields] ( identifier[brain_or_object] )
keyword[return] identifier[fields] . identifier[get] ( identifier[name] , identifier[default] ) | def get_field(brain_or_object, name, default=None):
"""Return the named field
"""
fields = get_fields(brain_or_object)
return fields.get(name, default) |
def _yield_abbreviations_for_parameter(param, kwargs):
"""Get an abbreviation for a function parameter."""
name = param.name
kind = param.kind
ann = param.annotation
default = param.default
not_found = (name, empty, empty)
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
if name in kwargs:
value = kwargs.pop(name)
elif ann is not empty:
warn("Using function annotations to implicitly specify interactive controls is deprecated. Use an explicit keyword argument for the parameter instead.", DeprecationWarning)
value = ann
elif default is not empty:
value = default
else:
yield not_found
yield (name, value, default)
elif kind == Parameter.VAR_KEYWORD:
# In this case name=kwargs and we yield the items in kwargs with their keys.
for k, v in kwargs.copy().items():
kwargs.pop(k)
yield k, v, empty | def function[_yield_abbreviations_for_parameter, parameter[param, kwargs]]:
constant[Get an abbreviation for a function parameter.]
variable[name] assign[=] name[param].name
variable[kind] assign[=] name[param].kind
variable[ann] assign[=] name[param].annotation
variable[default] assign[=] name[param].default
variable[not_found] assign[=] tuple[[<ast.Name object at 0x7da18f723a30>, <ast.Name object at 0x7da18f721f30>, <ast.Name object at 0x7da18f7227a0>]]
if compare[name[kind] in tuple[[<ast.Attribute object at 0x7da18f722770>, <ast.Attribute object at 0x7da18f723340>]]] begin[:]
if compare[name[name] in name[kwargs]] begin[:]
variable[value] assign[=] call[name[kwargs].pop, parameter[name[name]]]
<ast.Yield object at 0x7da18f722ef0> | keyword[def] identifier[_yield_abbreviations_for_parameter] ( identifier[param] , identifier[kwargs] ):
literal[string]
identifier[name] = identifier[param] . identifier[name]
identifier[kind] = identifier[param] . identifier[kind]
identifier[ann] = identifier[param] . identifier[annotation]
identifier[default] = identifier[param] . identifier[default]
identifier[not_found] =( identifier[name] , identifier[empty] , identifier[empty] )
keyword[if] identifier[kind] keyword[in] ( identifier[Parameter] . identifier[POSITIONAL_OR_KEYWORD] , identifier[Parameter] . identifier[KEYWORD_ONLY] ):
keyword[if] identifier[name] keyword[in] identifier[kwargs] :
identifier[value] = identifier[kwargs] . identifier[pop] ( identifier[name] )
keyword[elif] identifier[ann] keyword[is] keyword[not] identifier[empty] :
identifier[warn] ( literal[string] , identifier[DeprecationWarning] )
identifier[value] = identifier[ann]
keyword[elif] identifier[default] keyword[is] keyword[not] identifier[empty] :
identifier[value] = identifier[default]
keyword[else] :
keyword[yield] identifier[not_found]
keyword[yield] ( identifier[name] , identifier[value] , identifier[default] )
keyword[elif] identifier[kind] == identifier[Parameter] . identifier[VAR_KEYWORD] :
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[kwargs] . identifier[copy] (). identifier[items] ():
identifier[kwargs] . identifier[pop] ( identifier[k] )
keyword[yield] identifier[k] , identifier[v] , identifier[empty] | def _yield_abbreviations_for_parameter(param, kwargs):
"""Get an abbreviation for a function parameter."""
name = param.name
kind = param.kind
ann = param.annotation
default = param.default
not_found = (name, empty, empty)
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
if name in kwargs:
value = kwargs.pop(name) # depends on [control=['if'], data=['name', 'kwargs']]
elif ann is not empty:
warn('Using function annotations to implicitly specify interactive controls is deprecated. Use an explicit keyword argument for the parameter instead.', DeprecationWarning)
value = ann # depends on [control=['if'], data=['ann']]
elif default is not empty:
value = default # depends on [control=['if'], data=['default']]
else:
yield not_found
yield (name, value, default) # depends on [control=['if'], data=[]]
elif kind == Parameter.VAR_KEYWORD:
# In this case name=kwargs and we yield the items in kwargs with their keys.
for (k, v) in kwargs.copy().items():
kwargs.pop(k)
yield (k, v, empty) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]] |
def convert_spanstring(span_string):
"""
converts a span of tokens (str, e.g. 'word_88..word_91')
into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']
Note: Please don't use this function directly, use spanstring2tokens()
instead, which checks for non-existing tokens!
Examples
--------
>>> convert_spanstring('word_1')
['word_1']
>>> convert_spanstring('word_2,word_3')
['word_2', 'word_3']
>>> convert_spanstring('word_7..word_11')
['word_7', 'word_8', 'word_9', 'word_10', 'word_11']
>>> convert_spanstring('word_2,word_3,word_7..word_9')
['word_2', 'word_3', 'word_7', 'word_8', 'word_9']
>>> convert_spanstring('word_7..word_9,word_15,word_17..word_19')
['word_7', 'word_8', 'word_9', 'word_15', 'word_17', 'word_18', 'word_19']
"""
prefix_err = "All tokens must share the same prefix: {0} vs. {1}"
tokens = []
if not span_string:
return tokens
spans = span_string.split(',')
for span in spans:
span_elements = span.split('..')
if len(span_elements) == 1:
tokens.append(span_elements[0])
elif len(span_elements) == 2:
start, end = span_elements
start_prefix, start_id_str = start.split('_')
end_prefix, end_id_str = end.split('_')
assert start_prefix == end_prefix, prefix_err.format(
start_prefix, end_prefix)
tokens.extend("{0}_{1}".format(start_prefix, token_id)
for token_id in range(int(start_id_str),
int(end_id_str)+1))
else:
raise ValueError("Can't parse span '{}'".format(span_string))
first_prefix = tokens[0].split('_')[0]
for token in tokens:
token_parts = token.split('_')
assert len(token_parts) == 2, \
"All token IDs must use the format prefix + '_' + number"
assert token_parts[0] == first_prefix, prefix_err.format(
token_parts[0], first_prefix)
return tokens | def function[convert_spanstring, parameter[span_string]]:
constant[
converts a span of tokens (str, e.g. 'word_88..word_91')
into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']
Note: Please don't use this function directly, use spanstring2tokens()
instead, which checks for non-existing tokens!
Examples
--------
>>> convert_spanstring('word_1')
['word_1']
>>> convert_spanstring('word_2,word_3')
['word_2', 'word_3']
>>> convert_spanstring('word_7..word_11')
['word_7', 'word_8', 'word_9', 'word_10', 'word_11']
>>> convert_spanstring('word_2,word_3,word_7..word_9')
['word_2', 'word_3', 'word_7', 'word_8', 'word_9']
>>> convert_spanstring('word_7..word_9,word_15,word_17..word_19')
['word_7', 'word_8', 'word_9', 'word_15', 'word_17', 'word_18', 'word_19']
]
variable[prefix_err] assign[=] constant[All tokens must share the same prefix: {0} vs. {1}]
variable[tokens] assign[=] list[[]]
if <ast.UnaryOp object at 0x7da18bccb160> begin[:]
return[name[tokens]]
variable[spans] assign[=] call[name[span_string].split, parameter[constant[,]]]
for taget[name[span]] in starred[name[spans]] begin[:]
variable[span_elements] assign[=] call[name[span].split, parameter[constant[..]]]
if compare[call[name[len], parameter[name[span_elements]]] equal[==] constant[1]] begin[:]
call[name[tokens].append, parameter[call[name[span_elements]][constant[0]]]]
variable[first_prefix] assign[=] call[call[call[name[tokens]][constant[0]].split, parameter[constant[_]]]][constant[0]]
for taget[name[token]] in starred[name[tokens]] begin[:]
variable[token_parts] assign[=] call[name[token].split, parameter[constant[_]]]
assert[compare[call[name[len], parameter[name[token_parts]]] equal[==] constant[2]]]
assert[compare[call[name[token_parts]][constant[0]] equal[==] name[first_prefix]]]
return[name[tokens]] | keyword[def] identifier[convert_spanstring] ( identifier[span_string] ):
literal[string]
identifier[prefix_err] = literal[string]
identifier[tokens] =[]
keyword[if] keyword[not] identifier[span_string] :
keyword[return] identifier[tokens]
identifier[spans] = identifier[span_string] . identifier[split] ( literal[string] )
keyword[for] identifier[span] keyword[in] identifier[spans] :
identifier[span_elements] = identifier[span] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[span_elements] )== literal[int] :
identifier[tokens] . identifier[append] ( identifier[span_elements] [ literal[int] ])
keyword[elif] identifier[len] ( identifier[span_elements] )== literal[int] :
identifier[start] , identifier[end] = identifier[span_elements]
identifier[start_prefix] , identifier[start_id_str] = identifier[start] . identifier[split] ( literal[string] )
identifier[end_prefix] , identifier[end_id_str] = identifier[end] . identifier[split] ( literal[string] )
keyword[assert] identifier[start_prefix] == identifier[end_prefix] , identifier[prefix_err] . identifier[format] (
identifier[start_prefix] , identifier[end_prefix] )
identifier[tokens] . identifier[extend] ( literal[string] . identifier[format] ( identifier[start_prefix] , identifier[token_id] )
keyword[for] identifier[token_id] keyword[in] identifier[range] ( identifier[int] ( identifier[start_id_str] ),
identifier[int] ( identifier[end_id_str] )+ literal[int] ))
keyword[else] :
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[span_string] ))
identifier[first_prefix] = identifier[tokens] [ literal[int] ]. identifier[split] ( literal[string] )[ literal[int] ]
keyword[for] identifier[token] keyword[in] identifier[tokens] :
identifier[token_parts] = identifier[token] . identifier[split] ( literal[string] )
keyword[assert] identifier[len] ( identifier[token_parts] )== literal[int] , literal[string]
keyword[assert] identifier[token_parts] [ literal[int] ]== identifier[first_prefix] , identifier[prefix_err] . identifier[format] (
identifier[token_parts] [ literal[int] ], identifier[first_prefix] )
keyword[return] identifier[tokens] | def convert_spanstring(span_string):
"""
converts a span of tokens (str, e.g. 'word_88..word_91')
into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']
Note: Please don't use this function directly, use spanstring2tokens()
instead, which checks for non-existing tokens!
Examples
--------
>>> convert_spanstring('word_1')
['word_1']
>>> convert_spanstring('word_2,word_3')
['word_2', 'word_3']
>>> convert_spanstring('word_7..word_11')
['word_7', 'word_8', 'word_9', 'word_10', 'word_11']
>>> convert_spanstring('word_2,word_3,word_7..word_9')
['word_2', 'word_3', 'word_7', 'word_8', 'word_9']
>>> convert_spanstring('word_7..word_9,word_15,word_17..word_19')
['word_7', 'word_8', 'word_9', 'word_15', 'word_17', 'word_18', 'word_19']
"""
prefix_err = 'All tokens must share the same prefix: {0} vs. {1}'
tokens = []
if not span_string:
return tokens # depends on [control=['if'], data=[]]
spans = span_string.split(',')
for span in spans:
span_elements = span.split('..')
if len(span_elements) == 1:
tokens.append(span_elements[0]) # depends on [control=['if'], data=[]]
elif len(span_elements) == 2:
(start, end) = span_elements
(start_prefix, start_id_str) = start.split('_')
(end_prefix, end_id_str) = end.split('_')
assert start_prefix == end_prefix, prefix_err.format(start_prefix, end_prefix)
tokens.extend(('{0}_{1}'.format(start_prefix, token_id) for token_id in range(int(start_id_str), int(end_id_str) + 1))) # depends on [control=['if'], data=[]]
else:
raise ValueError("Can't parse span '{}'".format(span_string)) # depends on [control=['for'], data=['span']]
first_prefix = tokens[0].split('_')[0]
for token in tokens:
token_parts = token.split('_')
assert len(token_parts) == 2, "All token IDs must use the format prefix + '_' + number"
assert token_parts[0] == first_prefix, prefix_err.format(token_parts[0], first_prefix) # depends on [control=['for'], data=['token']]
return tokens |
def from_dict(cls, d):
""" Override default, adding the capture of content and contenttype.
"""
o = super(Signature, cls).from_dict(d)
if 'content' in d:
# Sometimes, several contents, (one txt, other html), take last
try:
o._content = d['content']['_content']
o._contenttype = d['content']['type']
except TypeError:
o._content = d['content'][-1]['_content']
o._contenttype = d['content'][-1]['type']
return o | def function[from_dict, parameter[cls, d]]:
constant[ Override default, adding the capture of content and contenttype.
]
variable[o] assign[=] call[call[name[super], parameter[name[Signature], name[cls]]].from_dict, parameter[name[d]]]
if compare[constant[content] in name[d]] begin[:]
<ast.Try object at 0x7da18bc72890>
return[name[o]] | keyword[def] identifier[from_dict] ( identifier[cls] , identifier[d] ):
literal[string]
identifier[o] = identifier[super] ( identifier[Signature] , identifier[cls] ). identifier[from_dict] ( identifier[d] )
keyword[if] literal[string] keyword[in] identifier[d] :
keyword[try] :
identifier[o] . identifier[_content] = identifier[d] [ literal[string] ][ literal[string] ]
identifier[o] . identifier[_contenttype] = identifier[d] [ literal[string] ][ literal[string] ]
keyword[except] identifier[TypeError] :
identifier[o] . identifier[_content] = identifier[d] [ literal[string] ][- literal[int] ][ literal[string] ]
identifier[o] . identifier[_contenttype] = identifier[d] [ literal[string] ][- literal[int] ][ literal[string] ]
keyword[return] identifier[o] | def from_dict(cls, d):
""" Override default, adding the capture of content and contenttype.
"""
o = super(Signature, cls).from_dict(d)
if 'content' in d:
# Sometimes, several contents, (one txt, other html), take last
try:
o._content = d['content']['_content']
o._contenttype = d['content']['type'] # depends on [control=['try'], data=[]]
except TypeError:
o._content = d['content'][-1]['_content']
o._contenttype = d['content'][-1]['type'] # depends on [control=['except'], data=[]] # depends on [control=['if'], data=['d']]
return o |
def redraw_layer(self,name):
"""
Redraws the given layer.
:raises ValueError: If there is no Layer with the given name.
"""
if name not in self._layers:
raise ValueError("Layer %s not part of widget, cannot redraw")
self._layers[name].on_redraw() | def function[redraw_layer, parameter[self, name]]:
constant[
Redraws the given layer.
:raises ValueError: If there is no Layer with the given name.
]
if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self]._layers] begin[:]
<ast.Raise object at 0x7da1b0193bb0>
call[call[name[self]._layers][name[name]].on_redraw, parameter[]] | keyword[def] identifier[redraw_layer] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_layers] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[self] . identifier[_layers] [ identifier[name] ]. identifier[on_redraw] () | def redraw_layer(self, name):
"""
Redraws the given layer.
:raises ValueError: If there is no Layer with the given name.
"""
if name not in self._layers:
raise ValueError('Layer %s not part of widget, cannot redraw') # depends on [control=['if'], data=[]]
self._layers[name].on_redraw() |
def _submit_request(self):
"""Submit a request to the ACS Zeropoint Calculator.
If an exception is raised during the request, an error message is
given. Otherwise, the response is saved in the corresponding
attribute.
"""
try:
self._response = urlopen(self._url)
except URLError as e:
msg = ('{}\n{}\nThe query failed! Please check your inputs. '
'If the error persists, submit a ticket to the '
'ACS Help Desk at hsthelp.stsci.edu with the error message '
'displayed above.'.format(str(e), self._msg_div))
LOG.error(msg)
self._failed = True
else:
self._failed = False | def function[_submit_request, parameter[self]]:
constant[Submit a request to the ACS Zeropoint Calculator.
If an exception is raised during the request, an error message is
given. Otherwise, the response is saved in the corresponding
attribute.
]
<ast.Try object at 0x7da204962920> | keyword[def] identifier[_submit_request] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[_response] = identifier[urlopen] ( identifier[self] . identifier[_url] )
keyword[except] identifier[URLError] keyword[as] identifier[e] :
identifier[msg] =( literal[string]
literal[string]
literal[string]
literal[string] . identifier[format] ( identifier[str] ( identifier[e] ), identifier[self] . identifier[_msg_div] ))
identifier[LOG] . identifier[error] ( identifier[msg] )
identifier[self] . identifier[_failed] = keyword[True]
keyword[else] :
identifier[self] . identifier[_failed] = keyword[False] | def _submit_request(self):
"""Submit a request to the ACS Zeropoint Calculator.
If an exception is raised during the request, an error message is
given. Otherwise, the response is saved in the corresponding
attribute.
"""
try:
self._response = urlopen(self._url) # depends on [control=['try'], data=[]]
except URLError as e:
msg = '{}\n{}\nThe query failed! Please check your inputs. If the error persists, submit a ticket to the ACS Help Desk at hsthelp.stsci.edu with the error message displayed above.'.format(str(e), self._msg_div)
LOG.error(msg)
self._failed = True # depends on [control=['except'], data=['e']]
else:
self._failed = False |
def resize(self, height, width, **kwargs):
"""
resize pty of an execed process
"""
self.client.exec_resize(self.exec_id, height=height, width=width) | def function[resize, parameter[self, height, width]]:
constant[
resize pty of an execed process
]
call[name[self].client.exec_resize, parameter[name[self].exec_id]] | keyword[def] identifier[resize] ( identifier[self] , identifier[height] , identifier[width] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[client] . identifier[exec_resize] ( identifier[self] . identifier[exec_id] , identifier[height] = identifier[height] , identifier[width] = identifier[width] ) | def resize(self, height, width, **kwargs):
"""
resize pty of an execed process
"""
self.client.exec_resize(self.exec_id, height=height, width=width) |
def _create_file_racefree(self, file):
"""
Creates a file, but fails if the file already exists.
This function will thus only succeed if this process actually creates
the file; if the file already exists, it will cause an OSError,
solving race conditions.
:param str file: File to create.
"""
write_lock_flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
os.open(file, write_lock_flags) | def function[_create_file_racefree, parameter[self, file]]:
constant[
Creates a file, but fails if the file already exists.
This function will thus only succeed if this process actually creates
the file; if the file already exists, it will cause an OSError,
solving race conditions.
:param str file: File to create.
]
variable[write_lock_flags] assign[=] binary_operation[binary_operation[name[os].O_CREAT <ast.BitOr object at 0x7da2590d6aa0> name[os].O_EXCL] <ast.BitOr object at 0x7da2590d6aa0> name[os].O_WRONLY]
call[name[os].open, parameter[name[file], name[write_lock_flags]]] | keyword[def] identifier[_create_file_racefree] ( identifier[self] , identifier[file] ):
literal[string]
identifier[write_lock_flags] = identifier[os] . identifier[O_CREAT] | identifier[os] . identifier[O_EXCL] | identifier[os] . identifier[O_WRONLY]
identifier[os] . identifier[open] ( identifier[file] , identifier[write_lock_flags] ) | def _create_file_racefree(self, file):
"""
Creates a file, but fails if the file already exists.
This function will thus only succeed if this process actually creates
the file; if the file already exists, it will cause an OSError,
solving race conditions.
:param str file: File to create.
"""
write_lock_flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
os.open(file, write_lock_flags) |
def _check_peptide_lengths(self, peptide_lengths=None):
"""
If peptide lengths not specified, then try using the default
lengths associated with this predictor object. If those aren't
a valid non-empty sequence of integers, then raise an exception.
Otherwise return the peptide lengths.
"""
if not peptide_lengths:
peptide_lengths = self.default_peptide_lengths
if not peptide_lengths:
raise ValueError(
("Must either provide 'peptide_lengths' argument "
"or set 'default_peptide_lengths"))
if isinstance(peptide_lengths, int):
peptide_lengths = [peptide_lengths]
require_iterable_of(peptide_lengths, int)
for peptide_length in peptide_lengths:
if (self.min_peptide_length is not None and
peptide_length < self.min_peptide_length):
raise ValueError(
"Invalid peptide length %d, shorter than min %d" % (
peptide_length,
self.min_peptide_length))
elif (self.max_peptide_length is not None and
peptide_length > self.max_peptide_length):
raise ValueError(
"Invalid peptide length %d, longer than max %d" % (
peptide_length,
self.max_peptide_length))
return peptide_lengths | def function[_check_peptide_lengths, parameter[self, peptide_lengths]]:
constant[
If peptide lengths not specified, then try using the default
lengths associated with this predictor object. If those aren't
a valid non-empty sequence of integers, then raise an exception.
Otherwise return the peptide lengths.
]
if <ast.UnaryOp object at 0x7da1b0005810> begin[:]
variable[peptide_lengths] assign[=] name[self].default_peptide_lengths
if <ast.UnaryOp object at 0x7da1b0005120> begin[:]
<ast.Raise object at 0x7da1b00056f0>
if call[name[isinstance], parameter[name[peptide_lengths], name[int]]] begin[:]
variable[peptide_lengths] assign[=] list[[<ast.Name object at 0x7da1b0006080>]]
call[name[require_iterable_of], parameter[name[peptide_lengths], name[int]]]
for taget[name[peptide_length]] in starred[name[peptide_lengths]] begin[:]
if <ast.BoolOp object at 0x7da1b0004640> begin[:]
<ast.Raise object at 0x7da1b0005900>
return[name[peptide_lengths]] | keyword[def] identifier[_check_peptide_lengths] ( identifier[self] , identifier[peptide_lengths] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[peptide_lengths] :
identifier[peptide_lengths] = identifier[self] . identifier[default_peptide_lengths]
keyword[if] keyword[not] identifier[peptide_lengths] :
keyword[raise] identifier[ValueError] (
( literal[string]
literal[string] ))
keyword[if] identifier[isinstance] ( identifier[peptide_lengths] , identifier[int] ):
identifier[peptide_lengths] =[ identifier[peptide_lengths] ]
identifier[require_iterable_of] ( identifier[peptide_lengths] , identifier[int] )
keyword[for] identifier[peptide_length] keyword[in] identifier[peptide_lengths] :
keyword[if] ( identifier[self] . identifier[min_peptide_length] keyword[is] keyword[not] keyword[None] keyword[and]
identifier[peptide_length] < identifier[self] . identifier[min_peptide_length] ):
keyword[raise] identifier[ValueError] (
literal[string] %(
identifier[peptide_length] ,
identifier[self] . identifier[min_peptide_length] ))
keyword[elif] ( identifier[self] . identifier[max_peptide_length] keyword[is] keyword[not] keyword[None] keyword[and]
identifier[peptide_length] > identifier[self] . identifier[max_peptide_length] ):
keyword[raise] identifier[ValueError] (
literal[string] %(
identifier[peptide_length] ,
identifier[self] . identifier[max_peptide_length] ))
keyword[return] identifier[peptide_lengths] | def _check_peptide_lengths(self, peptide_lengths=None):
"""
If peptide lengths not specified, then try using the default
lengths associated with this predictor object. If those aren't
a valid non-empty sequence of integers, then raise an exception.
Otherwise return the peptide lengths.
"""
if not peptide_lengths:
peptide_lengths = self.default_peptide_lengths # depends on [control=['if'], data=[]]
if not peptide_lengths:
raise ValueError("Must either provide 'peptide_lengths' argument or set 'default_peptide_lengths") # depends on [control=['if'], data=[]]
if isinstance(peptide_lengths, int):
peptide_lengths = [peptide_lengths] # depends on [control=['if'], data=[]]
require_iterable_of(peptide_lengths, int)
for peptide_length in peptide_lengths:
if self.min_peptide_length is not None and peptide_length < self.min_peptide_length:
raise ValueError('Invalid peptide length %d, shorter than min %d' % (peptide_length, self.min_peptide_length)) # depends on [control=['if'], data=[]]
elif self.max_peptide_length is not None and peptide_length > self.max_peptide_length:
raise ValueError('Invalid peptide length %d, longer than max %d' % (peptide_length, self.max_peptide_length)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['peptide_length']]
return peptide_lengths |
def _get_best_type_from_mapping(mapping):
"""
THERE ARE MULTIPLE TYPES IN AN INDEX, PICK THE BEST
:param mapping: THE ES MAPPING DOCUMENT
:return: (type_name, mapping) PAIR (mapping.properties WILL HAVE PROPERTIES
"""
best_type_name = None
best_mapping = None
for k, m in mapping.items():
if k == "_default_":
continue
if best_type_name is None or len(m.properties) > len(best_mapping.properties):
best_type_name = k
best_mapping = m
if best_type_name == None:
return "_default_", mapping["_default_"]
return best_type_name, best_mapping | def function[_get_best_type_from_mapping, parameter[mapping]]:
constant[
THERE ARE MULTIPLE TYPES IN AN INDEX, PICK THE BEST
:param mapping: THE ES MAPPING DOCUMENT
:return: (type_name, mapping) PAIR (mapping.properties WILL HAVE PROPERTIES
]
variable[best_type_name] assign[=] constant[None]
variable[best_mapping] assign[=] constant[None]
for taget[tuple[[<ast.Name object at 0x7da1b0baf040>, <ast.Name object at 0x7da1b0baf490>]]] in starred[call[name[mapping].items, parameter[]]] begin[:]
if compare[name[k] equal[==] constant[_default_]] begin[:]
continue
if <ast.BoolOp object at 0x7da1b0bafc70> begin[:]
variable[best_type_name] assign[=] name[k]
variable[best_mapping] assign[=] name[m]
if compare[name[best_type_name] equal[==] constant[None]] begin[:]
return[tuple[[<ast.Constant object at 0x7da1b0baefe0>, <ast.Subscript object at 0x7da1b0baf6a0>]]]
return[tuple[[<ast.Name object at 0x7da1b0baf9d0>, <ast.Name object at 0x7da1b0baf9a0>]]] | keyword[def] identifier[_get_best_type_from_mapping] ( identifier[mapping] ):
literal[string]
identifier[best_type_name] = keyword[None]
identifier[best_mapping] = keyword[None]
keyword[for] identifier[k] , identifier[m] keyword[in] identifier[mapping] . identifier[items] ():
keyword[if] identifier[k] == literal[string] :
keyword[continue]
keyword[if] identifier[best_type_name] keyword[is] keyword[None] keyword[or] identifier[len] ( identifier[m] . identifier[properties] )> identifier[len] ( identifier[best_mapping] . identifier[properties] ):
identifier[best_type_name] = identifier[k]
identifier[best_mapping] = identifier[m]
keyword[if] identifier[best_type_name] == keyword[None] :
keyword[return] literal[string] , identifier[mapping] [ literal[string] ]
keyword[return] identifier[best_type_name] , identifier[best_mapping] | def _get_best_type_from_mapping(mapping):
"""
THERE ARE MULTIPLE TYPES IN AN INDEX, PICK THE BEST
:param mapping: THE ES MAPPING DOCUMENT
:return: (type_name, mapping) PAIR (mapping.properties WILL HAVE PROPERTIES
"""
best_type_name = None
best_mapping = None
for (k, m) in mapping.items():
if k == '_default_':
continue # depends on [control=['if'], data=[]]
if best_type_name is None or len(m.properties) > len(best_mapping.properties):
best_type_name = k
best_mapping = m # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
if best_type_name == None:
return ('_default_', mapping['_default_']) # depends on [control=['if'], data=[]]
return (best_type_name, best_mapping) |
def __tableStringParser(self, tableString):
"""
Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: Missing data value.
ValueError: Missing parent data.
Returns:
Array of header and decisions::
print(return)
[
['headerVar1', ... ,'headerVarN'],
[
['decisionValue1', ... ,'decisionValueN'],
[<row2 strings>],
...
[<rowN strings>]
]
]
"""
error = []
header = []
decisions = []
if tableString.split() == []:
error.append('Table variable is empty!')
else:
tableString = tableString.split('\n')
newData = []
for element in tableString:
if element.strip():
newData.append(element)
for element in newData[0].split():
if not element in header:
header.append(element)
else:
error.append('Header element: ' + element + ' is not unique!')
for i, tableString in enumerate(newData[2:]):
split = tableString.split()
if len(split) == len(header):
decisions.append(split)
else:
error.append('Row: {}==> missing: {} data'.format(
str(i).ljust(4),
str(len(header) - len(split)).ljust(2))
)
if error:
view.Tli.showErrors('TableStringError', error)
else:
return [header, decisions] | def function[__tableStringParser, parameter[self, tableString]]:
constant[
Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: Missing data value.
ValueError: Missing parent data.
Returns:
Array of header and decisions::
print(return)
[
['headerVar1', ... ,'headerVarN'],
[
['decisionValue1', ... ,'decisionValueN'],
[<row2 strings>],
...
[<rowN strings>]
]
]
]
variable[error] assign[=] list[[]]
variable[header] assign[=] list[[]]
variable[decisions] assign[=] list[[]]
if compare[call[name[tableString].split, parameter[]] equal[==] list[[]]] begin[:]
call[name[error].append, parameter[constant[Table variable is empty!]]]
if name[error] begin[:]
call[name[view].Tli.showErrors, parameter[constant[TableStringError], name[error]]] | keyword[def] identifier[__tableStringParser] ( identifier[self] , identifier[tableString] ):
literal[string]
identifier[error] =[]
identifier[header] =[]
identifier[decisions] =[]
keyword[if] identifier[tableString] . identifier[split] ()==[]:
identifier[error] . identifier[append] ( literal[string] )
keyword[else] :
identifier[tableString] = identifier[tableString] . identifier[split] ( literal[string] )
identifier[newData] =[]
keyword[for] identifier[element] keyword[in] identifier[tableString] :
keyword[if] identifier[element] . identifier[strip] ():
identifier[newData] . identifier[append] ( identifier[element] )
keyword[for] identifier[element] keyword[in] identifier[newData] [ literal[int] ]. identifier[split] ():
keyword[if] keyword[not] identifier[element] keyword[in] identifier[header] :
identifier[header] . identifier[append] ( identifier[element] )
keyword[else] :
identifier[error] . identifier[append] ( literal[string] + identifier[element] + literal[string] )
keyword[for] identifier[i] , identifier[tableString] keyword[in] identifier[enumerate] ( identifier[newData] [ literal[int] :]):
identifier[split] = identifier[tableString] . identifier[split] ()
keyword[if] identifier[len] ( identifier[split] )== identifier[len] ( identifier[header] ):
identifier[decisions] . identifier[append] ( identifier[split] )
keyword[else] :
identifier[error] . identifier[append] ( literal[string] . identifier[format] (
identifier[str] ( identifier[i] ). identifier[ljust] ( literal[int] ),
identifier[str] ( identifier[len] ( identifier[header] )- identifier[len] ( identifier[split] )). identifier[ljust] ( literal[int] ))
)
keyword[if] identifier[error] :
identifier[view] . identifier[Tli] . identifier[showErrors] ( literal[string] , identifier[error] )
keyword[else] :
keyword[return] [ identifier[header] , identifier[decisions] ] | def __tableStringParser(self, tableString):
"""
Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: Missing data value.
ValueError: Missing parent data.
Returns:
Array of header and decisions::
print(return)
[
['headerVar1', ... ,'headerVarN'],
[
['decisionValue1', ... ,'decisionValueN'],
[<row2 strings>],
...
[<rowN strings>]
]
]
"""
error = []
header = []
decisions = []
if tableString.split() == []:
error.append('Table variable is empty!') # depends on [control=['if'], data=[]]
else:
tableString = tableString.split('\n')
newData = []
for element in tableString:
if element.strip():
newData.append(element) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['element']]
for element in newData[0].split():
if not element in header:
header.append(element) # depends on [control=['if'], data=[]]
else:
error.append('Header element: ' + element + ' is not unique!') # depends on [control=['for'], data=['element']]
for (i, tableString) in enumerate(newData[2:]):
split = tableString.split()
if len(split) == len(header):
decisions.append(split) # depends on [control=['if'], data=[]]
else:
error.append('Row: {}==> missing: {} data'.format(str(i).ljust(4), str(len(header) - len(split)).ljust(2))) # depends on [control=['for'], data=[]]
if error:
view.Tli.showErrors('TableStringError', error) # depends on [control=['if'], data=[]]
else:
return [header, decisions] |
def get_instance(self, payload):
"""
Build an instance of WebhookInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.messaging.v1.session.webhook.WebhookInstance
:rtype: twilio.rest.messaging.v1.session.webhook.WebhookInstance
"""
return WebhookInstance(self._version, payload, session_sid=self._solution['session_sid'], ) | def function[get_instance, parameter[self, payload]]:
constant[
Build an instance of WebhookInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.messaging.v1.session.webhook.WebhookInstance
:rtype: twilio.rest.messaging.v1.session.webhook.WebhookInstance
]
return[call[name[WebhookInstance], parameter[name[self]._version, name[payload]]]] | keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ):
literal[string]
keyword[return] identifier[WebhookInstance] ( identifier[self] . identifier[_version] , identifier[payload] , identifier[session_sid] = identifier[self] . identifier[_solution] [ literal[string] ],) | def get_instance(self, payload):
"""
Build an instance of WebhookInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.messaging.v1.session.webhook.WebhookInstance
:rtype: twilio.rest.messaging.v1.session.webhook.WebhookInstance
"""
return WebhookInstance(self._version, payload, session_sid=self._solution['session_sid']) |
def enter_room(self, sid, room, namespace=None):
"""Enter a room.
The only difference with the :func:`socketio.Server.enter_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
"""
return self.server.enter_room(sid, room,
namespace=namespace or self.namespace) | def function[enter_room, parameter[self, sid, room, namespace]]:
constant[Enter a room.
The only difference with the :func:`socketio.Server.enter_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
]
return[call[name[self].server.enter_room, parameter[name[sid], name[room]]]] | keyword[def] identifier[enter_room] ( identifier[self] , identifier[sid] , identifier[room] , identifier[namespace] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[server] . identifier[enter_room] ( identifier[sid] , identifier[room] ,
identifier[namespace] = identifier[namespace] keyword[or] identifier[self] . identifier[namespace] ) | def enter_room(self, sid, room, namespace=None):
"""Enter a room.
The only difference with the :func:`socketio.Server.enter_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
"""
return self.server.enter_room(sid, room, namespace=namespace or self.namespace) |
def load_from_dict(self, data: dict, overwrite: bool=True):
"""
Loads key/values from dicts or list into the ConfigKey.
:param data: The data object to load.
This can be a dict, or a list of key/value tuples.
:param overwrite: Should the ConfigKey overwrite data already in it?
"""
if data is None or data == {}:
return False
# Loop over items
if isinstance(data, list) or isinstance(data, tuple):
# Pick a random item from the tuple.
if len(data[0]) != 2:
raise exc.LoaderException("Cannot load data with length {}".format(len(data[0])))
items = data
elif isinstance(data, dict) or isinstance(data, self.__class__):
items = data.items()
else:
raise exc.LoaderException("Cannot load data of type {}".format(type(data)))
for key, item in items:
assert isinstance(key, str)
if hasattr(self, key) and not overwrite:
# Refuse to overwrite existing data.
continue
# Check name to verify it's safe.
if self.safe_load:
if key.startswith("__") or key in ['dump', 'items', 'keys', 'values',
'iter_list', 'load_from_dict', 'iter_list_dump',
'parsed', 'safe_load']:
# It's evil!
key = "unsafe_" + key
if '.' in key:
# Doubly evil!
key = key.replace('.', '_')
if isinstance(item, dict):
# Create a new ConfigKey object with the dict.
ncfg = ConfigKey()
# Parse the data.
ncfg.load_from_dict(item)
# Set our new ConfigKey as an attribute of ourselves.
setattr(self, key, ncfg)
elif isinstance(item, list):
# Iterate over the list, creating ConfigKey items as appropriate.
nlst = self.iter_list(item)
# Set our new list as an attribute of ourselves.
setattr(self, key, nlst)
else:
# Set the item as an attribute of ourselves.
setattr(self, key, item)
# Flip the parsed flag,
self.parsed = True | def function[load_from_dict, parameter[self, data, overwrite]]:
constant[
Loads key/values from dicts or list into the ConfigKey.
:param data: The data object to load.
This can be a dict, or a list of key/value tuples.
:param overwrite: Should the ConfigKey overwrite data already in it?
]
if <ast.BoolOp object at 0x7da1b1471ba0> begin[:]
return[constant[False]]
if <ast.BoolOp object at 0x7da1b14718a0> begin[:]
if compare[call[name[len], parameter[call[name[data]][constant[0]]]] not_equal[!=] constant[2]] begin[:]
<ast.Raise object at 0x7da204622470>
variable[items] assign[=] name[data]
for taget[tuple[[<ast.Name object at 0x7da20c6a86d0>, <ast.Name object at 0x7da20c6a9d80>]]] in starred[name[items]] begin[:]
assert[call[name[isinstance], parameter[name[key], name[str]]]]
if <ast.BoolOp object at 0x7da20c6abfa0> begin[:]
continue
if name[self].safe_load begin[:]
if <ast.BoolOp object at 0x7da20c6a93f0> begin[:]
variable[key] assign[=] binary_operation[constant[unsafe_] + name[key]]
if compare[constant[.] in name[key]] begin[:]
variable[key] assign[=] call[name[key].replace, parameter[constant[.], constant[_]]]
if call[name[isinstance], parameter[name[item], name[dict]]] begin[:]
variable[ncfg] assign[=] call[name[ConfigKey], parameter[]]
call[name[ncfg].load_from_dict, parameter[name[item]]]
call[name[setattr], parameter[name[self], name[key], name[ncfg]]]
name[self].parsed assign[=] constant[True] | keyword[def] identifier[load_from_dict] ( identifier[self] , identifier[data] : identifier[dict] , identifier[overwrite] : identifier[bool] = keyword[True] ):
literal[string]
keyword[if] identifier[data] keyword[is] keyword[None] keyword[or] identifier[data] =={}:
keyword[return] keyword[False]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[list] ) keyword[or] identifier[isinstance] ( identifier[data] , identifier[tuple] ):
keyword[if] identifier[len] ( identifier[data] [ literal[int] ])!= literal[int] :
keyword[raise] identifier[exc] . identifier[LoaderException] ( literal[string] . identifier[format] ( identifier[len] ( identifier[data] [ literal[int] ])))
identifier[items] = identifier[data]
keyword[elif] identifier[isinstance] ( identifier[data] , identifier[dict] ) keyword[or] identifier[isinstance] ( identifier[data] , identifier[self] . identifier[__class__] ):
identifier[items] = identifier[data] . identifier[items] ()
keyword[else] :
keyword[raise] identifier[exc] . identifier[LoaderException] ( literal[string] . identifier[format] ( identifier[type] ( identifier[data] )))
keyword[for] identifier[key] , identifier[item] keyword[in] identifier[items] :
keyword[assert] identifier[isinstance] ( identifier[key] , identifier[str] )
keyword[if] identifier[hasattr] ( identifier[self] , identifier[key] ) keyword[and] keyword[not] identifier[overwrite] :
keyword[continue]
keyword[if] identifier[self] . identifier[safe_load] :
keyword[if] identifier[key] . identifier[startswith] ( literal[string] ) keyword[or] identifier[key] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] ]:
identifier[key] = literal[string] + identifier[key]
keyword[if] literal[string] keyword[in] identifier[key] :
identifier[key] = identifier[key] . identifier[replace] ( literal[string] , literal[string] )
keyword[if] identifier[isinstance] ( identifier[item] , identifier[dict] ):
identifier[ncfg] = identifier[ConfigKey] ()
identifier[ncfg] . identifier[load_from_dict] ( identifier[item] )
identifier[setattr] ( identifier[self] , identifier[key] , identifier[ncfg] )
keyword[elif] identifier[isinstance] ( identifier[item] , identifier[list] ):
identifier[nlst] = identifier[self] . identifier[iter_list] ( identifier[item] )
identifier[setattr] ( identifier[self] , identifier[key] , identifier[nlst] )
keyword[else] :
identifier[setattr] ( identifier[self] , identifier[key] , identifier[item] )
identifier[self] . identifier[parsed] = keyword[True] | def load_from_dict(self, data: dict, overwrite: bool=True):
"""
Loads key/values from dicts or list into the ConfigKey.
:param data: The data object to load.
This can be a dict, or a list of key/value tuples.
:param overwrite: Should the ConfigKey overwrite data already in it?
"""
if data is None or data == {}:
return False # depends on [control=['if'], data=[]]
# Loop over items
if isinstance(data, list) or isinstance(data, tuple):
# Pick a random item from the tuple.
if len(data[0]) != 2:
raise exc.LoaderException('Cannot load data with length {}'.format(len(data[0]))) # depends on [control=['if'], data=[]]
items = data # depends on [control=['if'], data=[]]
elif isinstance(data, dict) or isinstance(data, self.__class__):
items = data.items() # depends on [control=['if'], data=[]]
else:
raise exc.LoaderException('Cannot load data of type {}'.format(type(data)))
for (key, item) in items:
assert isinstance(key, str)
if hasattr(self, key) and (not overwrite):
# Refuse to overwrite existing data.
continue # depends on [control=['if'], data=[]]
# Check name to verify it's safe.
if self.safe_load:
if key.startswith('__') or key in ['dump', 'items', 'keys', 'values', 'iter_list', 'load_from_dict', 'iter_list_dump', 'parsed', 'safe_load']:
# It's evil!
key = 'unsafe_' + key # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
if '.' in key:
# Doubly evil!
key = key.replace('.', '_') # depends on [control=['if'], data=['key']]
if isinstance(item, dict):
# Create a new ConfigKey object with the dict.
ncfg = ConfigKey()
# Parse the data.
ncfg.load_from_dict(item)
# Set our new ConfigKey as an attribute of ourselves.
setattr(self, key, ncfg) # depends on [control=['if'], data=[]]
elif isinstance(item, list):
# Iterate over the list, creating ConfigKey items as appropriate.
nlst = self.iter_list(item)
# Set our new list as an attribute of ourselves.
setattr(self, key, nlst) # depends on [control=['if'], data=[]]
else:
# Set the item as an attribute of ourselves.
setattr(self, key, item) # depends on [control=['for'], data=[]]
# Flip the parsed flag,
self.parsed = True |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidActionMenuView, self).init_widget()
d = self.declaration
w = self.widget
#: Kinda hackish, but when we get the menu back, load it
w.getMenu().then(self.on_menu)
w.setOnMenuItemClickListener(w.getId())
w.onMenuItemClick.connect(self.on_menu_item_click) | def function[init_widget, parameter[self]]:
constant[ Initialize the underlying widget.
]
call[call[name[super], parameter[name[AndroidActionMenuView], name[self]]].init_widget, parameter[]]
variable[d] assign[=] name[self].declaration
variable[w] assign[=] name[self].widget
call[call[name[w].getMenu, parameter[]].then, parameter[name[self].on_menu]]
call[name[w].setOnMenuItemClickListener, parameter[call[name[w].getId, parameter[]]]]
call[name[w].onMenuItemClick.connect, parameter[name[self].on_menu_item_click]] | keyword[def] identifier[init_widget] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[AndroidActionMenuView] , identifier[self] ). identifier[init_widget] ()
identifier[d] = identifier[self] . identifier[declaration]
identifier[w] = identifier[self] . identifier[widget]
identifier[w] . identifier[getMenu] (). identifier[then] ( identifier[self] . identifier[on_menu] )
identifier[w] . identifier[setOnMenuItemClickListener] ( identifier[w] . identifier[getId] ())
identifier[w] . identifier[onMenuItemClick] . identifier[connect] ( identifier[self] . identifier[on_menu_item_click] ) | def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidActionMenuView, self).init_widget()
d = self.declaration
w = self.widget
#: Kinda hackish, but when we get the menu back, load it
w.getMenu().then(self.on_menu)
w.setOnMenuItemClickListener(w.getId())
w.onMenuItemClick.connect(self.on_menu_item_click) |
def timer(self, key, **dims):
"""Adds timer with dimensions to the registry"""
return super(MetricsRegistry, self).timer(
self.metadata.register(key, **dims)) | def function[timer, parameter[self, key]]:
constant[Adds timer with dimensions to the registry]
return[call[call[name[super], parameter[name[MetricsRegistry], name[self]]].timer, parameter[call[name[self].metadata.register, parameter[name[key]]]]]] | keyword[def] identifier[timer] ( identifier[self] , identifier[key] ,** identifier[dims] ):
literal[string]
keyword[return] identifier[super] ( identifier[MetricsRegistry] , identifier[self] ). identifier[timer] (
identifier[self] . identifier[metadata] . identifier[register] ( identifier[key] ,** identifier[dims] )) | def timer(self, key, **dims):
"""Adds timer with dimensions to the registry"""
return super(MetricsRegistry, self).timer(self.metadata.register(key, **dims)) |
def EnumAndLogControlAncestors(control: Control, showAllName: bool = True) -> None:
"""
Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
showAllName: bool, if False, print the first 30 characters of control.Name.
"""
lists = []
while control:
lists.insert(0, control)
control = control.GetParentControl()
for i, control in enumerate(lists):
LogControl(control, i, showAllName) | def function[EnumAndLogControlAncestors, parameter[control, showAllName]]:
constant[
Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
showAllName: bool, if False, print the first 30 characters of control.Name.
]
variable[lists] assign[=] list[[]]
while name[control] begin[:]
call[name[lists].insert, parameter[constant[0], name[control]]]
variable[control] assign[=] call[name[control].GetParentControl, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da1b26ac550>, <ast.Name object at 0x7da1b26af7f0>]]] in starred[call[name[enumerate], parameter[name[lists]]]] begin[:]
call[name[LogControl], parameter[name[control], name[i], name[showAllName]]] | keyword[def] identifier[EnumAndLogControlAncestors] ( identifier[control] : identifier[Control] , identifier[showAllName] : identifier[bool] = keyword[True] )-> keyword[None] :
literal[string]
identifier[lists] =[]
keyword[while] identifier[control] :
identifier[lists] . identifier[insert] ( literal[int] , identifier[control] )
identifier[control] = identifier[control] . identifier[GetParentControl] ()
keyword[for] identifier[i] , identifier[control] keyword[in] identifier[enumerate] ( identifier[lists] ):
identifier[LogControl] ( identifier[control] , identifier[i] , identifier[showAllName] ) | def EnumAndLogControlAncestors(control: Control, showAllName: bool=True) -> None:
"""
Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
showAllName: bool, if False, print the first 30 characters of control.Name.
"""
lists = []
while control:
lists.insert(0, control)
control = control.GetParentControl() # depends on [control=['while'], data=[]]
for (i, control) in enumerate(lists):
LogControl(control, i, showAllName) # depends on [control=['for'], data=[]] |
def update_extent_from_rectangle(self):
"""Update extent value in GUI based from the QgsMapTool rectangle.
.. note:: Delegates to update_extent()
"""
self.show()
self.canvas.unsetMapTool(self.rectangle_map_tool)
self.canvas.setMapTool(self.pan_tool)
rectangle = self.rectangle_map_tool.rectangle()
if rectangle:
self.bounding_box_group.setTitle(
self.tr('Bounding box from rectangle'))
extent = rectangle_geo_array(rectangle, self.iface.mapCanvas())
self.update_extent(extent) | def function[update_extent_from_rectangle, parameter[self]]:
constant[Update extent value in GUI based from the QgsMapTool rectangle.
.. note:: Delegates to update_extent()
]
call[name[self].show, parameter[]]
call[name[self].canvas.unsetMapTool, parameter[name[self].rectangle_map_tool]]
call[name[self].canvas.setMapTool, parameter[name[self].pan_tool]]
variable[rectangle] assign[=] call[name[self].rectangle_map_tool.rectangle, parameter[]]
if name[rectangle] begin[:]
call[name[self].bounding_box_group.setTitle, parameter[call[name[self].tr, parameter[constant[Bounding box from rectangle]]]]]
variable[extent] assign[=] call[name[rectangle_geo_array], parameter[name[rectangle], call[name[self].iface.mapCanvas, parameter[]]]]
call[name[self].update_extent, parameter[name[extent]]] | keyword[def] identifier[update_extent_from_rectangle] ( identifier[self] ):
literal[string]
identifier[self] . identifier[show] ()
identifier[self] . identifier[canvas] . identifier[unsetMapTool] ( identifier[self] . identifier[rectangle_map_tool] )
identifier[self] . identifier[canvas] . identifier[setMapTool] ( identifier[self] . identifier[pan_tool] )
identifier[rectangle] = identifier[self] . identifier[rectangle_map_tool] . identifier[rectangle] ()
keyword[if] identifier[rectangle] :
identifier[self] . identifier[bounding_box_group] . identifier[setTitle] (
identifier[self] . identifier[tr] ( literal[string] ))
identifier[extent] = identifier[rectangle_geo_array] ( identifier[rectangle] , identifier[self] . identifier[iface] . identifier[mapCanvas] ())
identifier[self] . identifier[update_extent] ( identifier[extent] ) | def update_extent_from_rectangle(self):
"""Update extent value in GUI based from the QgsMapTool rectangle.
.. note:: Delegates to update_extent()
"""
self.show()
self.canvas.unsetMapTool(self.rectangle_map_tool)
self.canvas.setMapTool(self.pan_tool)
rectangle = self.rectangle_map_tool.rectangle()
if rectangle:
self.bounding_box_group.setTitle(self.tr('Bounding box from rectangle'))
extent = rectangle_geo_array(rectangle, self.iface.mapCanvas())
self.update_extent(extent) # depends on [control=['if'], data=[]] |
def get_training_image_text_data_iters(source_root: str,
source: str, target: str,
validation_source_root: str,
validation_source: str, validation_target: str,
vocab_target: vocab.Vocab,
vocab_target_path: Optional[str],
batch_size: int,
batch_by_words: bool,
batch_num_devices: int,
source_image_size: tuple,
max_seq_len_target: int,
bucketing: bool,
bucket_width: int,
use_feature_loader: bool = False,
preload_features: bool = False) -> Tuple['ParallelSampleIter',
'ParallelSampleIter',
'DataConfig', 'DataInfo']:
"""
Returns data iterators for training and validation data.
:param source_root: Path to source images since the file in source contains relative paths.
:param source: Path to source training data.
:param target: Path to target training data.
:param validation_source_root: Path to validation source images since the file in validation_source contains relative paths.
:param validation_source: Path to source validation data.
:param validation_target: Path to target validation data.
:param vocab_target: Target vocabulary.
:param vocab_target_path: Path to target vocabulary.
:param batch_size: Batch size.
:param batch_by_words: Size batches by words rather than sentences.
:param batch_num_devices: Number of devices batches will be parallelized across.
:param source_image_size: size to resize the image to (for iterator)
:param max_seq_len_target: Maximum target sequence length.
:param bucketing: Whether to use bucketing.
:param bucket_width: Size of buckets.
:param use_feature_loader: If True, features are loaded instead of images.
:param preload_features: If use_feature_loader si True, this enables load all the feature to memory
:return: Tuple of (training data iterator, validation data iterator, data config).
"""
logger.info("===============================")
logger.info("Creating training data iterator")
logger.info("===============================")
# define buckets
buckets = define_empty_source_parallel_buckets(max_seq_len_target, bucket_width) if bucketing else [
(0, max_seq_len_target)]
source_images = [FileListReader(source, source_root)]
target_sentences = SequenceReader(target, vocab_target, add_bos=True)
# 2. pass: Get data statistics only on target (source not considered)
data_statistics = get_data_statistics(source_readers=None,
target_reader=target_sentences,
buckets=buckets,
length_ratio_mean=1.0,
length_ratio_std=1.0,
source_vocabs=None,
target_vocab=vocab_target)
bucket_batch_sizes = define_bucket_batch_sizes(buckets,
batch_size,
batch_by_words,
batch_num_devices,
data_statistics.average_len_target_per_bucket)
data_statistics.log(bucket_batch_sizes)
data_loader = RawListTextDatasetLoader(buckets=buckets,
eos_id=vocab_target[C.EOS_SYMBOL],
pad_id=C.PAD_ID)
training_data = data_loader.load(source_images[0], target_sentences,
data_statistics.num_sents_per_bucket).fill_up(bucket_batch_sizes)
data_info = DataInfo(sources=source_images,
target=target,
source_vocabs=None,
target_vocab=vocab_target_path,
shared_vocab=False,
num_shards=1)
config_data = DataConfig(data_statistics=data_statistics,
max_seq_len_source=0,
max_seq_len_target=max_seq_len_target,
num_source_factors=len(source_images))
# Add useful stuff to config_data
config_data.source_root = source_root
config_data.validation_source_root = validation_source_root
config_data.use_feature_loader = use_feature_loader
train_iter = ImageTextSampleIter(data=training_data,
buckets=buckets,
batch_size=batch_size,
bucket_batch_sizes=bucket_batch_sizes,
image_size=source_image_size,
use_feature_loader=use_feature_loader,
preload_features=preload_features)
validation_iter = get_validation_image_text_data_iter(data_loader=data_loader,
validation_source_root=validation_source_root,
validation_source=validation_source,
validation_target=validation_target,
buckets=buckets,
bucket_batch_sizes=bucket_batch_sizes,
source_image_size=source_image_size,
vocab_target=vocab_target,
max_seq_len_target=max_seq_len_target,
batch_size=batch_size,
use_feature_loader=use_feature_loader,
preload_features=preload_features)
return train_iter, validation_iter, config_data, data_info | def function[get_training_image_text_data_iters, parameter[source_root, source, target, validation_source_root, validation_source, validation_target, vocab_target, vocab_target_path, batch_size, batch_by_words, batch_num_devices, source_image_size, max_seq_len_target, bucketing, bucket_width, use_feature_loader, preload_features]]:
constant[
Returns data iterators for training and validation data.
:param source_root: Path to source images since the file in source contains relative paths.
:param source: Path to source training data.
:param target: Path to target training data.
:param validation_source_root: Path to validation source images since the file in validation_source contains relative paths.
:param validation_source: Path to source validation data.
:param validation_target: Path to target validation data.
:param vocab_target: Target vocabulary.
:param vocab_target_path: Path to target vocabulary.
:param batch_size: Batch size.
:param batch_by_words: Size batches by words rather than sentences.
:param batch_num_devices: Number of devices batches will be parallelized across.
:param source_image_size: size to resize the image to (for iterator)
:param max_seq_len_target: Maximum target sequence length.
:param bucketing: Whether to use bucketing.
:param bucket_width: Size of buckets.
:param use_feature_loader: If True, features are loaded instead of images.
:param preload_features: If use_feature_loader si True, this enables load all the feature to memory
:return: Tuple of (training data iterator, validation data iterator, data config).
]
call[name[logger].info, parameter[constant[===============================]]]
call[name[logger].info, parameter[constant[Creating training data iterator]]]
call[name[logger].info, parameter[constant[===============================]]]
variable[buckets] assign[=] <ast.IfExp object at 0x7da1b1df73a0>
variable[source_images] assign[=] list[[<ast.Call object at 0x7da1b1df7130>]]
variable[target_sentences] assign[=] call[name[SequenceReader], parameter[name[target], name[vocab_target]]]
variable[data_statistics] assign[=] call[name[get_data_statistics], parameter[]]
variable[bucket_batch_sizes] assign[=] call[name[define_bucket_batch_sizes], parameter[name[buckets], name[batch_size], name[batch_by_words], name[batch_num_devices], name[data_statistics].average_len_target_per_bucket]]
call[name[data_statistics].log, parameter[name[bucket_batch_sizes]]]
variable[data_loader] assign[=] call[name[RawListTextDatasetLoader], parameter[]]
variable[training_data] assign[=] call[call[name[data_loader].load, parameter[call[name[source_images]][constant[0]], name[target_sentences], name[data_statistics].num_sents_per_bucket]].fill_up, parameter[name[bucket_batch_sizes]]]
variable[data_info] assign[=] call[name[DataInfo], parameter[]]
variable[config_data] assign[=] call[name[DataConfig], parameter[]]
name[config_data].source_root assign[=] name[source_root]
name[config_data].validation_source_root assign[=] name[validation_source_root]
name[config_data].use_feature_loader assign[=] name[use_feature_loader]
variable[train_iter] assign[=] call[name[ImageTextSampleIter], parameter[]]
variable[validation_iter] assign[=] call[name[get_validation_image_text_data_iter], parameter[]]
return[tuple[[<ast.Name object at 0x7da20c6abca0>, <ast.Name object at 0x7da20c6a8880>, <ast.Name object at 0x7da20c6a8970>, <ast.Name object at 0x7da20c6a9150>]]] | keyword[def] identifier[get_training_image_text_data_iters] ( identifier[source_root] : identifier[str] ,
identifier[source] : identifier[str] , identifier[target] : identifier[str] ,
identifier[validation_source_root] : identifier[str] ,
identifier[validation_source] : identifier[str] , identifier[validation_target] : identifier[str] ,
identifier[vocab_target] : identifier[vocab] . identifier[Vocab] ,
identifier[vocab_target_path] : identifier[Optional] [ identifier[str] ],
identifier[batch_size] : identifier[int] ,
identifier[batch_by_words] : identifier[bool] ,
identifier[batch_num_devices] : identifier[int] ,
identifier[source_image_size] : identifier[tuple] ,
identifier[max_seq_len_target] : identifier[int] ,
identifier[bucketing] : identifier[bool] ,
identifier[bucket_width] : identifier[int] ,
identifier[use_feature_loader] : identifier[bool] = keyword[False] ,
identifier[preload_features] : identifier[bool] = keyword[False] )-> identifier[Tuple] [ literal[string] ,
literal[string] ,
literal[string] , literal[string] ]:
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[buckets] = identifier[define_empty_source_parallel_buckets] ( identifier[max_seq_len_target] , identifier[bucket_width] ) keyword[if] identifier[bucketing] keyword[else] [
( literal[int] , identifier[max_seq_len_target] )]
identifier[source_images] =[ identifier[FileListReader] ( identifier[source] , identifier[source_root] )]
identifier[target_sentences] = identifier[SequenceReader] ( identifier[target] , identifier[vocab_target] , identifier[add_bos] = keyword[True] )
identifier[data_statistics] = identifier[get_data_statistics] ( identifier[source_readers] = keyword[None] ,
identifier[target_reader] = identifier[target_sentences] ,
identifier[buckets] = identifier[buckets] ,
identifier[length_ratio_mean] = literal[int] ,
identifier[length_ratio_std] = literal[int] ,
identifier[source_vocabs] = keyword[None] ,
identifier[target_vocab] = identifier[vocab_target] )
identifier[bucket_batch_sizes] = identifier[define_bucket_batch_sizes] ( identifier[buckets] ,
identifier[batch_size] ,
identifier[batch_by_words] ,
identifier[batch_num_devices] ,
identifier[data_statistics] . identifier[average_len_target_per_bucket] )
identifier[data_statistics] . identifier[log] ( identifier[bucket_batch_sizes] )
identifier[data_loader] = identifier[RawListTextDatasetLoader] ( identifier[buckets] = identifier[buckets] ,
identifier[eos_id] = identifier[vocab_target] [ identifier[C] . identifier[EOS_SYMBOL] ],
identifier[pad_id] = identifier[C] . identifier[PAD_ID] )
identifier[training_data] = identifier[data_loader] . identifier[load] ( identifier[source_images] [ literal[int] ], identifier[target_sentences] ,
identifier[data_statistics] . identifier[num_sents_per_bucket] ). identifier[fill_up] ( identifier[bucket_batch_sizes] )
identifier[data_info] = identifier[DataInfo] ( identifier[sources] = identifier[source_images] ,
identifier[target] = identifier[target] ,
identifier[source_vocabs] = keyword[None] ,
identifier[target_vocab] = identifier[vocab_target_path] ,
identifier[shared_vocab] = keyword[False] ,
identifier[num_shards] = literal[int] )
identifier[config_data] = identifier[DataConfig] ( identifier[data_statistics] = identifier[data_statistics] ,
identifier[max_seq_len_source] = literal[int] ,
identifier[max_seq_len_target] = identifier[max_seq_len_target] ,
identifier[num_source_factors] = identifier[len] ( identifier[source_images] ))
identifier[config_data] . identifier[source_root] = identifier[source_root]
identifier[config_data] . identifier[validation_source_root] = identifier[validation_source_root]
identifier[config_data] . identifier[use_feature_loader] = identifier[use_feature_loader]
identifier[train_iter] = identifier[ImageTextSampleIter] ( identifier[data] = identifier[training_data] ,
identifier[buckets] = identifier[buckets] ,
identifier[batch_size] = identifier[batch_size] ,
identifier[bucket_batch_sizes] = identifier[bucket_batch_sizes] ,
identifier[image_size] = identifier[source_image_size] ,
identifier[use_feature_loader] = identifier[use_feature_loader] ,
identifier[preload_features] = identifier[preload_features] )
identifier[validation_iter] = identifier[get_validation_image_text_data_iter] ( identifier[data_loader] = identifier[data_loader] ,
identifier[validation_source_root] = identifier[validation_source_root] ,
identifier[validation_source] = identifier[validation_source] ,
identifier[validation_target] = identifier[validation_target] ,
identifier[buckets] = identifier[buckets] ,
identifier[bucket_batch_sizes] = identifier[bucket_batch_sizes] ,
identifier[source_image_size] = identifier[source_image_size] ,
identifier[vocab_target] = identifier[vocab_target] ,
identifier[max_seq_len_target] = identifier[max_seq_len_target] ,
identifier[batch_size] = identifier[batch_size] ,
identifier[use_feature_loader] = identifier[use_feature_loader] ,
identifier[preload_features] = identifier[preload_features] )
keyword[return] identifier[train_iter] , identifier[validation_iter] , identifier[config_data] , identifier[data_info] | def get_training_image_text_data_iters(source_root: str, source: str, target: str, validation_source_root: str, validation_source: str, validation_target: str, vocab_target: vocab.Vocab, vocab_target_path: Optional[str], batch_size: int, batch_by_words: bool, batch_num_devices: int, source_image_size: tuple, max_seq_len_target: int, bucketing: bool, bucket_width: int, use_feature_loader: bool=False, preload_features: bool=False) -> Tuple['ParallelSampleIter', 'ParallelSampleIter', 'DataConfig', 'DataInfo']:
"""
Returns data iterators for training and validation data.
:param source_root: Path to source images since the file in source contains relative paths.
:param source: Path to source training data.
:param target: Path to target training data.
:param validation_source_root: Path to validation source images since the file in validation_source contains relative paths.
:param validation_source: Path to source validation data.
:param validation_target: Path to target validation data.
:param vocab_target: Target vocabulary.
:param vocab_target_path: Path to target vocabulary.
:param batch_size: Batch size.
:param batch_by_words: Size batches by words rather than sentences.
:param batch_num_devices: Number of devices batches will be parallelized across.
:param source_image_size: size to resize the image to (for iterator)
:param max_seq_len_target: Maximum target sequence length.
:param bucketing: Whether to use bucketing.
:param bucket_width: Size of buckets.
:param use_feature_loader: If True, features are loaded instead of images.
:param preload_features: If use_feature_loader si True, this enables load all the feature to memory
:return: Tuple of (training data iterator, validation data iterator, data config).
"""
logger.info('===============================')
logger.info('Creating training data iterator')
logger.info('===============================')
# define buckets
buckets = define_empty_source_parallel_buckets(max_seq_len_target, bucket_width) if bucketing else [(0, max_seq_len_target)]
source_images = [FileListReader(source, source_root)]
target_sentences = SequenceReader(target, vocab_target, add_bos=True)
# 2. pass: Get data statistics only on target (source not considered)
data_statistics = get_data_statistics(source_readers=None, target_reader=target_sentences, buckets=buckets, length_ratio_mean=1.0, length_ratio_std=1.0, source_vocabs=None, target_vocab=vocab_target)
bucket_batch_sizes = define_bucket_batch_sizes(buckets, batch_size, batch_by_words, batch_num_devices, data_statistics.average_len_target_per_bucket)
data_statistics.log(bucket_batch_sizes)
data_loader = RawListTextDatasetLoader(buckets=buckets, eos_id=vocab_target[C.EOS_SYMBOL], pad_id=C.PAD_ID)
training_data = data_loader.load(source_images[0], target_sentences, data_statistics.num_sents_per_bucket).fill_up(bucket_batch_sizes)
data_info = DataInfo(sources=source_images, target=target, source_vocabs=None, target_vocab=vocab_target_path, shared_vocab=False, num_shards=1)
config_data = DataConfig(data_statistics=data_statistics, max_seq_len_source=0, max_seq_len_target=max_seq_len_target, num_source_factors=len(source_images))
# Add useful stuff to config_data
config_data.source_root = source_root
config_data.validation_source_root = validation_source_root
config_data.use_feature_loader = use_feature_loader
train_iter = ImageTextSampleIter(data=training_data, buckets=buckets, batch_size=batch_size, bucket_batch_sizes=bucket_batch_sizes, image_size=source_image_size, use_feature_loader=use_feature_loader, preload_features=preload_features)
validation_iter = get_validation_image_text_data_iter(data_loader=data_loader, validation_source_root=validation_source_root, validation_source=validation_source, validation_target=validation_target, buckets=buckets, bucket_batch_sizes=bucket_batch_sizes, source_image_size=source_image_size, vocab_target=vocab_target, max_seq_len_target=max_seq_len_target, batch_size=batch_size, use_feature_loader=use_feature_loader, preload_features=preload_features)
return (train_iter, validation_iter, config_data, data_info) |
def histogram_bin_edges(data, bins=10, mode='equal', min_count=None, integer=False, remove_empty_edges=True, min_width=None):
r'''
Determine bin-edges.
:arguments:
**data** (``<array_like>``)
Input data. The histogram is computed over the flattened array.
:options:
**bins** ([``10``] | ``<int>``)
The number of bins.
**mode** ([``'equal'`` | ``<str>``)
Mode with which to compute the bin-edges:
* ``'equal'``: each bin has equal width.
* ``'log'``: logarithmic spacing.
* ``'uniform'``: uniform number of data-points per bin.
**min_count** (``<int>``)
The minimum number of data-points per bin.
**min_width** (``<float>``)
The minimum width of each bin.
**integer** ([``False``] | [``True``])
If ``True``, bins not encompassing an integer are removed
(e.g. a bin with edges ``[1.1, 1.9]`` is removed, but ``[0.9, 1.1]`` is not removed).
**remove_empty_edges** ([``True``] | [``False``])
Remove empty bins at the beginning or the end.
:returns:
**bin_edges** (``<array of dtype float>``)
The edges to pass into histogram.
'''
# determine the bin-edges
if mode == 'equal':
bin_edges = np.linspace(np.min(data),np.max(data),bins+1)
elif mode == 'log':
bin_edges = np.logspace(np.log10(np.min(data)),np.log10(np.max(data)),bins+1)
elif mode == 'uniform':
# - check
if hasattr(bins, "__len__"):
raise IOError('Only the number of bins can be specified')
# - use the minimum count to estimate the number of bins
if min_count is not None and min_count is not False:
if type(min_count) != int: raise IOError('"min_count" must be an integer number')
bins = int(np.floor(float(len(data))/float(min_count)))
# - number of data-points in each bin (equal for each)
count = int(np.floor(float(len(data))/float(bins))) * np.ones(bins, dtype='int')
# - increase the number of data-points by one is an many bins as needed,
# such that the total fits the total number of data-points
count[np.linspace(0, bins-1, len(data)-np.sum(count)).astype(np.int)] += 1
# - split the data
idx = np.empty((bins+1), dtype='int')
idx[0 ] = 0
idx[1:] = np.cumsum(count)
idx[-1] = len(data) - 1
# - determine the bin-edges
bin_edges = np.unique(np.sort(data)[idx])
else:
raise IOError('Unknown option')
# remove empty starting and ending bin (related to an unfortunate choice of bin-edges)
if remove_empty_edges:
N, _ = np.histogram(data, bins=bin_edges, density=False)
idx = np.min(np.where(N>0)[0])
jdx = np.max(np.where(N>0)[0])
bin_edges = bin_edges[(idx):(jdx+2)]
# merge bins with too few data-points (if needed)
bin_edges = histogram_bin_edges_mincount(data, min_count=min_count, bins=bin_edges)
# merge bins that have too small of a width
bin_edges = histogram_bin_edges_minwidth(min_width=min_width, bins=bin_edges)
# select only bins that encompass an integer (and retain the original bounds)
if integer:
idx = np.where(np.diff(np.floor(bin_edges))>=1)[0]
idx = np.unique(np.hstack((0, idx, len(bin_edges)-1)))
bin_edges = bin_edges[idx]
# return
return bin_edges | def function[histogram_bin_edges, parameter[data, bins, mode, min_count, integer, remove_empty_edges, min_width]]:
constant[
Determine bin-edges.
:arguments:
**data** (``<array_like>``)
Input data. The histogram is computed over the flattened array.
:options:
**bins** ([``10``] | ``<int>``)
The number of bins.
**mode** ([``'equal'`` | ``<str>``)
Mode with which to compute the bin-edges:
* ``'equal'``: each bin has equal width.
* ``'log'``: logarithmic spacing.
* ``'uniform'``: uniform number of data-points per bin.
**min_count** (``<int>``)
The minimum number of data-points per bin.
**min_width** (``<float>``)
The minimum width of each bin.
**integer** ([``False``] | [``True``])
If ``True``, bins not encompassing an integer are removed
(e.g. a bin with edges ``[1.1, 1.9]`` is removed, but ``[0.9, 1.1]`` is not removed).
**remove_empty_edges** ([``True``] | [``False``])
Remove empty bins at the beginning or the end.
:returns:
**bin_edges** (``<array of dtype float>``)
The edges to pass into histogram.
]
if compare[name[mode] equal[==] constant[equal]] begin[:]
variable[bin_edges] assign[=] call[name[np].linspace, parameter[call[name[np].min, parameter[name[data]]], call[name[np].max, parameter[name[data]]], binary_operation[name[bins] + constant[1]]]]
if name[remove_empty_edges] begin[:]
<ast.Tuple object at 0x7da1b1f7d000> assign[=] call[name[np].histogram, parameter[name[data]]]
variable[idx] assign[=] call[name[np].min, parameter[call[call[name[np].where, parameter[compare[name[N] greater[>] constant[0]]]]][constant[0]]]]
variable[jdx] assign[=] call[name[np].max, parameter[call[call[name[np].where, parameter[compare[name[N] greater[>] constant[0]]]]][constant[0]]]]
variable[bin_edges] assign[=] call[name[bin_edges]][<ast.Slice object at 0x7da18f09e860>]
variable[bin_edges] assign[=] call[name[histogram_bin_edges_mincount], parameter[name[data]]]
variable[bin_edges] assign[=] call[name[histogram_bin_edges_minwidth], parameter[]]
if name[integer] begin[:]
variable[idx] assign[=] call[call[name[np].where, parameter[compare[call[name[np].diff, parameter[call[name[np].floor, parameter[name[bin_edges]]]]] greater_or_equal[>=] constant[1]]]]][constant[0]]
variable[idx] assign[=] call[name[np].unique, parameter[call[name[np].hstack, parameter[tuple[[<ast.Constant object at 0x7da18f09c880>, <ast.Name object at 0x7da18f09f790>, <ast.BinOp object at 0x7da18f09fdc0>]]]]]]
variable[bin_edges] assign[=] call[name[bin_edges]][name[idx]]
return[name[bin_edges]] | keyword[def] identifier[histogram_bin_edges] ( identifier[data] , identifier[bins] = literal[int] , identifier[mode] = literal[string] , identifier[min_count] = keyword[None] , identifier[integer] = keyword[False] , identifier[remove_empty_edges] = keyword[True] , identifier[min_width] = keyword[None] ):
literal[string]
keyword[if] identifier[mode] == literal[string] :
identifier[bin_edges] = identifier[np] . identifier[linspace] ( identifier[np] . identifier[min] ( identifier[data] ), identifier[np] . identifier[max] ( identifier[data] ), identifier[bins] + literal[int] )
keyword[elif] identifier[mode] == literal[string] :
identifier[bin_edges] = identifier[np] . identifier[logspace] ( identifier[np] . identifier[log10] ( identifier[np] . identifier[min] ( identifier[data] )), identifier[np] . identifier[log10] ( identifier[np] . identifier[max] ( identifier[data] )), identifier[bins] + literal[int] )
keyword[elif] identifier[mode] == literal[string] :
keyword[if] identifier[hasattr] ( identifier[bins] , literal[string] ):
keyword[raise] identifier[IOError] ( literal[string] )
keyword[if] identifier[min_count] keyword[is] keyword[not] keyword[None] keyword[and] identifier[min_count] keyword[is] keyword[not] keyword[False] :
keyword[if] identifier[type] ( identifier[min_count] )!= identifier[int] : keyword[raise] identifier[IOError] ( literal[string] )
identifier[bins] = identifier[int] ( identifier[np] . identifier[floor] ( identifier[float] ( identifier[len] ( identifier[data] ))/ identifier[float] ( identifier[min_count] )))
identifier[count] = identifier[int] ( identifier[np] . identifier[floor] ( identifier[float] ( identifier[len] ( identifier[data] ))/ identifier[float] ( identifier[bins] )))* identifier[np] . identifier[ones] ( identifier[bins] , identifier[dtype] = literal[string] )
identifier[count] [ identifier[np] . identifier[linspace] ( literal[int] , identifier[bins] - literal[int] , identifier[len] ( identifier[data] )- identifier[np] . identifier[sum] ( identifier[count] )). identifier[astype] ( identifier[np] . identifier[int] )]+= literal[int]
identifier[idx] = identifier[np] . identifier[empty] (( identifier[bins] + literal[int] ), identifier[dtype] = literal[string] )
identifier[idx] [ literal[int] ]= literal[int]
identifier[idx] [ literal[int] :]= identifier[np] . identifier[cumsum] ( identifier[count] )
identifier[idx] [- literal[int] ]= identifier[len] ( identifier[data] )- literal[int]
identifier[bin_edges] = identifier[np] . identifier[unique] ( identifier[np] . identifier[sort] ( identifier[data] )[ identifier[idx] ])
keyword[else] :
keyword[raise] identifier[IOError] ( literal[string] )
keyword[if] identifier[remove_empty_edges] :
identifier[N] , identifier[_] = identifier[np] . identifier[histogram] ( identifier[data] , identifier[bins] = identifier[bin_edges] , identifier[density] = keyword[False] )
identifier[idx] = identifier[np] . identifier[min] ( identifier[np] . identifier[where] ( identifier[N] > literal[int] )[ literal[int] ])
identifier[jdx] = identifier[np] . identifier[max] ( identifier[np] . identifier[where] ( identifier[N] > literal[int] )[ literal[int] ])
identifier[bin_edges] = identifier[bin_edges] [( identifier[idx] ):( identifier[jdx] + literal[int] )]
identifier[bin_edges] = identifier[histogram_bin_edges_mincount] ( identifier[data] , identifier[min_count] = identifier[min_count] , identifier[bins] = identifier[bin_edges] )
identifier[bin_edges] = identifier[histogram_bin_edges_minwidth] ( identifier[min_width] = identifier[min_width] , identifier[bins] = identifier[bin_edges] )
keyword[if] identifier[integer] :
identifier[idx] = identifier[np] . identifier[where] ( identifier[np] . identifier[diff] ( identifier[np] . identifier[floor] ( identifier[bin_edges] ))>= literal[int] )[ literal[int] ]
identifier[idx] = identifier[np] . identifier[unique] ( identifier[np] . identifier[hstack] (( literal[int] , identifier[idx] , identifier[len] ( identifier[bin_edges] )- literal[int] )))
identifier[bin_edges] = identifier[bin_edges] [ identifier[idx] ]
keyword[return] identifier[bin_edges] | def histogram_bin_edges(data, bins=10, mode='equal', min_count=None, integer=False, remove_empty_edges=True, min_width=None):
"""
Determine bin-edges.
:arguments:
**data** (``<array_like>``)
Input data. The histogram is computed over the flattened array.
:options:
**bins** ([``10``] | ``<int>``)
The number of bins.
**mode** ([``'equal'`` | ``<str>``)
Mode with which to compute the bin-edges:
* ``'equal'``: each bin has equal width.
* ``'log'``: logarithmic spacing.
* ``'uniform'``: uniform number of data-points per bin.
**min_count** (``<int>``)
The minimum number of data-points per bin.
**min_width** (``<float>``)
The minimum width of each bin.
**integer** ([``False``] | [``True``])
If ``True``, bins not encompassing an integer are removed
(e.g. a bin with edges ``[1.1, 1.9]`` is removed, but ``[0.9, 1.1]`` is not removed).
**remove_empty_edges** ([``True``] | [``False``])
Remove empty bins at the beginning or the end.
:returns:
**bin_edges** (``<array of dtype float>``)
The edges to pass into histogram.
"""
# determine the bin-edges
if mode == 'equal':
bin_edges = np.linspace(np.min(data), np.max(data), bins + 1) # depends on [control=['if'], data=[]]
elif mode == 'log':
bin_edges = np.logspace(np.log10(np.min(data)), np.log10(np.max(data)), bins + 1) # depends on [control=['if'], data=[]]
elif mode == 'uniform':
# - check
if hasattr(bins, '__len__'):
raise IOError('Only the number of bins can be specified') # depends on [control=['if'], data=[]]
# - use the minimum count to estimate the number of bins
if min_count is not None and min_count is not False:
if type(min_count) != int:
raise IOError('"min_count" must be an integer number') # depends on [control=['if'], data=[]]
bins = int(np.floor(float(len(data)) / float(min_count))) # depends on [control=['if'], data=[]]
# - number of data-points in each bin (equal for each)
count = int(np.floor(float(len(data)) / float(bins))) * np.ones(bins, dtype='int')
# - increase the number of data-points by one is an many bins as needed,
# such that the total fits the total number of data-points
count[np.linspace(0, bins - 1, len(data) - np.sum(count)).astype(np.int)] += 1
# - split the data
idx = np.empty(bins + 1, dtype='int')
idx[0] = 0
idx[1:] = np.cumsum(count)
idx[-1] = len(data) - 1
# - determine the bin-edges
bin_edges = np.unique(np.sort(data)[idx]) # depends on [control=['if'], data=[]]
else:
raise IOError('Unknown option')
# remove empty starting and ending bin (related to an unfortunate choice of bin-edges)
if remove_empty_edges:
(N, _) = np.histogram(data, bins=bin_edges, density=False)
idx = np.min(np.where(N > 0)[0])
jdx = np.max(np.where(N > 0)[0])
bin_edges = bin_edges[idx:jdx + 2] # depends on [control=['if'], data=[]]
# merge bins with too few data-points (if needed)
bin_edges = histogram_bin_edges_mincount(data, min_count=min_count, bins=bin_edges)
# merge bins that have too small of a width
bin_edges = histogram_bin_edges_minwidth(min_width=min_width, bins=bin_edges)
# select only bins that encompass an integer (and retain the original bounds)
if integer:
idx = np.where(np.diff(np.floor(bin_edges)) >= 1)[0]
idx = np.unique(np.hstack((0, idx, len(bin_edges) - 1)))
bin_edges = bin_edges[idx] # depends on [control=['if'], data=[]]
# return
return bin_edges |
def dedup(stack: tuple) -> tuple:
'''Remove duplicates from the stack in first-seen order.'''
# Initializes with an accumulator and then reduces the stack with first match
# deduplication.
reducer = lambda x, y: x if y in x else x + (y,)
return reduce(reducer, stack, tuple()) | def function[dedup, parameter[stack]]:
constant[Remove duplicates from the stack in first-seen order.]
variable[reducer] assign[=] <ast.Lambda object at 0x7da1b024ed40>
return[call[name[reduce], parameter[name[reducer], name[stack], call[name[tuple], parameter[]]]]] | keyword[def] identifier[dedup] ( identifier[stack] : identifier[tuple] )-> identifier[tuple] :
literal[string]
identifier[reducer] = keyword[lambda] identifier[x] , identifier[y] : identifier[x] keyword[if] identifier[y] keyword[in] identifier[x] keyword[else] identifier[x] +( identifier[y] ,)
keyword[return] identifier[reduce] ( identifier[reducer] , identifier[stack] , identifier[tuple] ()) | def dedup(stack: tuple) -> tuple:
"""Remove duplicates from the stack in first-seen order."""
# Initializes with an accumulator and then reduces the stack with first match
# deduplication.
reducer = lambda x, y: x if y in x else x + (y,)
return reduce(reducer, stack, tuple()) |
def bunkers_storm_motion(pressure, u, v, heights):
r"""Calculate the Bunkers right-mover and left-mover storm motions and sfc-6km mean flow.
Uses the storm motion calculation from [Bunkers2000]_.
Parameters
----------
pressure : array-like
Pressure from sounding
u : array-like
U component of the wind
v : array-like
V component of the wind
heights : array-like
Heights from sounding
Returns
-------
right_mover: `pint.Quantity`
U and v component of Bunkers RM storm motion
left_mover: `pint.Quantity`
U and v component of Bunkers LM storm motion
wind_mean: `pint.Quantity`
U and v component of sfc-6km mean flow
"""
# mean wind from sfc-6km
wind_mean = concatenate(mean_pressure_weighted(pressure, u, v, heights=heights,
depth=6000 * units('meter')))
# mean wind from sfc-500m
wind_500m = concatenate(mean_pressure_weighted(pressure, u, v, heights=heights,
depth=500 * units('meter')))
# mean wind from 5.5-6km
wind_5500m = concatenate(mean_pressure_weighted(pressure, u, v, heights=heights,
depth=500 * units('meter'),
bottom=heights[0] + 5500 * units('meter')))
# Calculate the shear vector from sfc-500m to 5.5-6km
shear = wind_5500m - wind_500m
# Take the cross product of the wind shear and k, and divide by the vector magnitude and
# multiply by the deviaton empirically calculated in Bunkers (2000) (7.5 m/s)
shear_cross = concatenate([shear[1], -shear[0]])
rdev = shear_cross * (7.5 * units('m/s').to(u.units) / np.hypot(*shear))
# Add the deviations to the layer average wind to get the RM motion
right_mover = wind_mean + rdev
# Subtract the deviations to get the LM motion
left_mover = wind_mean - rdev
return right_mover, left_mover, wind_mean | def function[bunkers_storm_motion, parameter[pressure, u, v, heights]]:
constant[Calculate the Bunkers right-mover and left-mover storm motions and sfc-6km mean flow.
Uses the storm motion calculation from [Bunkers2000]_.
Parameters
----------
pressure : array-like
Pressure from sounding
u : array-like
U component of the wind
v : array-like
V component of the wind
heights : array-like
Heights from sounding
Returns
-------
right_mover: `pint.Quantity`
U and v component of Bunkers RM storm motion
left_mover: `pint.Quantity`
U and v component of Bunkers LM storm motion
wind_mean: `pint.Quantity`
U and v component of sfc-6km mean flow
]
variable[wind_mean] assign[=] call[name[concatenate], parameter[call[name[mean_pressure_weighted], parameter[name[pressure], name[u], name[v]]]]]
variable[wind_500m] assign[=] call[name[concatenate], parameter[call[name[mean_pressure_weighted], parameter[name[pressure], name[u], name[v]]]]]
variable[wind_5500m] assign[=] call[name[concatenate], parameter[call[name[mean_pressure_weighted], parameter[name[pressure], name[u], name[v]]]]]
variable[shear] assign[=] binary_operation[name[wind_5500m] - name[wind_500m]]
variable[shear_cross] assign[=] call[name[concatenate], parameter[list[[<ast.Subscript object at 0x7da1b22b8280>, <ast.UnaryOp object at 0x7da1b22bb820>]]]]
variable[rdev] assign[=] binary_operation[name[shear_cross] * binary_operation[binary_operation[constant[7.5] * call[call[name[units], parameter[constant[m/s]]].to, parameter[name[u].units]]] / call[name[np].hypot, parameter[<ast.Starred object at 0x7da1b22bac50>]]]]
variable[right_mover] assign[=] binary_operation[name[wind_mean] + name[rdev]]
variable[left_mover] assign[=] binary_operation[name[wind_mean] - name[rdev]]
return[tuple[[<ast.Name object at 0x7da1b22bae90>, <ast.Name object at 0x7da1b22ba6b0>, <ast.Name object at 0x7da1b22b95d0>]]] | keyword[def] identifier[bunkers_storm_motion] ( identifier[pressure] , identifier[u] , identifier[v] , identifier[heights] ):
literal[string]
identifier[wind_mean] = identifier[concatenate] ( identifier[mean_pressure_weighted] ( identifier[pressure] , identifier[u] , identifier[v] , identifier[heights] = identifier[heights] ,
identifier[depth] = literal[int] * identifier[units] ( literal[string] )))
identifier[wind_500m] = identifier[concatenate] ( identifier[mean_pressure_weighted] ( identifier[pressure] , identifier[u] , identifier[v] , identifier[heights] = identifier[heights] ,
identifier[depth] = literal[int] * identifier[units] ( literal[string] )))
identifier[wind_5500m] = identifier[concatenate] ( identifier[mean_pressure_weighted] ( identifier[pressure] , identifier[u] , identifier[v] , identifier[heights] = identifier[heights] ,
identifier[depth] = literal[int] * identifier[units] ( literal[string] ),
identifier[bottom] = identifier[heights] [ literal[int] ]+ literal[int] * identifier[units] ( literal[string] )))
identifier[shear] = identifier[wind_5500m] - identifier[wind_500m]
identifier[shear_cross] = identifier[concatenate] ([ identifier[shear] [ literal[int] ],- identifier[shear] [ literal[int] ]])
identifier[rdev] = identifier[shear_cross] *( literal[int] * identifier[units] ( literal[string] ). identifier[to] ( identifier[u] . identifier[units] )/ identifier[np] . identifier[hypot] (* identifier[shear] ))
identifier[right_mover] = identifier[wind_mean] + identifier[rdev]
identifier[left_mover] = identifier[wind_mean] - identifier[rdev]
keyword[return] identifier[right_mover] , identifier[left_mover] , identifier[wind_mean] | def bunkers_storm_motion(pressure, u, v, heights):
"""Calculate the Bunkers right-mover and left-mover storm motions and sfc-6km mean flow.
Uses the storm motion calculation from [Bunkers2000]_.
Parameters
----------
pressure : array-like
Pressure from sounding
u : array-like
U component of the wind
v : array-like
V component of the wind
heights : array-like
Heights from sounding
Returns
-------
right_mover: `pint.Quantity`
U and v component of Bunkers RM storm motion
left_mover: `pint.Quantity`
U and v component of Bunkers LM storm motion
wind_mean: `pint.Quantity`
U and v component of sfc-6km mean flow
"""
# mean wind from sfc-6km
wind_mean = concatenate(mean_pressure_weighted(pressure, u, v, heights=heights, depth=6000 * units('meter')))
# mean wind from sfc-500m
wind_500m = concatenate(mean_pressure_weighted(pressure, u, v, heights=heights, depth=500 * units('meter')))
# mean wind from 5.5-6km
wind_5500m = concatenate(mean_pressure_weighted(pressure, u, v, heights=heights, depth=500 * units('meter'), bottom=heights[0] + 5500 * units('meter')))
# Calculate the shear vector from sfc-500m to 5.5-6km
shear = wind_5500m - wind_500m
# Take the cross product of the wind shear and k, and divide by the vector magnitude and
# multiply by the deviaton empirically calculated in Bunkers (2000) (7.5 m/s)
shear_cross = concatenate([shear[1], -shear[0]])
rdev = shear_cross * (7.5 * units('m/s').to(u.units) / np.hypot(*shear))
# Add the deviations to the layer average wind to get the RM motion
right_mover = wind_mean + rdev
# Subtract the deviations to get the LM motion
left_mover = wind_mean - rdev
return (right_mover, left_mover, wind_mean) |
def indices_separate(self, points, dist_tolerance):
"""
Returns three lists containing the indices of the points lying on one side of the plane, on the plane
and on the other side of the plane. The dist_tolerance parameter controls the tolerance to which a point
is considered to lie on the plane or not (distance to the plane)
:param points: list of points
:param dist_tolerance: tolerance to which a point is considered to lie on the plane
or not (distance to the plane)
:return: The lists of indices of the points on one side of the plane, on the plane and
on the other side of the plane
"""
side1 = list()
inplane = list()
side2 = list()
for ip, pp in enumerate(points):
if self.is_in_plane(pp, dist_tolerance):
inplane.append(ip)
else:
if np.dot(pp + self.vector_to_origin, self.normal_vector) < 0.0:
side1.append(ip)
else:
side2.append(ip)
return [side1, inplane, side2] | def function[indices_separate, parameter[self, points, dist_tolerance]]:
constant[
Returns three lists containing the indices of the points lying on one side of the plane, on the plane
and on the other side of the plane. The dist_tolerance parameter controls the tolerance to which a point
is considered to lie on the plane or not (distance to the plane)
:param points: list of points
:param dist_tolerance: tolerance to which a point is considered to lie on the plane
or not (distance to the plane)
:return: The lists of indices of the points on one side of the plane, on the plane and
on the other side of the plane
]
variable[side1] assign[=] call[name[list], parameter[]]
variable[inplane] assign[=] call[name[list], parameter[]]
variable[side2] assign[=] call[name[list], parameter[]]
for taget[tuple[[<ast.Name object at 0x7da2041dbd00>, <ast.Name object at 0x7da2041d8a90>]]] in starred[call[name[enumerate], parameter[name[points]]]] begin[:]
if call[name[self].is_in_plane, parameter[name[pp], name[dist_tolerance]]] begin[:]
call[name[inplane].append, parameter[name[ip]]]
return[list[[<ast.Name object at 0x7da2041d8d90>, <ast.Name object at 0x7da2041d93c0>, <ast.Name object at 0x7da2041d8190>]]] | keyword[def] identifier[indices_separate] ( identifier[self] , identifier[points] , identifier[dist_tolerance] ):
literal[string]
identifier[side1] = identifier[list] ()
identifier[inplane] = identifier[list] ()
identifier[side2] = identifier[list] ()
keyword[for] identifier[ip] , identifier[pp] keyword[in] identifier[enumerate] ( identifier[points] ):
keyword[if] identifier[self] . identifier[is_in_plane] ( identifier[pp] , identifier[dist_tolerance] ):
identifier[inplane] . identifier[append] ( identifier[ip] )
keyword[else] :
keyword[if] identifier[np] . identifier[dot] ( identifier[pp] + identifier[self] . identifier[vector_to_origin] , identifier[self] . identifier[normal_vector] )< literal[int] :
identifier[side1] . identifier[append] ( identifier[ip] )
keyword[else] :
identifier[side2] . identifier[append] ( identifier[ip] )
keyword[return] [ identifier[side1] , identifier[inplane] , identifier[side2] ] | def indices_separate(self, points, dist_tolerance):
"""
Returns three lists containing the indices of the points lying on one side of the plane, on the plane
and on the other side of the plane. The dist_tolerance parameter controls the tolerance to which a point
is considered to lie on the plane or not (distance to the plane)
:param points: list of points
:param dist_tolerance: tolerance to which a point is considered to lie on the plane
or not (distance to the plane)
:return: The lists of indices of the points on one side of the plane, on the plane and
on the other side of the plane
"""
side1 = list()
inplane = list()
side2 = list()
for (ip, pp) in enumerate(points):
if self.is_in_plane(pp, dist_tolerance):
inplane.append(ip) # depends on [control=['if'], data=[]]
elif np.dot(pp + self.vector_to_origin, self.normal_vector) < 0.0:
side1.append(ip) # depends on [control=['if'], data=[]]
else:
side2.append(ip) # depends on [control=['for'], data=[]]
return [side1, inplane, side2] |
def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid"""
# only returns true for ecaxtly one set of new_relations from all the
# ones that are symmetrically equivalent
if not (self.criteria_sets is None or one_match):
for check in self.duplicate_checks:
vertex_a = new_relations.get(check[0])
vertex_b = new_relations.get(check[1])
if vertex_a is None and vertex_b is None:
continue # if this pair is completely absent in the new
# relations, it is either completely in the match or it
# is to be matched. So it is either already checked for
# symmetry duplicates, or it will be check in future.
if vertex_a is None:
# maybe vertex_a is in the match and vertex_b is the only
# one in the new relations. try to get vertex_a from the
# match.
vertex_a = match.forward.get(check[0])
if vertex_a is None:
# ok, vertex_a is to be found, don't care about it right
# now. it will be checked in future calls.
continue
elif vertex_b is None:
# maybe vertex_b is in the match and vertex_a is the only
# one in the new relations. try to get vertex_b from the
# match.
vertex_b = match.forward.get(check[1])
if vertex_b is None:
# ok, vertex_b is to be found, don't care about it right
# now. it will be checked in future calls.
continue
if vertex_a > vertex_b:
# Why does this work? The answer is not so easy to explain,
# and certainly not easy to find. if vertex_a > vertex_b, it
# means that there is a symmetry operation that leads to
# an equivalent match where vertex_b < vertex_a. The latter
# match is preferred for as much pairs (vertex_a, vertex_b)
# as possible without rejecting all possible matches. The
# real difficulty is to construct a proper list of
# (vertex_a, vertex_b) pairs that will reject all but one
# matches. I conjecture that this list contains all the
# first two vertices from each normalized symmetry cycle of
# the pattern graph. We need a math guy to do the proof. -- Toon
return False
return True
return True | def function[check_next_match, parameter[self, match, new_relations, subject_graph, one_match]]:
constant[Check if the (onset for a) match can be a valid]
if <ast.UnaryOp object at 0x7da207f01330> begin[:]
for taget[name[check]] in starred[name[self].duplicate_checks] begin[:]
variable[vertex_a] assign[=] call[name[new_relations].get, parameter[call[name[check]][constant[0]]]]
variable[vertex_b] assign[=] call[name[new_relations].get, parameter[call[name[check]][constant[1]]]]
if <ast.BoolOp object at 0x7da207f00220> begin[:]
continue
if compare[name[vertex_a] is constant[None]] begin[:]
variable[vertex_a] assign[=] call[name[match].forward.get, parameter[call[name[check]][constant[0]]]]
if compare[name[vertex_a] is constant[None]] begin[:]
continue
if compare[name[vertex_a] greater[>] name[vertex_b]] begin[:]
return[constant[False]]
return[constant[True]]
return[constant[True]] | keyword[def] identifier[check_next_match] ( identifier[self] , identifier[match] , identifier[new_relations] , identifier[subject_graph] , identifier[one_match] ):
literal[string]
keyword[if] keyword[not] ( identifier[self] . identifier[criteria_sets] keyword[is] keyword[None] keyword[or] identifier[one_match] ):
keyword[for] identifier[check] keyword[in] identifier[self] . identifier[duplicate_checks] :
identifier[vertex_a] = identifier[new_relations] . identifier[get] ( identifier[check] [ literal[int] ])
identifier[vertex_b] = identifier[new_relations] . identifier[get] ( identifier[check] [ literal[int] ])
keyword[if] identifier[vertex_a] keyword[is] keyword[None] keyword[and] identifier[vertex_b] keyword[is] keyword[None] :
keyword[continue]
keyword[if] identifier[vertex_a] keyword[is] keyword[None] :
identifier[vertex_a] = identifier[match] . identifier[forward] . identifier[get] ( identifier[check] [ literal[int] ])
keyword[if] identifier[vertex_a] keyword[is] keyword[None] :
keyword[continue]
keyword[elif] identifier[vertex_b] keyword[is] keyword[None] :
identifier[vertex_b] = identifier[match] . identifier[forward] . identifier[get] ( identifier[check] [ literal[int] ])
keyword[if] identifier[vertex_b] keyword[is] keyword[None] :
keyword[continue]
keyword[if] identifier[vertex_a] > identifier[vertex_b] :
keyword[return] keyword[False]
keyword[return] keyword[True]
keyword[return] keyword[True] | def check_next_match(self, match, new_relations, subject_graph, one_match):
"""Check if the (onset for a) match can be a valid"""
# only returns true for ecaxtly one set of new_relations from all the
# ones that are symmetrically equivalent
if not (self.criteria_sets is None or one_match):
for check in self.duplicate_checks:
vertex_a = new_relations.get(check[0])
vertex_b = new_relations.get(check[1])
if vertex_a is None and vertex_b is None:
continue # if this pair is completely absent in the new # depends on [control=['if'], data=[]]
# relations, it is either completely in the match or it
# is to be matched. So it is either already checked for
# symmetry duplicates, or it will be check in future.
if vertex_a is None:
# maybe vertex_a is in the match and vertex_b is the only
# one in the new relations. try to get vertex_a from the
# match.
vertex_a = match.forward.get(check[0])
if vertex_a is None:
# ok, vertex_a is to be found, don't care about it right
# now. it will be checked in future calls.
continue # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['vertex_a']]
elif vertex_b is None:
# maybe vertex_b is in the match and vertex_a is the only
# one in the new relations. try to get vertex_b from the
# match.
vertex_b = match.forward.get(check[1])
if vertex_b is None:
# ok, vertex_b is to be found, don't care about it right
# now. it will be checked in future calls.
continue # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['vertex_b']]
if vertex_a > vertex_b:
# Why does this work? The answer is not so easy to explain,
# and certainly not easy to find. if vertex_a > vertex_b, it
# means that there is a symmetry operation that leads to
# an equivalent match where vertex_b < vertex_a. The latter
# match is preferred for as much pairs (vertex_a, vertex_b)
# as possible without rejecting all possible matches. The
# real difficulty is to construct a proper list of
# (vertex_a, vertex_b) pairs that will reject all but one
# matches. I conjecture that this list contains all the
# first two vertices from each normalized symmetry cycle of
# the pattern graph. We need a math guy to do the proof. -- Toon
return False # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['check']]
return True # depends on [control=['if'], data=[]]
return True |
def unpause_tube(self, tube):
"""Unpause a tube which was previously paused with :func:`pause_tube()`.
.. seealso::
:func:`pause_tube()`
"""
with self._sock_ctx() as socket:
self._send_message('pause-tube {0} 0'.format(tube), socket)
return self._receive_word(socket, b'PAUSED') | def function[unpause_tube, parameter[self, tube]]:
constant[Unpause a tube which was previously paused with :func:`pause_tube()`.
.. seealso::
:func:`pause_tube()`
]
with call[name[self]._sock_ctx, parameter[]] begin[:]
call[name[self]._send_message, parameter[call[constant[pause-tube {0} 0].format, parameter[name[tube]]], name[socket]]]
return[call[name[self]._receive_word, parameter[name[socket], constant[b'PAUSED']]]] | keyword[def] identifier[unpause_tube] ( identifier[self] , identifier[tube] ):
literal[string]
keyword[with] identifier[self] . identifier[_sock_ctx] () keyword[as] identifier[socket] :
identifier[self] . identifier[_send_message] ( literal[string] . identifier[format] ( identifier[tube] ), identifier[socket] )
keyword[return] identifier[self] . identifier[_receive_word] ( identifier[socket] , literal[string] ) | def unpause_tube(self, tube):
"""Unpause a tube which was previously paused with :func:`pause_tube()`.
.. seealso::
:func:`pause_tube()`
"""
with self._sock_ctx() as socket:
self._send_message('pause-tube {0} 0'.format(tube), socket)
return self._receive_word(socket, b'PAUSED') # depends on [control=['with'], data=['socket']] |
def wrap(self, image):
"""
Wraps a nested python sequence or PIL/pillow Image.
"""
if hasattr(image, 'size') and hasattr(image, 'convert'):
# Treat image as PIL/pillow Image object
self.width, self.height = image.size
array_type = ctypes.c_ubyte * 4 * (self.width * self.height)
self.pixels_array = array_type()
pixels = image.convert('RGBA').getdata()
for i, pixel in enumerate(pixels):
self.pixels_array[i] = pixel
else:
self.width, self.height, pixels = image
array_type = ctypes.c_ubyte * 4 * self.width * self.height
self.pixels_array = array_type()
for i in range(self.height):
for j in range(self.width):
for k in range(4):
self.pixels_array[i][j][k] = pixels[i][j][k]
pointer_type = ctypes.POINTER(ctypes.c_ubyte)
self.pixels = ctypes.cast(self.pixels_array, pointer_type) | def function[wrap, parameter[self, image]]:
constant[
Wraps a nested python sequence or PIL/pillow Image.
]
if <ast.BoolOp object at 0x7da204566a70> begin[:]
<ast.Tuple object at 0x7da204567c70> assign[=] name[image].size
variable[array_type] assign[=] binary_operation[binary_operation[name[ctypes].c_ubyte * constant[4]] * binary_operation[name[self].width * name[self].height]]
name[self].pixels_array assign[=] call[name[array_type], parameter[]]
variable[pixels] assign[=] call[call[name[image].convert, parameter[constant[RGBA]]].getdata, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da204565570>, <ast.Name object at 0x7da204564580>]]] in starred[call[name[enumerate], parameter[name[pixels]]]] begin[:]
call[name[self].pixels_array][name[i]] assign[=] name[pixel]
variable[pointer_type] assign[=] call[name[ctypes].POINTER, parameter[name[ctypes].c_ubyte]]
name[self].pixels assign[=] call[name[ctypes].cast, parameter[name[self].pixels_array, name[pointer_type]]] | keyword[def] identifier[wrap] ( identifier[self] , identifier[image] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[image] , literal[string] ) keyword[and] identifier[hasattr] ( identifier[image] , literal[string] ):
identifier[self] . identifier[width] , identifier[self] . identifier[height] = identifier[image] . identifier[size]
identifier[array_type] = identifier[ctypes] . identifier[c_ubyte] * literal[int] *( identifier[self] . identifier[width] * identifier[self] . identifier[height] )
identifier[self] . identifier[pixels_array] = identifier[array_type] ()
identifier[pixels] = identifier[image] . identifier[convert] ( literal[string] ). identifier[getdata] ()
keyword[for] identifier[i] , identifier[pixel] keyword[in] identifier[enumerate] ( identifier[pixels] ):
identifier[self] . identifier[pixels_array] [ identifier[i] ]= identifier[pixel]
keyword[else] :
identifier[self] . identifier[width] , identifier[self] . identifier[height] , identifier[pixels] = identifier[image]
identifier[array_type] = identifier[ctypes] . identifier[c_ubyte] * literal[int] * identifier[self] . identifier[width] * identifier[self] . identifier[height]
identifier[self] . identifier[pixels_array] = identifier[array_type] ()
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[height] ):
keyword[for] identifier[j] keyword[in] identifier[range] ( identifier[self] . identifier[width] ):
keyword[for] identifier[k] keyword[in] identifier[range] ( literal[int] ):
identifier[self] . identifier[pixels_array] [ identifier[i] ][ identifier[j] ][ identifier[k] ]= identifier[pixels] [ identifier[i] ][ identifier[j] ][ identifier[k] ]
identifier[pointer_type] = identifier[ctypes] . identifier[POINTER] ( identifier[ctypes] . identifier[c_ubyte] )
identifier[self] . identifier[pixels] = identifier[ctypes] . identifier[cast] ( identifier[self] . identifier[pixels_array] , identifier[pointer_type] ) | def wrap(self, image):
"""
Wraps a nested python sequence or PIL/pillow Image.
"""
if hasattr(image, 'size') and hasattr(image, 'convert'):
# Treat image as PIL/pillow Image object
(self.width, self.height) = image.size
array_type = ctypes.c_ubyte * 4 * (self.width * self.height)
self.pixels_array = array_type()
pixels = image.convert('RGBA').getdata()
for (i, pixel) in enumerate(pixels):
self.pixels_array[i] = pixel # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
else:
(self.width, self.height, pixels) = image
array_type = ctypes.c_ubyte * 4 * self.width * self.height
self.pixels_array = array_type()
for i in range(self.height):
for j in range(self.width):
for k in range(4):
self.pixels_array[i][j][k] = pixels[i][j][k] # depends on [control=['for'], data=['k']] # depends on [control=['for'], data=['j']] # depends on [control=['for'], data=['i']]
pointer_type = ctypes.POINTER(ctypes.c_ubyte)
self.pixels = ctypes.cast(self.pixels_array, pointer_type) |
def check_include_exclude(attributes):
"""Check __include__ and __exclude__ attributes.
:type attributes: dict
"""
include = attributes.get('__include__', tuple())
exclude = attributes.get('__exclude__', tuple())
if not isinstance(include, tuple):
raise TypeError("Attribute __include__ must be a tuple.")
if not isinstance(exclude, tuple):
raise TypeError("Attribute __exclude__ must be a tuple.")
if all((not include, not exclude)):
return None
if all((include, exclude)):
raise AttributeError("Usage of __include__ and __exclude__ "
"at the same time is prohibited.") | def function[check_include_exclude, parameter[attributes]]:
constant[Check __include__ and __exclude__ attributes.
:type attributes: dict
]
variable[include] assign[=] call[name[attributes].get, parameter[constant[__include__], call[name[tuple], parameter[]]]]
variable[exclude] assign[=] call[name[attributes].get, parameter[constant[__exclude__], call[name[tuple], parameter[]]]]
if <ast.UnaryOp object at 0x7da1b246e740> begin[:]
<ast.Raise object at 0x7da1b246f580>
if <ast.UnaryOp object at 0x7da1b246f490> begin[:]
<ast.Raise object at 0x7da1b246f130>
if call[name[all], parameter[tuple[[<ast.UnaryOp object at 0x7da1b246fa90>, <ast.UnaryOp object at 0x7da1b246f3a0>]]]] begin[:]
return[constant[None]]
if call[name[all], parameter[tuple[[<ast.Name object at 0x7da1b246f1c0>, <ast.Name object at 0x7da1b246f190>]]]] begin[:]
<ast.Raise object at 0x7da1b246f160> | keyword[def] identifier[check_include_exclude] ( identifier[attributes] ):
literal[string]
identifier[include] = identifier[attributes] . identifier[get] ( literal[string] , identifier[tuple] ())
identifier[exclude] = identifier[attributes] . identifier[get] ( literal[string] , identifier[tuple] ())
keyword[if] keyword[not] identifier[isinstance] ( identifier[include] , identifier[tuple] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[if] keyword[not] identifier[isinstance] ( identifier[exclude] , identifier[tuple] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[if] identifier[all] (( keyword[not] identifier[include] , keyword[not] identifier[exclude] )):
keyword[return] keyword[None]
keyword[if] identifier[all] (( identifier[include] , identifier[exclude] )):
keyword[raise] identifier[AttributeError] ( literal[string]
literal[string] ) | def check_include_exclude(attributes):
"""Check __include__ and __exclude__ attributes.
:type attributes: dict
"""
include = attributes.get('__include__', tuple())
exclude = attributes.get('__exclude__', tuple())
if not isinstance(include, tuple):
raise TypeError('Attribute __include__ must be a tuple.') # depends on [control=['if'], data=[]]
if not isinstance(exclude, tuple):
raise TypeError('Attribute __exclude__ must be a tuple.') # depends on [control=['if'], data=[]]
if all((not include, not exclude)):
return None # depends on [control=['if'], data=[]]
if all((include, exclude)):
raise AttributeError('Usage of __include__ and __exclude__ at the same time is prohibited.') # depends on [control=['if'], data=[]] |
def stopDtmfAcknowledge():
"""STOP DTMF ACKNOWLEDGE Section 9.3.30"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x32) # 00110010
packet = a / b
return packet | def function[stopDtmfAcknowledge, parameter[]]:
constant[STOP DTMF ACKNOWLEDGE Section 9.3.30]
variable[a] assign[=] call[name[TpPd], parameter[]]
variable[b] assign[=] call[name[MessageType], parameter[]]
variable[packet] assign[=] binary_operation[name[a] / name[b]]
return[name[packet]] | keyword[def] identifier[stopDtmfAcknowledge] ():
literal[string]
identifier[a] = identifier[TpPd] ( identifier[pd] = literal[int] )
identifier[b] = identifier[MessageType] ( identifier[mesType] = literal[int] )
identifier[packet] = identifier[a] / identifier[b]
keyword[return] identifier[packet] | def stopDtmfAcknowledge():
"""STOP DTMF ACKNOWLEDGE Section 9.3.30"""
a = TpPd(pd=3)
b = MessageType(mesType=50) # 00110010
packet = a / b
return packet |
def p_select_from_statement_1(self, p):
'''
statement : SELECT ANY variable_name FROM INSTANCES OF identifier
| SELECT MANY variable_name FROM INSTANCES OF identifier
'''
p[0] = SelectFromNode(cardinality=p[2],
variable_name=p[3],
key_letter=p[7]) | def function[p_select_from_statement_1, parameter[self, p]]:
constant[
statement : SELECT ANY variable_name FROM INSTANCES OF identifier
| SELECT MANY variable_name FROM INSTANCES OF identifier
]
call[name[p]][constant[0]] assign[=] call[name[SelectFromNode], parameter[]] | keyword[def] identifier[p_select_from_statement_1] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[SelectFromNode] ( identifier[cardinality] = identifier[p] [ literal[int] ],
identifier[variable_name] = identifier[p] [ literal[int] ],
identifier[key_letter] = identifier[p] [ literal[int] ]) | def p_select_from_statement_1(self, p):
"""
statement : SELECT ANY variable_name FROM INSTANCES OF identifier
| SELECT MANY variable_name FROM INSTANCES OF identifier
"""
p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], key_letter=p[7]) |
def set_tunnel(self, host, port=None, headers=None):
''' Sets up the host and the port for the HTTP CONNECT Tunnelling. '''
self._httprequest.set_tunnel(unicode(host), unicode(str(port))) | def function[set_tunnel, parameter[self, host, port, headers]]:
constant[ Sets up the host and the port for the HTTP CONNECT Tunnelling. ]
call[name[self]._httprequest.set_tunnel, parameter[call[name[unicode], parameter[name[host]]], call[name[unicode], parameter[call[name[str], parameter[name[port]]]]]]] | keyword[def] identifier[set_tunnel] ( identifier[self] , identifier[host] , identifier[port] = keyword[None] , identifier[headers] = keyword[None] ):
literal[string]
identifier[self] . identifier[_httprequest] . identifier[set_tunnel] ( identifier[unicode] ( identifier[host] ), identifier[unicode] ( identifier[str] ( identifier[port] ))) | def set_tunnel(self, host, port=None, headers=None):
""" Sets up the host and the port for the HTTP CONNECT Tunnelling. """
self._httprequest.set_tunnel(unicode(host), unicode(str(port))) |
def valid_path(value):
"Validate a cookie path ASCII string"
# Generate UnicodeDecodeError if path can't store as ASCII.
value.encode("ascii")
# Cookies without leading slash will likely be ignored, raise ASAP.
if not (value and value[0] == "/"):
return False
if not Definitions.PATH_RE.match(value):
return False
return True | def function[valid_path, parameter[value]]:
constant[Validate a cookie path ASCII string]
call[name[value].encode, parameter[constant[ascii]]]
if <ast.UnaryOp object at 0x7da1b0534f40> begin[:]
return[constant[False]]
if <ast.UnaryOp object at 0x7da1b0536bf0> begin[:]
return[constant[False]]
return[constant[True]] | keyword[def] identifier[valid_path] ( identifier[value] ):
literal[string]
identifier[value] . identifier[encode] ( literal[string] )
keyword[if] keyword[not] ( identifier[value] keyword[and] identifier[value] [ literal[int] ]== literal[string] ):
keyword[return] keyword[False]
keyword[if] keyword[not] identifier[Definitions] . identifier[PATH_RE] . identifier[match] ( identifier[value] ):
keyword[return] keyword[False]
keyword[return] keyword[True] | def valid_path(value):
"""Validate a cookie path ASCII string"""
# Generate UnicodeDecodeError if path can't store as ASCII.
value.encode('ascii')
# Cookies without leading slash will likely be ignored, raise ASAP.
if not (value and value[0] == '/'):
return False # depends on [control=['if'], data=[]]
if not Definitions.PATH_RE.match(value):
return False # depends on [control=['if'], data=[]]
return True |
def fillkeys(Recs):
"""
reconciles keys of dictionaries within Recs.
"""
keylist, OutRecs = [], []
for rec in Recs:
for key in list(rec.keys()):
if key not in keylist:
keylist.append(key)
for rec in Recs:
for key in keylist:
if key not in list(rec.keys()):
rec[key] = ""
OutRecs.append(rec)
return OutRecs, keylist | def function[fillkeys, parameter[Recs]]:
constant[
reconciles keys of dictionaries within Recs.
]
<ast.Tuple object at 0x7da1b047b1f0> assign[=] tuple[[<ast.List object at 0x7da1b047a260>, <ast.List object at 0x7da1b04799c0>]]
for taget[name[rec]] in starred[name[Recs]] begin[:]
for taget[name[key]] in starred[call[name[list], parameter[call[name[rec].keys, parameter[]]]]] begin[:]
if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[keylist]] begin[:]
call[name[keylist].append, parameter[name[key]]]
for taget[name[rec]] in starred[name[Recs]] begin[:]
for taget[name[key]] in starred[name[keylist]] begin[:]
if compare[name[key] <ast.NotIn object at 0x7da2590d7190> call[name[list], parameter[call[name[rec].keys, parameter[]]]]] begin[:]
call[name[rec]][name[key]] assign[=] constant[]
call[name[OutRecs].append, parameter[name[rec]]]
return[tuple[[<ast.Name object at 0x7da1b047afb0>, <ast.Name object at 0x7da1b0479b40>]]] | keyword[def] identifier[fillkeys] ( identifier[Recs] ):
literal[string]
identifier[keylist] , identifier[OutRecs] =[],[]
keyword[for] identifier[rec] keyword[in] identifier[Recs] :
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[rec] . identifier[keys] ()):
keyword[if] identifier[key] keyword[not] keyword[in] identifier[keylist] :
identifier[keylist] . identifier[append] ( identifier[key] )
keyword[for] identifier[rec] keyword[in] identifier[Recs] :
keyword[for] identifier[key] keyword[in] identifier[keylist] :
keyword[if] identifier[key] keyword[not] keyword[in] identifier[list] ( identifier[rec] . identifier[keys] ()):
identifier[rec] [ identifier[key] ]= literal[string]
identifier[OutRecs] . identifier[append] ( identifier[rec] )
keyword[return] identifier[OutRecs] , identifier[keylist] | def fillkeys(Recs):
"""
reconciles keys of dictionaries within Recs.
"""
(keylist, OutRecs) = ([], [])
for rec in Recs:
for key in list(rec.keys()):
if key not in keylist:
keylist.append(key) # depends on [control=['if'], data=['key', 'keylist']] # depends on [control=['for'], data=['key']] # depends on [control=['for'], data=['rec']]
for rec in Recs:
for key in keylist:
if key not in list(rec.keys()):
rec[key] = '' # depends on [control=['if'], data=['key']] # depends on [control=['for'], data=['key']]
OutRecs.append(rec) # depends on [control=['for'], data=['rec']]
return (OutRecs, keylist) |
def create_self_signed_cert():
"""Creates a self-signed certificate key pair."""
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
config_dir.mkdir(parents=True, exist_ok=True)
key_prefix = gethostname()
crt_file = config_dir / ('%s.crt' % key_prefix)
key_file = config_dir / ('%s.key' % key_prefix)
if crt_file.exists() and key_file.exists():
return crt_file, key_file
logger = logging.getLogger('xenon')
logger.info("Creating authentication keys for xenon-grpc.")
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
# valid for almost ten years!
cert.gmtime_adj_notAfter(10 * 365 * 24 * 3600)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha256')
open(str(crt_file), "wb").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(str(key_file), "wb").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
return crt_file, key_file | def function[create_self_signed_cert, parameter[]]:
constant[Creates a self-signed certificate key pair.]
variable[config_dir] assign[=] binary_operation[call[name[Path], parameter[name[BaseDirectory].xdg_config_home]] / constant[xenon-grpc]]
call[name[config_dir].mkdir, parameter[]]
variable[key_prefix] assign[=] call[name[gethostname], parameter[]]
variable[crt_file] assign[=] binary_operation[name[config_dir] / binary_operation[constant[%s.crt] <ast.Mod object at 0x7da2590d6920> name[key_prefix]]]
variable[key_file] assign[=] binary_operation[name[config_dir] / binary_operation[constant[%s.key] <ast.Mod object at 0x7da2590d6920> name[key_prefix]]]
if <ast.BoolOp object at 0x7da1b197cfa0> begin[:]
return[tuple[[<ast.Name object at 0x7da1b197e080>, <ast.Name object at 0x7da1b197ebc0>]]]
variable[logger] assign[=] call[name[logging].getLogger, parameter[constant[xenon]]]
call[name[logger].info, parameter[constant[Creating authentication keys for xenon-grpc.]]]
variable[k] assign[=] call[name[crypto].PKey, parameter[]]
call[name[k].generate_key, parameter[name[crypto].TYPE_RSA, constant[1024]]]
variable[cert] assign[=] call[name[crypto].X509, parameter[]]
call[name[cert].get_subject, parameter[]].CN assign[=] call[name[gethostname], parameter[]]
call[name[cert].set_serial_number, parameter[constant[1000]]]
call[name[cert].gmtime_adj_notBefore, parameter[constant[0]]]
call[name[cert].gmtime_adj_notAfter, parameter[binary_operation[binary_operation[binary_operation[constant[10] * constant[365]] * constant[24]] * constant[3600]]]]
call[name[cert].set_issuer, parameter[call[name[cert].get_subject, parameter[]]]]
call[name[cert].set_pubkey, parameter[name[k]]]
call[name[cert].sign, parameter[name[k], constant[sha256]]]
call[call[name[open], parameter[call[name[str], parameter[name[crt_file]]], constant[wb]]].write, parameter[call[name[crypto].dump_certificate, parameter[name[crypto].FILETYPE_PEM, name[cert]]]]]
call[call[name[open], parameter[call[name[str], parameter[name[key_file]]], constant[wb]]].write, parameter[call[name[crypto].dump_privatekey, parameter[name[crypto].FILETYPE_PEM, name[k]]]]]
return[tuple[[<ast.Name object at 0x7da1b1885030>, <ast.Name object at 0x7da1b1885000>]]] | keyword[def] identifier[create_self_signed_cert] ():
literal[string]
identifier[config_dir] = identifier[Path] ( identifier[BaseDirectory] . identifier[xdg_config_home] )/ literal[string]
identifier[config_dir] . identifier[mkdir] ( identifier[parents] = keyword[True] , identifier[exist_ok] = keyword[True] )
identifier[key_prefix] = identifier[gethostname] ()
identifier[crt_file] = identifier[config_dir] /( literal[string] % identifier[key_prefix] )
identifier[key_file] = identifier[config_dir] /( literal[string] % identifier[key_prefix] )
keyword[if] identifier[crt_file] . identifier[exists] () keyword[and] identifier[key_file] . identifier[exists] ():
keyword[return] identifier[crt_file] , identifier[key_file]
identifier[logger] = identifier[logging] . identifier[getLogger] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[k] = identifier[crypto] . identifier[PKey] ()
identifier[k] . identifier[generate_key] ( identifier[crypto] . identifier[TYPE_RSA] , literal[int] )
identifier[cert] = identifier[crypto] . identifier[X509] ()
identifier[cert] . identifier[get_subject] (). identifier[CN] = identifier[gethostname] ()
identifier[cert] . identifier[set_serial_number] ( literal[int] )
identifier[cert] . identifier[gmtime_adj_notBefore] ( literal[int] )
identifier[cert] . identifier[gmtime_adj_notAfter] ( literal[int] * literal[int] * literal[int] * literal[int] )
identifier[cert] . identifier[set_issuer] ( identifier[cert] . identifier[get_subject] ())
identifier[cert] . identifier[set_pubkey] ( identifier[k] )
identifier[cert] . identifier[sign] ( identifier[k] , literal[string] )
identifier[open] ( identifier[str] ( identifier[crt_file] ), literal[string] ). identifier[write] (
identifier[crypto] . identifier[dump_certificate] ( identifier[crypto] . identifier[FILETYPE_PEM] , identifier[cert] ))
identifier[open] ( identifier[str] ( identifier[key_file] ), literal[string] ). identifier[write] (
identifier[crypto] . identifier[dump_privatekey] ( identifier[crypto] . identifier[FILETYPE_PEM] , identifier[k] ))
keyword[return] identifier[crt_file] , identifier[key_file] | def create_self_signed_cert():
"""Creates a self-signed certificate key pair."""
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
config_dir.mkdir(parents=True, exist_ok=True)
key_prefix = gethostname()
crt_file = config_dir / ('%s.crt' % key_prefix)
key_file = config_dir / ('%s.key' % key_prefix)
if crt_file.exists() and key_file.exists():
return (crt_file, key_file) # depends on [control=['if'], data=[]]
logger = logging.getLogger('xenon')
logger.info('Creating authentication keys for xenon-grpc.')
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
# valid for almost ten years!
cert.gmtime_adj_notAfter(10 * 365 * 24 * 3600)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha256')
open(str(crt_file), 'wb').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(str(key_file), 'wb').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
return (crt_file, key_file) |
def widgets(self):
"""
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form
"""
customization = self.activity._json_data.get('customization')
if customization and "ext" in customization.keys():
return customization['ext']['widgets']
else:
return [] | def function[widgets, parameter[self]]:
constant[
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form
]
variable[customization] assign[=] call[name[self].activity._json_data.get, parameter[constant[customization]]]
if <ast.BoolOp object at 0x7da20e960880> begin[:]
return[call[call[name[customization]][constant[ext]]][constant[widgets]]] | keyword[def] identifier[widgets] ( identifier[self] ):
literal[string]
identifier[customization] = identifier[self] . identifier[activity] . identifier[_json_data] . identifier[get] ( literal[string] )
keyword[if] identifier[customization] keyword[and] literal[string] keyword[in] identifier[customization] . identifier[keys] ():
keyword[return] identifier[customization] [ literal[string] ][ literal[string] ]
keyword[else] :
keyword[return] [] | def widgets(self):
"""
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form
"""
customization = self.activity._json_data.get('customization')
if customization and 'ext' in customization.keys():
return customization['ext']['widgets'] # depends on [control=['if'], data=[]]
else:
return [] |
def MeetsConditions(knowledge_base, source):
"""Check conditions on the source."""
source_conditions_met = True
os_conditions = ConvertSupportedOSToConditions(source)
if os_conditions:
source.conditions.append(os_conditions)
for condition in source.conditions:
source_conditions_met &= artifact_utils.CheckCondition(
condition, knowledge_base)
return source_conditions_met | def function[MeetsConditions, parameter[knowledge_base, source]]:
constant[Check conditions on the source.]
variable[source_conditions_met] assign[=] constant[True]
variable[os_conditions] assign[=] call[name[ConvertSupportedOSToConditions], parameter[name[source]]]
if name[os_conditions] begin[:]
call[name[source].conditions.append, parameter[name[os_conditions]]]
for taget[name[condition]] in starred[name[source].conditions] begin[:]
<ast.AugAssign object at 0x7da1b1b49d20>
return[name[source_conditions_met]] | keyword[def] identifier[MeetsConditions] ( identifier[knowledge_base] , identifier[source] ):
literal[string]
identifier[source_conditions_met] = keyword[True]
identifier[os_conditions] = identifier[ConvertSupportedOSToConditions] ( identifier[source] )
keyword[if] identifier[os_conditions] :
identifier[source] . identifier[conditions] . identifier[append] ( identifier[os_conditions] )
keyword[for] identifier[condition] keyword[in] identifier[source] . identifier[conditions] :
identifier[source_conditions_met] &= identifier[artifact_utils] . identifier[CheckCondition] (
identifier[condition] , identifier[knowledge_base] )
keyword[return] identifier[source_conditions_met] | def MeetsConditions(knowledge_base, source):
"""Check conditions on the source."""
source_conditions_met = True
os_conditions = ConvertSupportedOSToConditions(source)
if os_conditions:
source.conditions.append(os_conditions) # depends on [control=['if'], data=[]]
for condition in source.conditions:
source_conditions_met &= artifact_utils.CheckCondition(condition, knowledge_base) # depends on [control=['for'], data=['condition']]
return source_conditions_met |
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
) | def function[morsel_to_cookie, parameter[morsel]]:
constant[Convert a Morsel object into a Cookie containing the one k/v pair.]
variable[expires] assign[=] constant[None]
if call[name[morsel]][constant[max-age]] begin[:]
<ast.Try object at 0x7da1b1de29e0>
return[call[name[create_cookie], parameter[]]] | keyword[def] identifier[morsel_to_cookie] ( identifier[morsel] ):
literal[string]
identifier[expires] = keyword[None]
keyword[if] identifier[morsel] [ literal[string] ]:
keyword[try] :
identifier[expires] = identifier[int] ( identifier[time] . identifier[time] ()+ identifier[int] ( identifier[morsel] [ literal[string] ]))
keyword[except] identifier[ValueError] :
keyword[raise] identifier[TypeError] ( literal[string] % identifier[morsel] [ literal[string] ])
keyword[elif] identifier[morsel] [ literal[string] ]:
identifier[time_template] = literal[string]
identifier[expires] = identifier[calendar] . identifier[timegm] (
identifier[time] . identifier[strptime] ( identifier[morsel] [ literal[string] ], identifier[time_template] )
)
keyword[return] identifier[create_cookie] (
identifier[comment] = identifier[morsel] [ literal[string] ],
identifier[comment_url] = identifier[bool] ( identifier[morsel] [ literal[string] ]),
identifier[discard] = keyword[False] ,
identifier[domain] = identifier[morsel] [ literal[string] ],
identifier[expires] = identifier[expires] ,
identifier[name] = identifier[morsel] . identifier[key] ,
identifier[path] = identifier[morsel] [ literal[string] ],
identifier[port] = keyword[None] ,
identifier[rest] ={ literal[string] : identifier[morsel] [ literal[string] ]},
identifier[rfc2109] = keyword[False] ,
identifier[secure] = identifier[bool] ( identifier[morsel] [ literal[string] ]),
identifier[value] = identifier[morsel] . identifier[value] ,
identifier[version] = identifier[morsel] [ literal[string] ] keyword[or] literal[int] ,
) | def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age'])) # depends on [control=['try'], data=[]]
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age']) # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]]
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(time.strptime(morsel['expires'], time_template)) # depends on [control=['if'], data=[]]
return create_cookie(comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0) |
def run_process(cwd, args):
"""Executes an external process via subprocess.Popen"""
try:
process = check_output(args, cwd=cwd, stderr=STDOUT)
return process
except CalledProcessError as e:
log('Uh oh, the teapot broke again! Error:', e, type(e), lvl=verbose, pretty=True)
log(e.cmd, e.returncode, e.output, lvl=verbose)
return e.output | def function[run_process, parameter[cwd, args]]:
constant[Executes an external process via subprocess.Popen]
<ast.Try object at 0x7da1b0fad930> | keyword[def] identifier[run_process] ( identifier[cwd] , identifier[args] ):
literal[string]
keyword[try] :
identifier[process] = identifier[check_output] ( identifier[args] , identifier[cwd] = identifier[cwd] , identifier[stderr] = identifier[STDOUT] )
keyword[return] identifier[process]
keyword[except] identifier[CalledProcessError] keyword[as] identifier[e] :
identifier[log] ( literal[string] , identifier[e] , identifier[type] ( identifier[e] ), identifier[lvl] = identifier[verbose] , identifier[pretty] = keyword[True] )
identifier[log] ( identifier[e] . identifier[cmd] , identifier[e] . identifier[returncode] , identifier[e] . identifier[output] , identifier[lvl] = identifier[verbose] )
keyword[return] identifier[e] . identifier[output] | def run_process(cwd, args):
"""Executes an external process via subprocess.Popen"""
try:
process = check_output(args, cwd=cwd, stderr=STDOUT)
return process # depends on [control=['try'], data=[]]
except CalledProcessError as e:
log('Uh oh, the teapot broke again! Error:', e, type(e), lvl=verbose, pretty=True)
log(e.cmd, e.returncode, e.output, lvl=verbose)
return e.output # depends on [control=['except'], data=['e']] |
def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch.
"""
if fourth_arg is None:
collection_id, branch_name, author = first_arg, sec_arg, third_arg
gh_user = branch_name.split('_collection_')[0]
parent_sha = self.get_master_sha()
else:
gh_user, collection_id, parent_sha, author = first_arg, sec_arg, third_arg, fourth_arg
if commit_msg is None:
commit_msg = "Delete Collection '%s' via OpenTree API" % collection_id
return self._remove_document(gh_user, collection_id, parent_sha, author, commit_msg) | def function[remove_collection, parameter[self, first_arg, sec_arg, third_arg, fourth_arg, commit_msg]]:
constant[Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch.
]
if compare[name[fourth_arg] is constant[None]] begin[:]
<ast.Tuple object at 0x7da1b25b1750> assign[=] tuple[[<ast.Name object at 0x7da1b25b3970>, <ast.Name object at 0x7da1b25b0fa0>, <ast.Name object at 0x7da1b25b10f0>]]
variable[gh_user] assign[=] call[call[name[branch_name].split, parameter[constant[_collection_]]]][constant[0]]
variable[parent_sha] assign[=] call[name[self].get_master_sha, parameter[]]
if compare[name[commit_msg] is constant[None]] begin[:]
variable[commit_msg] assign[=] binary_operation[constant[Delete Collection '%s' via OpenTree API] <ast.Mod object at 0x7da2590d6920> name[collection_id]]
return[call[name[self]._remove_document, parameter[name[gh_user], name[collection_id], name[parent_sha], name[author], name[commit_msg]]]] | keyword[def] identifier[remove_collection] ( identifier[self] , identifier[first_arg] , identifier[sec_arg] , identifier[third_arg] , identifier[fourth_arg] = keyword[None] , identifier[commit_msg] = keyword[None] ):
literal[string]
keyword[if] identifier[fourth_arg] keyword[is] keyword[None] :
identifier[collection_id] , identifier[branch_name] , identifier[author] = identifier[first_arg] , identifier[sec_arg] , identifier[third_arg]
identifier[gh_user] = identifier[branch_name] . identifier[split] ( literal[string] )[ literal[int] ]
identifier[parent_sha] = identifier[self] . identifier[get_master_sha] ()
keyword[else] :
identifier[gh_user] , identifier[collection_id] , identifier[parent_sha] , identifier[author] = identifier[first_arg] , identifier[sec_arg] , identifier[third_arg] , identifier[fourth_arg]
keyword[if] identifier[commit_msg] keyword[is] keyword[None] :
identifier[commit_msg] = literal[string] % identifier[collection_id]
keyword[return] identifier[self] . identifier[_remove_document] ( identifier[gh_user] , identifier[collection_id] , identifier[parent_sha] , identifier[author] , identifier[commit_msg] ) | def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch.
"""
if fourth_arg is None:
(collection_id, branch_name, author) = (first_arg, sec_arg, third_arg)
gh_user = branch_name.split('_collection_')[0]
parent_sha = self.get_master_sha() # depends on [control=['if'], data=[]]
else:
(gh_user, collection_id, parent_sha, author) = (first_arg, sec_arg, third_arg, fourth_arg)
if commit_msg is None:
commit_msg = "Delete Collection '%s' via OpenTree API" % collection_id # depends on [control=['if'], data=['commit_msg']]
return self._remove_document(gh_user, collection_id, parent_sha, author, commit_msg) |
def connect(self, host, port):
"""Connects via a RS-485 to Ethernet adapter."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
self._reader = sock.makefile(mode='rb')
self._writer = sock.makefile(mode='wb') | def function[connect, parameter[self, host, port]]:
constant[Connects via a RS-485 to Ethernet adapter.]
variable[sock] assign[=] call[name[socket].socket, parameter[name[socket].AF_INET, name[socket].SOCK_STREAM]]
call[name[sock].connect, parameter[tuple[[<ast.Name object at 0x7da18bcc95a0>, <ast.Name object at 0x7da18bcc8220>]]]]
name[self]._reader assign[=] call[name[sock].makefile, parameter[]]
name[self]._writer assign[=] call[name[sock].makefile, parameter[]] | keyword[def] identifier[connect] ( identifier[self] , identifier[host] , identifier[port] ):
literal[string]
identifier[sock] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_STREAM] )
identifier[sock] . identifier[connect] (( identifier[host] , identifier[port] ))
identifier[self] . identifier[_reader] = identifier[sock] . identifier[makefile] ( identifier[mode] = literal[string] )
identifier[self] . identifier[_writer] = identifier[sock] . identifier[makefile] ( identifier[mode] = literal[string] ) | def connect(self, host, port):
"""Connects via a RS-485 to Ethernet adapter."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
self._reader = sock.makefile(mode='rb')
self._writer = sock.makefile(mode='wb') |
def parse_arguments(lexer: Lexer, is_const: bool) -> List[ArgumentNode]:
"""Arguments[Const]: (Argument[?Const]+)"""
item = parse_const_argument if is_const else parse_argument
return (
cast(
List[ArgumentNode],
many_nodes(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R),
)
if peek(lexer, TokenKind.PAREN_L)
else []
) | def function[parse_arguments, parameter[lexer, is_const]]:
constant[Arguments[Const]: (Argument[?Const]+)]
variable[item] assign[=] <ast.IfExp object at 0x7da1b22eb8e0>
return[<ast.IfExp object at 0x7da1b22e95a0>] | keyword[def] identifier[parse_arguments] ( identifier[lexer] : identifier[Lexer] , identifier[is_const] : identifier[bool] )-> identifier[List] [ identifier[ArgumentNode] ]:
literal[string]
identifier[item] = identifier[parse_const_argument] keyword[if] identifier[is_const] keyword[else] identifier[parse_argument]
keyword[return] (
identifier[cast] (
identifier[List] [ identifier[ArgumentNode] ],
identifier[many_nodes] ( identifier[lexer] , identifier[TokenKind] . identifier[PAREN_L] , identifier[item] , identifier[TokenKind] . identifier[PAREN_R] ),
)
keyword[if] identifier[peek] ( identifier[lexer] , identifier[TokenKind] . identifier[PAREN_L] )
keyword[else] []
) | def parse_arguments(lexer: Lexer, is_const: bool) -> List[ArgumentNode]:
"""Arguments[Const]: (Argument[?Const]+)"""
item = parse_const_argument if is_const else parse_argument
return cast(List[ArgumentNode], many_nodes(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R)) if peek(lexer, TokenKind.PAREN_L) else [] |
def get_view_url(self):
"""Return url for ajax to view for render dialog content"""
url = reverse("django_popup_view_field:get_popup_view", args=(self.view_class_name,))
return "{url}?{cd}".format(
url=url,
cd=self.callback_data
) | def function[get_view_url, parameter[self]]:
constant[Return url for ajax to view for render dialog content]
variable[url] assign[=] call[name[reverse], parameter[constant[django_popup_view_field:get_popup_view]]]
return[call[constant[{url}?{cd}].format, parameter[]]] | keyword[def] identifier[get_view_url] ( identifier[self] ):
literal[string]
identifier[url] = identifier[reverse] ( literal[string] , identifier[args] =( identifier[self] . identifier[view_class_name] ,))
keyword[return] literal[string] . identifier[format] (
identifier[url] = identifier[url] ,
identifier[cd] = identifier[self] . identifier[callback_data]
) | def get_view_url(self):
"""Return url for ajax to view for render dialog content"""
url = reverse('django_popup_view_field:get_popup_view', args=(self.view_class_name,))
return '{url}?{cd}'.format(url=url, cd=self.callback_data) |
def _get_violations(self, query, record):
"""Reverse-engineer the query to figure out why a record was selected.
:param query: MongoDB query
:type query: MongQuery
:param record: Record in question
:type record: dict
:return: Reasons why bad
:rtype: list(ConstraintViolation)
"""
# special case, when no constraints are given
if len(query.all_clauses) == 0:
return [NullConstraintViolation()]
# normal case, check all the constraints
reasons = []
for clause in query.all_clauses:
var_name = None
key = clause.constraint.field.name
op = clause.constraint.op
fval = mongo_get(record, key)
if fval is None:
expected = clause.constraint.value
reasons.append(ConstraintViolation(clause.constraint, 'missing', expected))
continue
if op.is_variable():
# retrieve value for variable
var_name = clause.constraint.value
value = mongo_get(record, var_name, default=None)
if value is None:
reasons.append(ConstraintViolation(clause.constraint, 'missing', var_name))
continue
clause.constraint.value = value # swap out value, temporarily
# take length for size
if op.is_size():
if isinstance(fval, str) or not hasattr(fval, '__len__'):
reasons.append(ConstraintViolation(clause.constraint, type(fval), 'sequence'))
if op.is_variable():
clause.constraint.value = var_name # put original value back
continue
fval = len(fval)
ok, expected = clause.constraint.passes(fval)
if not ok:
reasons.append(ConstraintViolation(clause.constraint, fval, expected))
if op.is_variable():
clause.constraint.value = var_name # put original value back
return reasons | def function[_get_violations, parameter[self, query, record]]:
constant[Reverse-engineer the query to figure out why a record was selected.
:param query: MongoDB query
:type query: MongQuery
:param record: Record in question
:type record: dict
:return: Reasons why bad
:rtype: list(ConstraintViolation)
]
if compare[call[name[len], parameter[name[query].all_clauses]] equal[==] constant[0]] begin[:]
return[list[[<ast.Call object at 0x7da18fe90e80>]]]
variable[reasons] assign[=] list[[]]
for taget[name[clause]] in starred[name[query].all_clauses] begin[:]
variable[var_name] assign[=] constant[None]
variable[key] assign[=] name[clause].constraint.field.name
variable[op] assign[=] name[clause].constraint.op
variable[fval] assign[=] call[name[mongo_get], parameter[name[record], name[key]]]
if compare[name[fval] is constant[None]] begin[:]
variable[expected] assign[=] name[clause].constraint.value
call[name[reasons].append, parameter[call[name[ConstraintViolation], parameter[name[clause].constraint, constant[missing], name[expected]]]]]
continue
if call[name[op].is_variable, parameter[]] begin[:]
variable[var_name] assign[=] name[clause].constraint.value
variable[value] assign[=] call[name[mongo_get], parameter[name[record], name[var_name]]]
if compare[name[value] is constant[None]] begin[:]
call[name[reasons].append, parameter[call[name[ConstraintViolation], parameter[name[clause].constraint, constant[missing], name[var_name]]]]]
continue
name[clause].constraint.value assign[=] name[value]
if call[name[op].is_size, parameter[]] begin[:]
if <ast.BoolOp object at 0x7da18fe927d0> begin[:]
call[name[reasons].append, parameter[call[name[ConstraintViolation], parameter[name[clause].constraint, call[name[type], parameter[name[fval]]], constant[sequence]]]]]
if call[name[op].is_variable, parameter[]] begin[:]
name[clause].constraint.value assign[=] name[var_name]
continue
variable[fval] assign[=] call[name[len], parameter[name[fval]]]
<ast.Tuple object at 0x7da18fe92f20> assign[=] call[name[clause].constraint.passes, parameter[name[fval]]]
if <ast.UnaryOp object at 0x7da1b2346f80> begin[:]
call[name[reasons].append, parameter[call[name[ConstraintViolation], parameter[name[clause].constraint, name[fval], name[expected]]]]]
if call[name[op].is_variable, parameter[]] begin[:]
name[clause].constraint.value assign[=] name[var_name]
return[name[reasons]] | keyword[def] identifier[_get_violations] ( identifier[self] , identifier[query] , identifier[record] ):
literal[string]
keyword[if] identifier[len] ( identifier[query] . identifier[all_clauses] )== literal[int] :
keyword[return] [ identifier[NullConstraintViolation] ()]
identifier[reasons] =[]
keyword[for] identifier[clause] keyword[in] identifier[query] . identifier[all_clauses] :
identifier[var_name] = keyword[None]
identifier[key] = identifier[clause] . identifier[constraint] . identifier[field] . identifier[name]
identifier[op] = identifier[clause] . identifier[constraint] . identifier[op]
identifier[fval] = identifier[mongo_get] ( identifier[record] , identifier[key] )
keyword[if] identifier[fval] keyword[is] keyword[None] :
identifier[expected] = identifier[clause] . identifier[constraint] . identifier[value]
identifier[reasons] . identifier[append] ( identifier[ConstraintViolation] ( identifier[clause] . identifier[constraint] , literal[string] , identifier[expected] ))
keyword[continue]
keyword[if] identifier[op] . identifier[is_variable] ():
identifier[var_name] = identifier[clause] . identifier[constraint] . identifier[value]
identifier[value] = identifier[mongo_get] ( identifier[record] , identifier[var_name] , identifier[default] = keyword[None] )
keyword[if] identifier[value] keyword[is] keyword[None] :
identifier[reasons] . identifier[append] ( identifier[ConstraintViolation] ( identifier[clause] . identifier[constraint] , literal[string] , identifier[var_name] ))
keyword[continue]
identifier[clause] . identifier[constraint] . identifier[value] = identifier[value]
keyword[if] identifier[op] . identifier[is_size] ():
keyword[if] identifier[isinstance] ( identifier[fval] , identifier[str] ) keyword[or] keyword[not] identifier[hasattr] ( identifier[fval] , literal[string] ):
identifier[reasons] . identifier[append] ( identifier[ConstraintViolation] ( identifier[clause] . identifier[constraint] , identifier[type] ( identifier[fval] ), literal[string] ))
keyword[if] identifier[op] . identifier[is_variable] ():
identifier[clause] . identifier[constraint] . identifier[value] = identifier[var_name]
keyword[continue]
identifier[fval] = identifier[len] ( identifier[fval] )
identifier[ok] , identifier[expected] = identifier[clause] . identifier[constraint] . identifier[passes] ( identifier[fval] )
keyword[if] keyword[not] identifier[ok] :
identifier[reasons] . identifier[append] ( identifier[ConstraintViolation] ( identifier[clause] . identifier[constraint] , identifier[fval] , identifier[expected] ))
keyword[if] identifier[op] . identifier[is_variable] ():
identifier[clause] . identifier[constraint] . identifier[value] = identifier[var_name]
keyword[return] identifier[reasons] | def _get_violations(self, query, record):
"""Reverse-engineer the query to figure out why a record was selected.
:param query: MongoDB query
:type query: MongQuery
:param record: Record in question
:type record: dict
:return: Reasons why bad
:rtype: list(ConstraintViolation)
"""
# special case, when no constraints are given
if len(query.all_clauses) == 0:
return [NullConstraintViolation()] # depends on [control=['if'], data=[]]
# normal case, check all the constraints
reasons = []
for clause in query.all_clauses:
var_name = None
key = clause.constraint.field.name
op = clause.constraint.op
fval = mongo_get(record, key)
if fval is None:
expected = clause.constraint.value
reasons.append(ConstraintViolation(clause.constraint, 'missing', expected))
continue # depends on [control=['if'], data=[]]
if op.is_variable():
# retrieve value for variable
var_name = clause.constraint.value
value = mongo_get(record, var_name, default=None)
if value is None:
reasons.append(ConstraintViolation(clause.constraint, 'missing', var_name))
continue # depends on [control=['if'], data=[]]
clause.constraint.value = value # swap out value, temporarily # depends on [control=['if'], data=[]]
# take length for size
if op.is_size():
if isinstance(fval, str) or not hasattr(fval, '__len__'):
reasons.append(ConstraintViolation(clause.constraint, type(fval), 'sequence'))
if op.is_variable():
clause.constraint.value = var_name # put original value back # depends on [control=['if'], data=[]]
continue # depends on [control=['if'], data=[]]
fval = len(fval) # depends on [control=['if'], data=[]]
(ok, expected) = clause.constraint.passes(fval)
if not ok:
reasons.append(ConstraintViolation(clause.constraint, fval, expected)) # depends on [control=['if'], data=[]]
if op.is_variable():
clause.constraint.value = var_name # put original value back # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['clause']]
return reasons |
def get_distance(self, node1_name, node2_name):
""" Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, if requested a length of an edge, that is not present in current tree
"""
return self.__root.get_distance(target=node1_name, target2=node2_name) | def function[get_distance, parameter[self, node1_name, node2_name]]:
constant[ Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, if requested a length of an edge, that is not present in current tree
]
return[call[name[self].__root.get_distance, parameter[]]] | keyword[def] identifier[get_distance] ( identifier[self] , identifier[node1_name] , identifier[node2_name] ):
literal[string]
keyword[return] identifier[self] . identifier[__root] . identifier[get_distance] ( identifier[target] = identifier[node1_name] , identifier[target2] = identifier[node2_name] ) | def get_distance(self, node1_name, node2_name):
""" Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, if requested a length of an edge, that is not present in current tree
"""
return self.__root.get_distance(target=node1_name, target2=node2_name) |
def post_save(sender, instance, created, **kwargs):
"""
After save create order instance for sending instance for orderable models.
"""
# Only create order model instances for
# those modules specified in settings.
model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
labels = resolve_labels(model_label)
order_field_names = is_orderable(model_label)
if order_field_names:
orderitem_set = getattr(
instance,
resolve_order_item_related_set_name(labels)
)
if not orderitem_set.all():
fields = {}
for order_field_name in order_field_names:
fields[order_field_name] = 1
orderitem_set.model.objects.create(item=instance, **fields)
sanitize_order(orderitem_set.model) | def function[post_save, parameter[sender, instance, created]]:
constant[
After save create order instance for sending instance for orderable models.
]
variable[model_label] assign[=] call[constant[.].join, parameter[list[[<ast.Attribute object at 0x7da1b0a2ece0>, <ast.Attribute object at 0x7da1b0a2d990>]]]]
variable[labels] assign[=] call[name[resolve_labels], parameter[name[model_label]]]
variable[order_field_names] assign[=] call[name[is_orderable], parameter[name[model_label]]]
if name[order_field_names] begin[:]
variable[orderitem_set] assign[=] call[name[getattr], parameter[name[instance], call[name[resolve_order_item_related_set_name], parameter[name[labels]]]]]
if <ast.UnaryOp object at 0x7da1b0a2fe20> begin[:]
variable[fields] assign[=] dictionary[[], []]
for taget[name[order_field_name]] in starred[name[order_field_names]] begin[:]
call[name[fields]][name[order_field_name]] assign[=] constant[1]
call[name[orderitem_set].model.objects.create, parameter[]]
call[name[sanitize_order], parameter[name[orderitem_set].model]] | keyword[def] identifier[post_save] ( identifier[sender] , identifier[instance] , identifier[created] ,** identifier[kwargs] ):
literal[string]
identifier[model_label] = literal[string] . identifier[join] ([ identifier[sender] . identifier[_meta] . identifier[app_label] , identifier[sender] . identifier[_meta] . identifier[object_name] ])
identifier[labels] = identifier[resolve_labels] ( identifier[model_label] )
identifier[order_field_names] = identifier[is_orderable] ( identifier[model_label] )
keyword[if] identifier[order_field_names] :
identifier[orderitem_set] = identifier[getattr] (
identifier[instance] ,
identifier[resolve_order_item_related_set_name] ( identifier[labels] )
)
keyword[if] keyword[not] identifier[orderitem_set] . identifier[all] ():
identifier[fields] ={}
keyword[for] identifier[order_field_name] keyword[in] identifier[order_field_names] :
identifier[fields] [ identifier[order_field_name] ]= literal[int]
identifier[orderitem_set] . identifier[model] . identifier[objects] . identifier[create] ( identifier[item] = identifier[instance] ,** identifier[fields] )
identifier[sanitize_order] ( identifier[orderitem_set] . identifier[model] ) | def post_save(sender, instance, created, **kwargs):
"""
After save create order instance for sending instance for orderable models.
"""
# Only create order model instances for
# those modules specified in settings.
model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
labels = resolve_labels(model_label)
order_field_names = is_orderable(model_label)
if order_field_names:
orderitem_set = getattr(instance, resolve_order_item_related_set_name(labels))
if not orderitem_set.all():
fields = {}
for order_field_name in order_field_names:
fields[order_field_name] = 1 # depends on [control=['for'], data=['order_field_name']]
orderitem_set.model.objects.create(item=instance, **fields)
sanitize_order(orderitem_set.model) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] |
def _getSectionIds(self, server, sections):
""" Converts a list of section objects or names to sectionIds needed for library sharing. """
if not sections: return []
# Get a list of all section ids for looking up each section.
allSectionIds = {}
machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server
url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier)
data = self.query(url, self._session.get)
for elem in data[0]:
allSectionIds[elem.attrib.get('id', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('title', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('key', '').lower()] = elem.attrib.get('id')
log.debug(allSectionIds)
# Convert passed in section items to section ids from above lookup
sectionIds = []
for section in sections:
sectionKey = section.key if isinstance(section, LibrarySection) else section
sectionIds.append(allSectionIds[sectionKey.lower()])
return sectionIds | def function[_getSectionIds, parameter[self, server, sections]]:
constant[ Converts a list of section objects or names to sectionIds needed for library sharing. ]
if <ast.UnaryOp object at 0x7da1b060a4d0> begin[:]
return[list[[]]]
variable[allSectionIds] assign[=] dictionary[[], []]
variable[machineIdentifier] assign[=] <ast.IfExp object at 0x7da1b060aa40>
variable[url] assign[=] call[name[self].PLEXSERVERS.replace, parameter[constant[{machineId}], name[machineIdentifier]]]
variable[data] assign[=] call[name[self].query, parameter[name[url], name[self]._session.get]]
for taget[name[elem]] in starred[call[name[data]][constant[0]]] begin[:]
call[name[allSectionIds]][call[call[name[elem].attrib.get, parameter[constant[id], constant[]]].lower, parameter[]]] assign[=] call[name[elem].attrib.get, parameter[constant[id]]]
call[name[allSectionIds]][call[call[name[elem].attrib.get, parameter[constant[title], constant[]]].lower, parameter[]]] assign[=] call[name[elem].attrib.get, parameter[constant[id]]]
call[name[allSectionIds]][call[call[name[elem].attrib.get, parameter[constant[key], constant[]]].lower, parameter[]]] assign[=] call[name[elem].attrib.get, parameter[constant[id]]]
call[name[log].debug, parameter[name[allSectionIds]]]
variable[sectionIds] assign[=] list[[]]
for taget[name[section]] in starred[name[sections]] begin[:]
variable[sectionKey] assign[=] <ast.IfExp object at 0x7da2044c07c0>
call[name[sectionIds].append, parameter[call[name[allSectionIds]][call[name[sectionKey].lower, parameter[]]]]]
return[name[sectionIds]] | keyword[def] identifier[_getSectionIds] ( identifier[self] , identifier[server] , identifier[sections] ):
literal[string]
keyword[if] keyword[not] identifier[sections] : keyword[return] []
identifier[allSectionIds] ={}
identifier[machineIdentifier] = identifier[server] . identifier[machineIdentifier] keyword[if] identifier[isinstance] ( identifier[server] , identifier[PlexServer] ) keyword[else] identifier[server]
identifier[url] = identifier[self] . identifier[PLEXSERVERS] . identifier[replace] ( literal[string] , identifier[machineIdentifier] )
identifier[data] = identifier[self] . identifier[query] ( identifier[url] , identifier[self] . identifier[_session] . identifier[get] )
keyword[for] identifier[elem] keyword[in] identifier[data] [ literal[int] ]:
identifier[allSectionIds] [ identifier[elem] . identifier[attrib] . identifier[get] ( literal[string] , literal[string] ). identifier[lower] ()]= identifier[elem] . identifier[attrib] . identifier[get] ( literal[string] )
identifier[allSectionIds] [ identifier[elem] . identifier[attrib] . identifier[get] ( literal[string] , literal[string] ). identifier[lower] ()]= identifier[elem] . identifier[attrib] . identifier[get] ( literal[string] )
identifier[allSectionIds] [ identifier[elem] . identifier[attrib] . identifier[get] ( literal[string] , literal[string] ). identifier[lower] ()]= identifier[elem] . identifier[attrib] . identifier[get] ( literal[string] )
identifier[log] . identifier[debug] ( identifier[allSectionIds] )
identifier[sectionIds] =[]
keyword[for] identifier[section] keyword[in] identifier[sections] :
identifier[sectionKey] = identifier[section] . identifier[key] keyword[if] identifier[isinstance] ( identifier[section] , identifier[LibrarySection] ) keyword[else] identifier[section]
identifier[sectionIds] . identifier[append] ( identifier[allSectionIds] [ identifier[sectionKey] . identifier[lower] ()])
keyword[return] identifier[sectionIds] | def _getSectionIds(self, server, sections):
""" Converts a list of section objects or names to sectionIds needed for library sharing. """
if not sections:
return [] # depends on [control=['if'], data=[]]
# Get a list of all section ids for looking up each section.
allSectionIds = {}
machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server
url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier)
data = self.query(url, self._session.get)
for elem in data[0]:
allSectionIds[elem.attrib.get('id', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('title', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('key', '').lower()] = elem.attrib.get('id') # depends on [control=['for'], data=['elem']]
log.debug(allSectionIds)
# Convert passed in section items to section ids from above lookup
sectionIds = []
for section in sections:
sectionKey = section.key if isinstance(section, LibrarySection) else section
sectionIds.append(allSectionIds[sectionKey.lower()]) # depends on [control=['for'], data=['section']]
return sectionIds |
def on(self, event, handler=None):
"""Create, add or update an event with a handler or more attached."""
if isinstance(event, str) and ' ' in event: # event is list str-based
self.on(event.split(' '), handler)
elif isinstance(event, list): # many events contains same handler
for each in event:
self.on(each, handler)
elif isinstance(event, dict): # event is a dict of <event, handler>
for key, value in event.items():
self.on(key, value)
elif isinstance(handler, list): # handler is a list of handlers
for each in handler:
self.on(event, each)
elif isinstance(handler, Event): # handler is Event object
self.events[event] = handler # add or update an event
setattr(self, event, self.events[event]) # self.event.trigger()
elif event in self.events: # add a handler to an existing event
self.events[event].on(handler)
else: # create new event with a handler attached
self.on(event, Event(handler)) | def function[on, parameter[self, event, handler]]:
constant[Create, add or update an event with a handler or more attached.]
if <ast.BoolOp object at 0x7da18eb543a0> begin[:]
call[name[self].on, parameter[call[name[event].split, parameter[constant[ ]]], name[handler]]] | keyword[def] identifier[on] ( identifier[self] , identifier[event] , identifier[handler] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[event] , identifier[str] ) keyword[and] literal[string] keyword[in] identifier[event] :
identifier[self] . identifier[on] ( identifier[event] . identifier[split] ( literal[string] ), identifier[handler] )
keyword[elif] identifier[isinstance] ( identifier[event] , identifier[list] ):
keyword[for] identifier[each] keyword[in] identifier[event] :
identifier[self] . identifier[on] ( identifier[each] , identifier[handler] )
keyword[elif] identifier[isinstance] ( identifier[event] , identifier[dict] ):
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[event] . identifier[items] ():
identifier[self] . identifier[on] ( identifier[key] , identifier[value] )
keyword[elif] identifier[isinstance] ( identifier[handler] , identifier[list] ):
keyword[for] identifier[each] keyword[in] identifier[handler] :
identifier[self] . identifier[on] ( identifier[event] , identifier[each] )
keyword[elif] identifier[isinstance] ( identifier[handler] , identifier[Event] ):
identifier[self] . identifier[events] [ identifier[event] ]= identifier[handler]
identifier[setattr] ( identifier[self] , identifier[event] , identifier[self] . identifier[events] [ identifier[event] ])
keyword[elif] identifier[event] keyword[in] identifier[self] . identifier[events] :
identifier[self] . identifier[events] [ identifier[event] ]. identifier[on] ( identifier[handler] )
keyword[else] :
identifier[self] . identifier[on] ( identifier[event] , identifier[Event] ( identifier[handler] )) | def on(self, event, handler=None):
"""Create, add or update an event with a handler or more attached."""
if isinstance(event, str) and ' ' in event: # event is list str-based
self.on(event.split(' '), handler) # depends on [control=['if'], data=[]]
elif isinstance(event, list): # many events contains same handler
for each in event:
self.on(each, handler) # depends on [control=['for'], data=['each']] # depends on [control=['if'], data=[]]
elif isinstance(event, dict): # event is a dict of <event, handler>
for (key, value) in event.items():
self.on(key, value) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
elif isinstance(handler, list): # handler is a list of handlers
for each in handler:
self.on(event, each) # depends on [control=['for'], data=['each']] # depends on [control=['if'], data=[]]
elif isinstance(handler, Event): # handler is Event object
self.events[event] = handler # add or update an event
setattr(self, event, self.events[event]) # self.event.trigger() # depends on [control=['if'], data=[]]
elif event in self.events: # add a handler to an existing event
self.events[event].on(handler) # depends on [control=['if'], data=['event']]
else: # create new event with a handler attached
self.on(event, Event(handler)) |
def zoom_fit(self, no_reset=False):
"""Zoom to fit display window.
Also see :meth:`zoom_to`.
Parameters
----------
no_reset : bool
Do not reset ``autozoom`` setting.
"""
# calculate actual width of the limits/image, considering rotation
try:
xy_mn, xy_mx = self.get_limits()
except ImageViewNoDataError:
return
try:
wwidth, wheight = self.get_window_size()
self.logger.debug("Window size is %dx%d" % (wwidth, wheight))
if self.t_['swap_xy']:
wwidth, wheight = wheight, wwidth
except Exception:
return
# zoom_fit also centers image
with self.suppress_redraw:
self.center_image(no_reset=no_reset)
ctr_x, ctr_y, rot_deg = self.get_rotation_info()
# Find min/max extents of limits as shown by viewer
xs = np.array((xy_mn[0], xy_mx[0], xy_mx[0], xy_mn[0]))
ys = np.array((xy_mn[1], xy_mn[1], xy_mx[1], xy_mx[1]))
x0, y0 = trcalc.rotate_pt(xs, ys, rot_deg, xoff=ctr_x, yoff=ctr_y)
min_x, min_y = np.min(x0), np.min(y0)
max_x, max_y = np.max(x0), np.max(y0)
width, height = max_x - min_x, max_y - min_y
if min(width, height) <= 0:
return
# Calculate optimum zoom level to still fit the window size
scale_x = (float(wwidth) /
(float(width) * self.t_['scale_x_base']))
scale_y = (float(wheight) /
(float(height) * self.t_['scale_y_base']))
scalefactor = min(scale_x, scale_y)
# account for t_[scale_x/y_base]
scale_x = scalefactor * self.t_['scale_x_base']
scale_y = scalefactor * self.t_['scale_y_base']
self._scale_to(scale_x, scale_y, no_reset=no_reset)
if self.t_['autozoom'] == 'once':
self.t_.set(autozoom='off') | def function[zoom_fit, parameter[self, no_reset]]:
constant[Zoom to fit display window.
Also see :meth:`zoom_to`.
Parameters
----------
no_reset : bool
Do not reset ``autozoom`` setting.
]
<ast.Try object at 0x7da207f9b190>
<ast.Try object at 0x7da207f9a7a0>
with name[self].suppress_redraw begin[:]
call[name[self].center_image, parameter[]]
<ast.Tuple object at 0x7da18eb56140> assign[=] call[name[self].get_rotation_info, parameter[]]
variable[xs] assign[=] call[name[np].array, parameter[tuple[[<ast.Subscript object at 0x7da18eb57190>, <ast.Subscript object at 0x7da18eb574c0>, <ast.Subscript object at 0x7da18eb56530>, <ast.Subscript object at 0x7da18eb57820>]]]]
variable[ys] assign[=] call[name[np].array, parameter[tuple[[<ast.Subscript object at 0x7da18eb54a00>, <ast.Subscript object at 0x7da18eb57010>, <ast.Subscript object at 0x7da18eb57ac0>, <ast.Subscript object at 0x7da18eb541f0>]]]]
<ast.Tuple object at 0x7da18eb57040> assign[=] call[name[trcalc].rotate_pt, parameter[name[xs], name[ys], name[rot_deg]]]
<ast.Tuple object at 0x7da18eb54310> assign[=] tuple[[<ast.Call object at 0x7da18eb57a90>, <ast.Call object at 0x7da1b0c24e20>]]
<ast.Tuple object at 0x7da1b0c26050> assign[=] tuple[[<ast.Call object at 0x7da1b0c24520>, <ast.Call object at 0x7da1b0c27160>]]
<ast.Tuple object at 0x7da1b0c26d40> assign[=] tuple[[<ast.BinOp object at 0x7da1b0c25690>, <ast.BinOp object at 0x7da1b0c25bd0>]]
if compare[call[name[min], parameter[name[width], name[height]]] less_or_equal[<=] constant[0]] begin[:]
return[None]
variable[scale_x] assign[=] binary_operation[call[name[float], parameter[name[wwidth]]] / binary_operation[call[name[float], parameter[name[width]]] * call[name[self].t_][constant[scale_x_base]]]]
variable[scale_y] assign[=] binary_operation[call[name[float], parameter[name[wheight]]] / binary_operation[call[name[float], parameter[name[height]]] * call[name[self].t_][constant[scale_y_base]]]]
variable[scalefactor] assign[=] call[name[min], parameter[name[scale_x], name[scale_y]]]
variable[scale_x] assign[=] binary_operation[name[scalefactor] * call[name[self].t_][constant[scale_x_base]]]
variable[scale_y] assign[=] binary_operation[name[scalefactor] * call[name[self].t_][constant[scale_y_base]]]
call[name[self]._scale_to, parameter[name[scale_x], name[scale_y]]]
if compare[call[name[self].t_][constant[autozoom]] equal[==] constant[once]] begin[:]
call[name[self].t_.set, parameter[]] | keyword[def] identifier[zoom_fit] ( identifier[self] , identifier[no_reset] = keyword[False] ):
literal[string]
keyword[try] :
identifier[xy_mn] , identifier[xy_mx] = identifier[self] . identifier[get_limits] ()
keyword[except] identifier[ImageViewNoDataError] :
keyword[return]
keyword[try] :
identifier[wwidth] , identifier[wheight] = identifier[self] . identifier[get_window_size] ()
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] %( identifier[wwidth] , identifier[wheight] ))
keyword[if] identifier[self] . identifier[t_] [ literal[string] ]:
identifier[wwidth] , identifier[wheight] = identifier[wheight] , identifier[wwidth]
keyword[except] identifier[Exception] :
keyword[return]
keyword[with] identifier[self] . identifier[suppress_redraw] :
identifier[self] . identifier[center_image] ( identifier[no_reset] = identifier[no_reset] )
identifier[ctr_x] , identifier[ctr_y] , identifier[rot_deg] = identifier[self] . identifier[get_rotation_info] ()
identifier[xs] = identifier[np] . identifier[array] (( identifier[xy_mn] [ literal[int] ], identifier[xy_mx] [ literal[int] ], identifier[xy_mx] [ literal[int] ], identifier[xy_mn] [ literal[int] ]))
identifier[ys] = identifier[np] . identifier[array] (( identifier[xy_mn] [ literal[int] ], identifier[xy_mn] [ literal[int] ], identifier[xy_mx] [ literal[int] ], identifier[xy_mx] [ literal[int] ]))
identifier[x0] , identifier[y0] = identifier[trcalc] . identifier[rotate_pt] ( identifier[xs] , identifier[ys] , identifier[rot_deg] , identifier[xoff] = identifier[ctr_x] , identifier[yoff] = identifier[ctr_y] )
identifier[min_x] , identifier[min_y] = identifier[np] . identifier[min] ( identifier[x0] ), identifier[np] . identifier[min] ( identifier[y0] )
identifier[max_x] , identifier[max_y] = identifier[np] . identifier[max] ( identifier[x0] ), identifier[np] . identifier[max] ( identifier[y0] )
identifier[width] , identifier[height] = identifier[max_x] - identifier[min_x] , identifier[max_y] - identifier[min_y]
keyword[if] identifier[min] ( identifier[width] , identifier[height] )<= literal[int] :
keyword[return]
identifier[scale_x] =( identifier[float] ( identifier[wwidth] )/
( identifier[float] ( identifier[width] )* identifier[self] . identifier[t_] [ literal[string] ]))
identifier[scale_y] =( identifier[float] ( identifier[wheight] )/
( identifier[float] ( identifier[height] )* identifier[self] . identifier[t_] [ literal[string] ]))
identifier[scalefactor] = identifier[min] ( identifier[scale_x] , identifier[scale_y] )
identifier[scale_x] = identifier[scalefactor] * identifier[self] . identifier[t_] [ literal[string] ]
identifier[scale_y] = identifier[scalefactor] * identifier[self] . identifier[t_] [ literal[string] ]
identifier[self] . identifier[_scale_to] ( identifier[scale_x] , identifier[scale_y] , identifier[no_reset] = identifier[no_reset] )
keyword[if] identifier[self] . identifier[t_] [ literal[string] ]== literal[string] :
identifier[self] . identifier[t_] . identifier[set] ( identifier[autozoom] = literal[string] ) | def zoom_fit(self, no_reset=False):
"""Zoom to fit display window.
Also see :meth:`zoom_to`.
Parameters
----------
no_reset : bool
Do not reset ``autozoom`` setting.
"""
# calculate actual width of the limits/image, considering rotation
try:
(xy_mn, xy_mx) = self.get_limits() # depends on [control=['try'], data=[]]
except ImageViewNoDataError:
return # depends on [control=['except'], data=[]]
try:
(wwidth, wheight) = self.get_window_size()
self.logger.debug('Window size is %dx%d' % (wwidth, wheight))
if self.t_['swap_xy']:
(wwidth, wheight) = (wheight, wwidth) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
except Exception:
return # depends on [control=['except'], data=[]]
# zoom_fit also centers image
with self.suppress_redraw:
self.center_image(no_reset=no_reset)
(ctr_x, ctr_y, rot_deg) = self.get_rotation_info()
# Find min/max extents of limits as shown by viewer
xs = np.array((xy_mn[0], xy_mx[0], xy_mx[0], xy_mn[0]))
ys = np.array((xy_mn[1], xy_mn[1], xy_mx[1], xy_mx[1]))
(x0, y0) = trcalc.rotate_pt(xs, ys, rot_deg, xoff=ctr_x, yoff=ctr_y)
(min_x, min_y) = (np.min(x0), np.min(y0))
(max_x, max_y) = (np.max(x0), np.max(y0))
(width, height) = (max_x - min_x, max_y - min_y)
if min(width, height) <= 0:
return # depends on [control=['if'], data=[]]
# Calculate optimum zoom level to still fit the window size
scale_x = float(wwidth) / (float(width) * self.t_['scale_x_base'])
scale_y = float(wheight) / (float(height) * self.t_['scale_y_base'])
scalefactor = min(scale_x, scale_y)
# account for t_[scale_x/y_base]
scale_x = scalefactor * self.t_['scale_x_base']
scale_y = scalefactor * self.t_['scale_y_base']
self._scale_to(scale_x, scale_y, no_reset=no_reset) # depends on [control=['with'], data=[]]
if self.t_['autozoom'] == 'once':
self.t_.set(autozoom='off') # depends on [control=['if'], data=[]] |
def osm_filter(network_type):
"""
Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string
"""
filters = {}
# drive: select only roads that are drivable by normal 2 wheel drive
# passenger vehicles both private and public
# roads. Filter out un-drivable roads and service roads tagged as parking,
# driveway, or emergency-access
filters['drive'] = ('["highway"!~"cycleway|footway|path|pedestrian|steps'
'|track|proposed|construction|bridleway|abandoned'
'|platform|raceway|service"]'
'["motor_vehicle"!~"no"]["motorcar"!~"no"]'
'["service"!~"parking|parking_aisle|driveway'
'|emergency_access"]')
# walk: select only roads and pathways that allow pedestrian access both
# private and public pathways and roads.
# Filter out limited access roadways and allow service roads
filters['walk'] = ('["highway"!~"motor|proposed|construction|abandoned'
'|platform|raceway"]["foot"!~"no"]'
'["pedestrians"!~"no"]')
if network_type in filters:
osm_filter = filters[network_type]
else:
raise ValueError('unknown network_type "{}"'.format(network_type))
return osm_filter | def function[osm_filter, parameter[network_type]]:
constant[
Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string
]
variable[filters] assign[=] dictionary[[], []]
call[name[filters]][constant[drive]] assign[=] constant[["highway"!~"cycleway|footway|path|pedestrian|steps|track|proposed|construction|bridleway|abandoned|platform|raceway|service"]["motor_vehicle"!~"no"]["motorcar"!~"no"]["service"!~"parking|parking_aisle|driveway|emergency_access"]]
call[name[filters]][constant[walk]] assign[=] constant[["highway"!~"motor|proposed|construction|abandoned|platform|raceway"]["foot"!~"no"]["pedestrians"!~"no"]]
if compare[name[network_type] in name[filters]] begin[:]
variable[osm_filter] assign[=] call[name[filters]][name[network_type]]
return[name[osm_filter]] | keyword[def] identifier[osm_filter] ( identifier[network_type] ):
literal[string]
identifier[filters] ={}
identifier[filters] [ literal[string] ]=( literal[string]
literal[string]
literal[string]
literal[string]
literal[string]
literal[string] )
identifier[filters] [ literal[string] ]=( literal[string]
literal[string]
literal[string] )
keyword[if] identifier[network_type] keyword[in] identifier[filters] :
identifier[osm_filter] = identifier[filters] [ identifier[network_type] ]
keyword[else] :
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[network_type] ))
keyword[return] identifier[osm_filter] | def osm_filter(network_type):
"""
Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string
"""
filters = {}
# drive: select only roads that are drivable by normal 2 wheel drive
# passenger vehicles both private and public
# roads. Filter out un-drivable roads and service roads tagged as parking,
# driveway, or emergency-access
filters['drive'] = '["highway"!~"cycleway|footway|path|pedestrian|steps|track|proposed|construction|bridleway|abandoned|platform|raceway|service"]["motor_vehicle"!~"no"]["motorcar"!~"no"]["service"!~"parking|parking_aisle|driveway|emergency_access"]'
# walk: select only roads and pathways that allow pedestrian access both
# private and public pathways and roads.
# Filter out limited access roadways and allow service roads
filters['walk'] = '["highway"!~"motor|proposed|construction|abandoned|platform|raceway"]["foot"!~"no"]["pedestrians"!~"no"]'
if network_type in filters:
osm_filter = filters[network_type] # depends on [control=['if'], data=['network_type', 'filters']]
else:
raise ValueError('unknown network_type "{}"'.format(network_type))
return osm_filter |
def visit_module(self, node):
"""
A interface will be called when visiting a module.
@param node: node of current module
"""
modulename = node.name.split(".")[-1]
if isTestModule(node.name) and self.moduleContainsTestCase(node):
self._checkTestModuleName(modulename, node) | def function[visit_module, parameter[self, node]]:
constant[
A interface will be called when visiting a module.
@param node: node of current module
]
variable[modulename] assign[=] call[call[name[node].name.split, parameter[constant[.]]]][<ast.UnaryOp object at 0x7da1b26ac640>]
if <ast.BoolOp object at 0x7da1b26aec50> begin[:]
call[name[self]._checkTestModuleName, parameter[name[modulename], name[node]]] | keyword[def] identifier[visit_module] ( identifier[self] , identifier[node] ):
literal[string]
identifier[modulename] = identifier[node] . identifier[name] . identifier[split] ( literal[string] )[- literal[int] ]
keyword[if] identifier[isTestModule] ( identifier[node] . identifier[name] ) keyword[and] identifier[self] . identifier[moduleContainsTestCase] ( identifier[node] ):
identifier[self] . identifier[_checkTestModuleName] ( identifier[modulename] , identifier[node] ) | def visit_module(self, node):
"""
A interface will be called when visiting a module.
@param node: node of current module
"""
modulename = node.name.split('.')[-1]
if isTestModule(node.name) and self.moduleContainsTestCase(node):
self._checkTestModuleName(modulename, node) # depends on [control=['if'], data=[]] |
def ubnd(self):
""" the upper bound vector while respecting log transform
Returns
-------
ubnd : pandas.Series
"""
if not self.istransformed:
return self.pst.parameter_data.parubnd.copy()
else:
ub = self.pst.parameter_data.parubnd.copy()
ub[self.log_indexer] = np.log10(ub[self.log_indexer])
return ub | def function[ubnd, parameter[self]]:
constant[ the upper bound vector while respecting log transform
Returns
-------
ubnd : pandas.Series
]
if <ast.UnaryOp object at 0x7da1b2407c10> begin[:]
return[call[name[self].pst.parameter_data.parubnd.copy, parameter[]]] | keyword[def] identifier[ubnd] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[istransformed] :
keyword[return] identifier[self] . identifier[pst] . identifier[parameter_data] . identifier[parubnd] . identifier[copy] ()
keyword[else] :
identifier[ub] = identifier[self] . identifier[pst] . identifier[parameter_data] . identifier[parubnd] . identifier[copy] ()
identifier[ub] [ identifier[self] . identifier[log_indexer] ]= identifier[np] . identifier[log10] ( identifier[ub] [ identifier[self] . identifier[log_indexer] ])
keyword[return] identifier[ub] | def ubnd(self):
""" the upper bound vector while respecting log transform
Returns
-------
ubnd : pandas.Series
"""
if not self.istransformed:
return self.pst.parameter_data.parubnd.copy() # depends on [control=['if'], data=[]]
else:
ub = self.pst.parameter_data.parubnd.copy()
ub[self.log_indexer] = np.log10(ub[self.log_indexer])
return ub |
def create_bravado_core_config(settings):
"""Create a configuration dict for bravado_core based on pyramid_swagger
settings.
:param settings: pyramid registry settings with configuration for
building a swagger schema
:type settings: dict
:returns: config dict suitable for passing into
bravado_core.spec.Spec.from_dict(..)
:rtype: dict
"""
# Map pyramid_swagger config key -> bravado_core config key
config_keys = {
'pyramid_swagger.enable_request_validation': 'validate_requests',
'pyramid_swagger.enable_response_validation': 'validate_responses',
'pyramid_swagger.enable_swagger_spec_validation': 'validate_swagger_spec',
'pyramid_swagger.use_models': 'use_models',
'pyramid_swagger.user_formats': 'formats',
'pyramid_swagger.include_missing_properties': 'include_missing_properties',
}
configs = {
'use_models': False
}
bravado_core_configs_from_pyramid_swagger_configs = {
bravado_core_key: settings[pyramid_swagger_key]
for pyramid_swagger_key, bravado_core_key in iteritems(config_keys)
if pyramid_swagger_key in settings
}
if bravado_core_configs_from_pyramid_swagger_configs:
warnings.warn(
message='Configs {old_configs} are deprecated, please use {new_configs} instead.'.format(
old_configs=', '.join(k for k, v in sorted(iteritems(config_keys))),
new_configs=', '.join(
'{}{}'.format(BRAVADO_CORE_CONFIG_PREFIX, v)
for k, v in sorted(iteritems(config_keys))
),
),
category=DeprecationWarning,
)
configs.update(bravado_core_configs_from_pyramid_swagger_configs)
configs.update({
key.replace(BRAVADO_CORE_CONFIG_PREFIX, ''): value
for key, value in iteritems(settings)
if key.startswith(BRAVADO_CORE_CONFIG_PREFIX)
})
return configs | def function[create_bravado_core_config, parameter[settings]]:
constant[Create a configuration dict for bravado_core based on pyramid_swagger
settings.
:param settings: pyramid registry settings with configuration for
building a swagger schema
:type settings: dict
:returns: config dict suitable for passing into
bravado_core.spec.Spec.from_dict(..)
:rtype: dict
]
variable[config_keys] assign[=] dictionary[[<ast.Constant object at 0x7da1b2872ad0>, <ast.Constant object at 0x7da1b2872440>, <ast.Constant object at 0x7da1b2871f30>, <ast.Constant object at 0x7da1b2872740>, <ast.Constant object at 0x7da1b2873550>, <ast.Constant object at 0x7da1b2870be0>], [<ast.Constant object at 0x7da1b2872500>, <ast.Constant object at 0x7da1b2872c80>, <ast.Constant object at 0x7da1b28703d0>, <ast.Constant object at 0x7da1b2871f90>, <ast.Constant object at 0x7da1b2870a90>, <ast.Constant object at 0x7da1b2871ba0>]]
variable[configs] assign[=] dictionary[[<ast.Constant object at 0x7da1b2872c50>], [<ast.Constant object at 0x7da1b2870cd0>]]
variable[bravado_core_configs_from_pyramid_swagger_configs] assign[=] <ast.DictComp object at 0x7da1b2873f40>
if name[bravado_core_configs_from_pyramid_swagger_configs] begin[:]
call[name[warnings].warn, parameter[]]
call[name[configs].update, parameter[name[bravado_core_configs_from_pyramid_swagger_configs]]]
call[name[configs].update, parameter[<ast.DictComp object at 0x7da1b2872110>]]
return[name[configs]] | keyword[def] identifier[create_bravado_core_config] ( identifier[settings] ):
literal[string]
identifier[config_keys] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
}
identifier[configs] ={
literal[string] : keyword[False]
}
identifier[bravado_core_configs_from_pyramid_swagger_configs] ={
identifier[bravado_core_key] : identifier[settings] [ identifier[pyramid_swagger_key] ]
keyword[for] identifier[pyramid_swagger_key] , identifier[bravado_core_key] keyword[in] identifier[iteritems] ( identifier[config_keys] )
keyword[if] identifier[pyramid_swagger_key] keyword[in] identifier[settings]
}
keyword[if] identifier[bravado_core_configs_from_pyramid_swagger_configs] :
identifier[warnings] . identifier[warn] (
identifier[message] = literal[string] . identifier[format] (
identifier[old_configs] = literal[string] . identifier[join] ( identifier[k] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[sorted] ( identifier[iteritems] ( identifier[config_keys] ))),
identifier[new_configs] = literal[string] . identifier[join] (
literal[string] . identifier[format] ( identifier[BRAVADO_CORE_CONFIG_PREFIX] , identifier[v] )
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[sorted] ( identifier[iteritems] ( identifier[config_keys] ))
),
),
identifier[category] = identifier[DeprecationWarning] ,
)
identifier[configs] . identifier[update] ( identifier[bravado_core_configs_from_pyramid_swagger_configs] )
identifier[configs] . identifier[update] ({
identifier[key] . identifier[replace] ( identifier[BRAVADO_CORE_CONFIG_PREFIX] , literal[string] ): identifier[value]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[iteritems] ( identifier[settings] )
keyword[if] identifier[key] . identifier[startswith] ( identifier[BRAVADO_CORE_CONFIG_PREFIX] )
})
keyword[return] identifier[configs] | def create_bravado_core_config(settings):
"""Create a configuration dict for bravado_core based on pyramid_swagger
settings.
:param settings: pyramid registry settings with configuration for
building a swagger schema
:type settings: dict
:returns: config dict suitable for passing into
bravado_core.spec.Spec.from_dict(..)
:rtype: dict
"""
# Map pyramid_swagger config key -> bravado_core config key
config_keys = {'pyramid_swagger.enable_request_validation': 'validate_requests', 'pyramid_swagger.enable_response_validation': 'validate_responses', 'pyramid_swagger.enable_swagger_spec_validation': 'validate_swagger_spec', 'pyramid_swagger.use_models': 'use_models', 'pyramid_swagger.user_formats': 'formats', 'pyramid_swagger.include_missing_properties': 'include_missing_properties'}
configs = {'use_models': False}
bravado_core_configs_from_pyramid_swagger_configs = {bravado_core_key: settings[pyramid_swagger_key] for (pyramid_swagger_key, bravado_core_key) in iteritems(config_keys) if pyramid_swagger_key in settings}
if bravado_core_configs_from_pyramid_swagger_configs:
warnings.warn(message='Configs {old_configs} are deprecated, please use {new_configs} instead.'.format(old_configs=', '.join((k for (k, v) in sorted(iteritems(config_keys)))), new_configs=', '.join(('{}{}'.format(BRAVADO_CORE_CONFIG_PREFIX, v) for (k, v) in sorted(iteritems(config_keys))))), category=DeprecationWarning)
configs.update(bravado_core_configs_from_pyramid_swagger_configs) # depends on [control=['if'], data=[]]
configs.update({key.replace(BRAVADO_CORE_CONFIG_PREFIX, ''): value for (key, value) in iteritems(settings) if key.startswith(BRAVADO_CORE_CONFIG_PREFIX)})
return configs |
def _parse_killer(cls, killer):
"""Parses a killer into a dictionary.
Parameters
----------
killer: :class:`str`
The killer's raw HTML string.
Returns
-------
:class:`dict`: A dictionary containing the killer's info.
"""
# If the killer contains a link, it is a player.
if "href" in killer:
killer_dict = {"name": link_content.search(killer).group(1), "player": True}
else:
killer_dict = {"name": killer, "player": False}
# Check if it contains a summon.
m = death_summon.search(killer)
if m:
killer_dict["summon"] = m.group("summon")
return killer_dict | def function[_parse_killer, parameter[cls, killer]]:
constant[Parses a killer into a dictionary.
Parameters
----------
killer: :class:`str`
The killer's raw HTML string.
Returns
-------
:class:`dict`: A dictionary containing the killer's info.
]
if compare[constant[href] in name[killer]] begin[:]
variable[killer_dict] assign[=] dictionary[[<ast.Constant object at 0x7da1b0b6fd60>, <ast.Constant object at 0x7da1b0b6fee0>], [<ast.Call object at 0x7da1b0b6ff10>, <ast.Constant object at 0x7da1b0b6d300>]]
variable[m] assign[=] call[name[death_summon].search, parameter[name[killer]]]
if name[m] begin[:]
call[name[killer_dict]][constant[summon]] assign[=] call[name[m].group, parameter[constant[summon]]]
return[name[killer_dict]] | keyword[def] identifier[_parse_killer] ( identifier[cls] , identifier[killer] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[killer] :
identifier[killer_dict] ={ literal[string] : identifier[link_content] . identifier[search] ( identifier[killer] ). identifier[group] ( literal[int] ), literal[string] : keyword[True] }
keyword[else] :
identifier[killer_dict] ={ literal[string] : identifier[killer] , literal[string] : keyword[False] }
identifier[m] = identifier[death_summon] . identifier[search] ( identifier[killer] )
keyword[if] identifier[m] :
identifier[killer_dict] [ literal[string] ]= identifier[m] . identifier[group] ( literal[string] )
keyword[return] identifier[killer_dict] | def _parse_killer(cls, killer):
"""Parses a killer into a dictionary.
Parameters
----------
killer: :class:`str`
The killer's raw HTML string.
Returns
-------
:class:`dict`: A dictionary containing the killer's info.
"""
# If the killer contains a link, it is a player.
if 'href' in killer:
killer_dict = {'name': link_content.search(killer).group(1), 'player': True} # depends on [control=['if'], data=['killer']]
else:
killer_dict = {'name': killer, 'player': False}
# Check if it contains a summon.
m = death_summon.search(killer)
if m:
killer_dict['summon'] = m.group('summon') # depends on [control=['if'], data=[]]
return killer_dict |
def emit(self, record):
""" pymongo expects a dict """
msg = self.format(record)
if not isinstance(msg, dict):
msg = json.loads(msg)
self.collection.insert(msg) | def function[emit, parameter[self, record]]:
constant[ pymongo expects a dict ]
variable[msg] assign[=] call[name[self].format, parameter[name[record]]]
if <ast.UnaryOp object at 0x7da1b03ba7a0> begin[:]
variable[msg] assign[=] call[name[json].loads, parameter[name[msg]]]
call[name[self].collection.insert, parameter[name[msg]]] | keyword[def] identifier[emit] ( identifier[self] , identifier[record] ):
literal[string]
identifier[msg] = identifier[self] . identifier[format] ( identifier[record] )
keyword[if] keyword[not] identifier[isinstance] ( identifier[msg] , identifier[dict] ):
identifier[msg] = identifier[json] . identifier[loads] ( identifier[msg] )
identifier[self] . identifier[collection] . identifier[insert] ( identifier[msg] ) | def emit(self, record):
""" pymongo expects a dict """
msg = self.format(record)
if not isinstance(msg, dict):
msg = json.loads(msg) # depends on [control=['if'], data=[]]
self.collection.insert(msg) |
def _emulated(self, timeout=None):
"""Get the next message avaiable in the queue.
:returns: The message and the name of the queue it came from as
a tuple.
:raises Empty: If there are no more items in any of the queues.
"""
# A set of queues we've already tried.
tried = set()
while True:
# Get the next queue in the cycle, and try to get an item off it.
try:
queue = self.cycle.next()
except StopIteration:
raise Empty("No queues registered")
try:
item = queue.get()
except Empty:
# raises Empty when we've tried all of them.
tried.add(queue.name)
if tried == self.all:
raise
else:
return item, queue.name | def function[_emulated, parameter[self, timeout]]:
constant[Get the next message avaiable in the queue.
:returns: The message and the name of the queue it came from as
a tuple.
:raises Empty: If there are no more items in any of the queues.
]
variable[tried] assign[=] call[name[set], parameter[]]
while constant[True] begin[:]
<ast.Try object at 0x7da1b09c76a0>
<ast.Try object at 0x7da1b0ae2560> | keyword[def] identifier[_emulated] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[tried] = identifier[set] ()
keyword[while] keyword[True] :
keyword[try] :
identifier[queue] = identifier[self] . identifier[cycle] . identifier[next] ()
keyword[except] identifier[StopIteration] :
keyword[raise] identifier[Empty] ( literal[string] )
keyword[try] :
identifier[item] = identifier[queue] . identifier[get] ()
keyword[except] identifier[Empty] :
identifier[tried] . identifier[add] ( identifier[queue] . identifier[name] )
keyword[if] identifier[tried] == identifier[self] . identifier[all] :
keyword[raise]
keyword[else] :
keyword[return] identifier[item] , identifier[queue] . identifier[name] | def _emulated(self, timeout=None):
"""Get the next message avaiable in the queue.
:returns: The message and the name of the queue it came from as
a tuple.
:raises Empty: If there are no more items in any of the queues.
"""
# A set of queues we've already tried.
tried = set()
while True:
# Get the next queue in the cycle, and try to get an item off it.
try:
queue = self.cycle.next() # depends on [control=['try'], data=[]]
except StopIteration:
raise Empty('No queues registered') # depends on [control=['except'], data=[]]
try:
item = queue.get() # depends on [control=['try'], data=[]]
except Empty:
# raises Empty when we've tried all of them.
tried.add(queue.name)
if tried == self.all:
raise # depends on [control=['if'], data=[]] # depends on [control=['except'], data=[]]
else:
return (item, queue.name) # depends on [control=['while'], data=[]] |
def pack(self, value=None):
"""Pack a StatsReply using the object's attributes.
This method will pack the attribute body and multipart_type before pack
the StatsReply object, then will return this struct as a binary data.
Returns:
stats_reply_packed (bytes): Binary data with StatsReply packed.
"""
buff = self.body
if not value:
value = self.body
if value:
if isinstance(value, (list, FixedTypeList)):
obj = self._get_body_instance()
obj.extend(value)
elif hasattr(value, 'pack'):
obj = value
self.body = obj.pack()
multipart_packed = super().pack()
self.body = buff
return multipart_packed | def function[pack, parameter[self, value]]:
constant[Pack a StatsReply using the object's attributes.
This method will pack the attribute body and multipart_type before pack
the StatsReply object, then will return this struct as a binary data.
Returns:
stats_reply_packed (bytes): Binary data with StatsReply packed.
]
variable[buff] assign[=] name[self].body
if <ast.UnaryOp object at 0x7da20c7c8040> begin[:]
variable[value] assign[=] name[self].body
if name[value] begin[:]
if call[name[isinstance], parameter[name[value], tuple[[<ast.Name object at 0x7da20c7ca4d0>, <ast.Name object at 0x7da20c6c62f0>]]]] begin[:]
variable[obj] assign[=] call[name[self]._get_body_instance, parameter[]]
call[name[obj].extend, parameter[name[value]]]
name[self].body assign[=] call[name[obj].pack, parameter[]]
variable[multipart_packed] assign[=] call[call[name[super], parameter[]].pack, parameter[]]
name[self].body assign[=] name[buff]
return[name[multipart_packed]] | keyword[def] identifier[pack] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
identifier[buff] = identifier[self] . identifier[body]
keyword[if] keyword[not] identifier[value] :
identifier[value] = identifier[self] . identifier[body]
keyword[if] identifier[value] :
keyword[if] identifier[isinstance] ( identifier[value] ,( identifier[list] , identifier[FixedTypeList] )):
identifier[obj] = identifier[self] . identifier[_get_body_instance] ()
identifier[obj] . identifier[extend] ( identifier[value] )
keyword[elif] identifier[hasattr] ( identifier[value] , literal[string] ):
identifier[obj] = identifier[value]
identifier[self] . identifier[body] = identifier[obj] . identifier[pack] ()
identifier[multipart_packed] = identifier[super] (). identifier[pack] ()
identifier[self] . identifier[body] = identifier[buff]
keyword[return] identifier[multipart_packed] | def pack(self, value=None):
"""Pack a StatsReply using the object's attributes.
This method will pack the attribute body and multipart_type before pack
the StatsReply object, then will return this struct as a binary data.
Returns:
stats_reply_packed (bytes): Binary data with StatsReply packed.
"""
buff = self.body
if not value:
value = self.body # depends on [control=['if'], data=[]]
if value:
if isinstance(value, (list, FixedTypeList)):
obj = self._get_body_instance()
obj.extend(value) # depends on [control=['if'], data=[]]
elif hasattr(value, 'pack'):
obj = value # depends on [control=['if'], data=[]]
self.body = obj.pack() # depends on [control=['if'], data=[]]
multipart_packed = super().pack()
self.body = buff
return multipart_packed |
def CreateNetworkConnectivityNHDPlus(in_drainage_line,
out_connectivity_file,
file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and DIVERGENCE fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivityNHDPlus
CreateNetworkConnectivityNHDPlus(
in_drainage_line='/path/to/drainageline.shp',
out_connectivity_file='/path/to/rapid_connect.csv')
"""
ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile = \
open_shapefile(in_drainage_line, file_geodatabase)
ogr_drainage_line_definition = \
ogr_drainage_line_shapefile_lyr.GetLayerDefn()
orig_field_names = []
for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
orig_field_names.append(
ogr_drainage_line_definition.GetFieldDefn(idx).GetName())
upper_field_names = [field.upper() for field in orig_field_names]
def get_field_name_index(upper_field_name, _upper_field_names):
"""
returns index of field name
"""
try:
return _upper_field_names.index(upper_field_name)
except ValueError:
raise IndexError("{0} not found in shapefile .."
.format(_upper_field_names))
rivid_field = \
orig_field_names[get_field_name_index('COMID', upper_field_names)]
fromnode_field = \
orig_field_names[get_field_name_index('FROMNODE', upper_field_names)]
tonode_field = \
orig_field_names[get_field_name_index('TONODE', upper_field_names)]
divergence_field =\
orig_field_names[get_field_name_index('DIVERGENCE', upper_field_names)]
number_of_features = ogr_drainage_line_shapefile_lyr.GetFeatureCount()
rivid_list = np.zeros(number_of_features, dtype=np.int32)
fromnode_list = np.zeros(number_of_features, dtype=np.int32)
tonode_list = np.zeros(number_of_features, dtype=np.int32)
divergence_list = np.zeros(number_of_features, dtype=np.int32)
for feature_idx, catchment_feature in \
enumerate(ogr_drainage_line_shapefile_lyr):
rivid_list[feature_idx] = catchment_feature.GetField(rivid_field)
fromnode_list[feature_idx] = catchment_feature.GetField(fromnode_field)
tonode_list[feature_idx] = catchment_feature.GetField(tonode_field)
divergence_list[feature_idx] = \
catchment_feature.GetField(divergence_field)
del ogr_drainage_line_shapefile
# -------------------------------------------------------------------------
# Compute connectivity, based on:
# https://github.com/c-h-david/rrr/blob/master/src/rrr_riv_tot_gen_all_nhdplus.py
# -------------------------------------------------------------------------
fromnode_list[fromnode_list == 0] = -9999
# Some NHDPlus v1 reaches have FLOWDIR='With Digitized'
# but no info in VAA table
fromnode_list[divergence_list == 2] = -9999
# Virtually disconnect the upstream node of all minor divergences
del divergence_list # delete information in list
next_down_id_list = np.zeros(number_of_features, dtype=np.int32)
for rivid_index in xrange(len(rivid_list)):
try:
next_down_id_list[rivid_index] = \
rivid_list[
np.where(fromnode_list == tonode_list[rivid_index])[0][0]]
except IndexError:
# this is an outlet
next_down_id_list[rivid_index] = -1
# determine the downstream reach for each reach
# empty unecessary lists
del fromnode_list
del tonode_list
StreamIDNextDownIDToConnectivity(rivid_list,
next_down_id_list,
out_connectivity_file) | def function[CreateNetworkConnectivityNHDPlus, parameter[in_drainage_line, out_connectivity_file, file_geodatabase]]:
constant[
Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and DIVERGENCE fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivityNHDPlus
CreateNetworkConnectivityNHDPlus(
in_drainage_line='/path/to/drainageline.shp',
out_connectivity_file='/path/to/rapid_connect.csv')
]
<ast.Tuple object at 0x7da18dc07370> assign[=] call[name[open_shapefile], parameter[name[in_drainage_line], name[file_geodatabase]]]
variable[ogr_drainage_line_definition] assign[=] call[name[ogr_drainage_line_shapefile_lyr].GetLayerDefn, parameter[]]
variable[orig_field_names] assign[=] list[[]]
for taget[name[idx]] in starred[call[name[xrange], parameter[call[name[ogr_drainage_line_definition].GetFieldCount, parameter[]]]]] begin[:]
call[name[orig_field_names].append, parameter[call[call[name[ogr_drainage_line_definition].GetFieldDefn, parameter[name[idx]]].GetName, parameter[]]]]
variable[upper_field_names] assign[=] <ast.ListComp object at 0x7da18dc040d0>
def function[get_field_name_index, parameter[upper_field_name, _upper_field_names]]:
constant[
returns index of field name
]
<ast.Try object at 0x7da18dc06ad0>
variable[rivid_field] assign[=] call[name[orig_field_names]][call[name[get_field_name_index], parameter[constant[COMID], name[upper_field_names]]]]
variable[fromnode_field] assign[=] call[name[orig_field_names]][call[name[get_field_name_index], parameter[constant[FROMNODE], name[upper_field_names]]]]
variable[tonode_field] assign[=] call[name[orig_field_names]][call[name[get_field_name_index], parameter[constant[TONODE], name[upper_field_names]]]]
variable[divergence_field] assign[=] call[name[orig_field_names]][call[name[get_field_name_index], parameter[constant[DIVERGENCE], name[upper_field_names]]]]
variable[number_of_features] assign[=] call[name[ogr_drainage_line_shapefile_lyr].GetFeatureCount, parameter[]]
variable[rivid_list] assign[=] call[name[np].zeros, parameter[name[number_of_features]]]
variable[fromnode_list] assign[=] call[name[np].zeros, parameter[name[number_of_features]]]
variable[tonode_list] assign[=] call[name[np].zeros, parameter[name[number_of_features]]]
variable[divergence_list] assign[=] call[name[np].zeros, parameter[name[number_of_features]]]
for taget[tuple[[<ast.Name object at 0x7da18dc04250>, <ast.Name object at 0x7da18dc05720>]]] in starred[call[name[enumerate], parameter[name[ogr_drainage_line_shapefile_lyr]]]] begin[:]
call[name[rivid_list]][name[feature_idx]] assign[=] call[name[catchment_feature].GetField, parameter[name[rivid_field]]]
call[name[fromnode_list]][name[feature_idx]] assign[=] call[name[catchment_feature].GetField, parameter[name[fromnode_field]]]
call[name[tonode_list]][name[feature_idx]] assign[=] call[name[catchment_feature].GetField, parameter[name[tonode_field]]]
call[name[divergence_list]][name[feature_idx]] assign[=] call[name[catchment_feature].GetField, parameter[name[divergence_field]]]
<ast.Delete object at 0x7da18dc051e0>
call[name[fromnode_list]][compare[name[fromnode_list] equal[==] constant[0]]] assign[=] <ast.UnaryOp object at 0x7da1b26af3a0>
call[name[fromnode_list]][compare[name[divergence_list] equal[==] constant[2]]] assign[=] <ast.UnaryOp object at 0x7da1b26aee30>
<ast.Delete object at 0x7da1b26aeaa0>
variable[next_down_id_list] assign[=] call[name[np].zeros, parameter[name[number_of_features]]]
for taget[name[rivid_index]] in starred[call[name[xrange], parameter[call[name[len], parameter[name[rivid_list]]]]]] begin[:]
<ast.Try object at 0x7da1b26ac2b0>
<ast.Delete object at 0x7da1b26acfd0>
<ast.Delete object at 0x7da1b26ae500>
call[name[StreamIDNextDownIDToConnectivity], parameter[name[rivid_list], name[next_down_id_list], name[out_connectivity_file]]] | keyword[def] identifier[CreateNetworkConnectivityNHDPlus] ( identifier[in_drainage_line] ,
identifier[out_connectivity_file] ,
identifier[file_geodatabase] = keyword[None] ):
literal[string]
identifier[ogr_drainage_line_shapefile_lyr] , identifier[ogr_drainage_line_shapefile] = identifier[open_shapefile] ( identifier[in_drainage_line] , identifier[file_geodatabase] )
identifier[ogr_drainage_line_definition] = identifier[ogr_drainage_line_shapefile_lyr] . identifier[GetLayerDefn] ()
identifier[orig_field_names] =[]
keyword[for] identifier[idx] keyword[in] identifier[xrange] ( identifier[ogr_drainage_line_definition] . identifier[GetFieldCount] ()):
identifier[orig_field_names] . identifier[append] (
identifier[ogr_drainage_line_definition] . identifier[GetFieldDefn] ( identifier[idx] ). identifier[GetName] ())
identifier[upper_field_names] =[ identifier[field] . identifier[upper] () keyword[for] identifier[field] keyword[in] identifier[orig_field_names] ]
keyword[def] identifier[get_field_name_index] ( identifier[upper_field_name] , identifier[_upper_field_names] ):
literal[string]
keyword[try] :
keyword[return] identifier[_upper_field_names] . identifier[index] ( identifier[upper_field_name] )
keyword[except] identifier[ValueError] :
keyword[raise] identifier[IndexError] ( literal[string]
. identifier[format] ( identifier[_upper_field_names] ))
identifier[rivid_field] = identifier[orig_field_names] [ identifier[get_field_name_index] ( literal[string] , identifier[upper_field_names] )]
identifier[fromnode_field] = identifier[orig_field_names] [ identifier[get_field_name_index] ( literal[string] , identifier[upper_field_names] )]
identifier[tonode_field] = identifier[orig_field_names] [ identifier[get_field_name_index] ( literal[string] , identifier[upper_field_names] )]
identifier[divergence_field] = identifier[orig_field_names] [ identifier[get_field_name_index] ( literal[string] , identifier[upper_field_names] )]
identifier[number_of_features] = identifier[ogr_drainage_line_shapefile_lyr] . identifier[GetFeatureCount] ()
identifier[rivid_list] = identifier[np] . identifier[zeros] ( identifier[number_of_features] , identifier[dtype] = identifier[np] . identifier[int32] )
identifier[fromnode_list] = identifier[np] . identifier[zeros] ( identifier[number_of_features] , identifier[dtype] = identifier[np] . identifier[int32] )
identifier[tonode_list] = identifier[np] . identifier[zeros] ( identifier[number_of_features] , identifier[dtype] = identifier[np] . identifier[int32] )
identifier[divergence_list] = identifier[np] . identifier[zeros] ( identifier[number_of_features] , identifier[dtype] = identifier[np] . identifier[int32] )
keyword[for] identifier[feature_idx] , identifier[catchment_feature] keyword[in] identifier[enumerate] ( identifier[ogr_drainage_line_shapefile_lyr] ):
identifier[rivid_list] [ identifier[feature_idx] ]= identifier[catchment_feature] . identifier[GetField] ( identifier[rivid_field] )
identifier[fromnode_list] [ identifier[feature_idx] ]= identifier[catchment_feature] . identifier[GetField] ( identifier[fromnode_field] )
identifier[tonode_list] [ identifier[feature_idx] ]= identifier[catchment_feature] . identifier[GetField] ( identifier[tonode_field] )
identifier[divergence_list] [ identifier[feature_idx] ]= identifier[catchment_feature] . identifier[GetField] ( identifier[divergence_field] )
keyword[del] identifier[ogr_drainage_line_shapefile]
identifier[fromnode_list] [ identifier[fromnode_list] == literal[int] ]=- literal[int]
identifier[fromnode_list] [ identifier[divergence_list] == literal[int] ]=- literal[int]
keyword[del] identifier[divergence_list]
identifier[next_down_id_list] = identifier[np] . identifier[zeros] ( identifier[number_of_features] , identifier[dtype] = identifier[np] . identifier[int32] )
keyword[for] identifier[rivid_index] keyword[in] identifier[xrange] ( identifier[len] ( identifier[rivid_list] )):
keyword[try] :
identifier[next_down_id_list] [ identifier[rivid_index] ]= identifier[rivid_list] [
identifier[np] . identifier[where] ( identifier[fromnode_list] == identifier[tonode_list] [ identifier[rivid_index] ])[ literal[int] ][ literal[int] ]]
keyword[except] identifier[IndexError] :
identifier[next_down_id_list] [ identifier[rivid_index] ]=- literal[int]
keyword[del] identifier[fromnode_list]
keyword[del] identifier[tonode_list]
identifier[StreamIDNextDownIDToConnectivity] ( identifier[rivid_list] ,
identifier[next_down_id_list] ,
identifier[out_connectivity_file] ) | def CreateNetworkConnectivityNHDPlus(in_drainage_line, out_connectivity_file, file_geodatabase=None):
"""
Creates Network Connectivity input CSV file for RAPID
based on the NHDPlus drainage lines with
COMID, FROMNODE, TONODE, and DIVERGENCE fields.
Parameters
----------
in_drainage_line: str
Path to the stream network (i.e. Drainage Line) shapefile.
out_connectivity_file: str
The path to the output connectivity file.
file_geodatabase: str, optional
Path to the file geodatabase. If you use this option,
in_drainage_line is the name of the stream network feature class
(WARNING: Not always stable with GDAL).
Example::
from RAPIDpy.gis.network import CreateNetworkConnectivityNHDPlus
CreateNetworkConnectivityNHDPlus(
in_drainage_line='/path/to/drainageline.shp',
out_connectivity_file='/path/to/rapid_connect.csv')
"""
(ogr_drainage_line_shapefile_lyr, ogr_drainage_line_shapefile) = open_shapefile(in_drainage_line, file_geodatabase)
ogr_drainage_line_definition = ogr_drainage_line_shapefile_lyr.GetLayerDefn()
orig_field_names = []
for idx in xrange(ogr_drainage_line_definition.GetFieldCount()):
orig_field_names.append(ogr_drainage_line_definition.GetFieldDefn(idx).GetName()) # depends on [control=['for'], data=['idx']]
upper_field_names = [field.upper() for field in orig_field_names]
def get_field_name_index(upper_field_name, _upper_field_names):
"""
returns index of field name
"""
try:
return _upper_field_names.index(upper_field_name) # depends on [control=['try'], data=[]]
except ValueError:
raise IndexError('{0} not found in shapefile ..'.format(_upper_field_names)) # depends on [control=['except'], data=[]]
rivid_field = orig_field_names[get_field_name_index('COMID', upper_field_names)]
fromnode_field = orig_field_names[get_field_name_index('FROMNODE', upper_field_names)]
tonode_field = orig_field_names[get_field_name_index('TONODE', upper_field_names)]
divergence_field = orig_field_names[get_field_name_index('DIVERGENCE', upper_field_names)]
number_of_features = ogr_drainage_line_shapefile_lyr.GetFeatureCount()
rivid_list = np.zeros(number_of_features, dtype=np.int32)
fromnode_list = np.zeros(number_of_features, dtype=np.int32)
tonode_list = np.zeros(number_of_features, dtype=np.int32)
divergence_list = np.zeros(number_of_features, dtype=np.int32)
for (feature_idx, catchment_feature) in enumerate(ogr_drainage_line_shapefile_lyr):
rivid_list[feature_idx] = catchment_feature.GetField(rivid_field)
fromnode_list[feature_idx] = catchment_feature.GetField(fromnode_field)
tonode_list[feature_idx] = catchment_feature.GetField(tonode_field)
divergence_list[feature_idx] = catchment_feature.GetField(divergence_field) # depends on [control=['for'], data=[]]
del ogr_drainage_line_shapefile
# -------------------------------------------------------------------------
# Compute connectivity, based on:
# https://github.com/c-h-david/rrr/blob/master/src/rrr_riv_tot_gen_all_nhdplus.py
# -------------------------------------------------------------------------
fromnode_list[fromnode_list == 0] = -9999
# Some NHDPlus v1 reaches have FLOWDIR='With Digitized'
# but no info in VAA table
fromnode_list[divergence_list == 2] = -9999
# Virtually disconnect the upstream node of all minor divergences
del divergence_list # delete information in list
next_down_id_list = np.zeros(number_of_features, dtype=np.int32)
for rivid_index in xrange(len(rivid_list)):
try:
next_down_id_list[rivid_index] = rivid_list[np.where(fromnode_list == tonode_list[rivid_index])[0][0]] # depends on [control=['try'], data=[]]
except IndexError:
# this is an outlet
next_down_id_list[rivid_index] = -1 # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['rivid_index']]
# determine the downstream reach for each reach
# empty unecessary lists
del fromnode_list
del tonode_list
StreamIDNextDownIDToConnectivity(rivid_list, next_down_id_list, out_connectivity_file) |
def add_choice(self, choice, name='', identifier=None):
"""stub"""
if not isinstance(choice, DisplayText):
raise InvalidArgument('choice is not a displayText object')
if identifier is None:
identifier = str(ObjectId())
current_identifiers = [c['id'] for c in self.my_osid_object_form._my_map['choices']]
if identifier not in current_identifiers:
choice = {
'id': identifier,
'texts': [self._dict_display_text(choice)],
'name': name
}
self.my_osid_object_form._my_map['choices'].append(choice)
else:
for current_choice in self.my_osid_object_form._my_map['choices']:
if current_choice['id'] == identifier:
self.add_or_replace_value('texts', choice, dictionary=current_choice)
choice = current_choice
return choice | def function[add_choice, parameter[self, choice, name, identifier]]:
constant[stub]
if <ast.UnaryOp object at 0x7da1b0915d20> begin[:]
<ast.Raise object at 0x7da1b0916500>
if compare[name[identifier] is constant[None]] begin[:]
variable[identifier] assign[=] call[name[str], parameter[call[name[ObjectId], parameter[]]]]
variable[current_identifiers] assign[=] <ast.ListComp object at 0x7da1b0914790>
if compare[name[identifier] <ast.NotIn object at 0x7da2590d7190> name[current_identifiers]] begin[:]
variable[choice] assign[=] dictionary[[<ast.Constant object at 0x7da1b0915f60>, <ast.Constant object at 0x7da1b0915c00>, <ast.Constant object at 0x7da1b0916aa0>], [<ast.Name object at 0x7da1b0916ec0>, <ast.List object at 0x7da1b09154b0>, <ast.Name object at 0x7da1b09154e0>]]
call[call[name[self].my_osid_object_form._my_map][constant[choices]].append, parameter[name[choice]]]
return[name[choice]] | keyword[def] identifier[add_choice] ( identifier[self] , identifier[choice] , identifier[name] = literal[string] , identifier[identifier] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[choice] , identifier[DisplayText] ):
keyword[raise] identifier[InvalidArgument] ( literal[string] )
keyword[if] identifier[identifier] keyword[is] keyword[None] :
identifier[identifier] = identifier[str] ( identifier[ObjectId] ())
identifier[current_identifiers] =[ identifier[c] [ literal[string] ] keyword[for] identifier[c] keyword[in] identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ]]
keyword[if] identifier[identifier] keyword[not] keyword[in] identifier[current_identifiers] :
identifier[choice] ={
literal[string] : identifier[identifier] ,
literal[string] :[ identifier[self] . identifier[_dict_display_text] ( identifier[choice] )],
literal[string] : identifier[name]
}
identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ]. identifier[append] ( identifier[choice] )
keyword[else] :
keyword[for] identifier[current_choice] keyword[in] identifier[self] . identifier[my_osid_object_form] . identifier[_my_map] [ literal[string] ]:
keyword[if] identifier[current_choice] [ literal[string] ]== identifier[identifier] :
identifier[self] . identifier[add_or_replace_value] ( literal[string] , identifier[choice] , identifier[dictionary] = identifier[current_choice] )
identifier[choice] = identifier[current_choice]
keyword[return] identifier[choice] | def add_choice(self, choice, name='', identifier=None):
"""stub"""
if not isinstance(choice, DisplayText):
raise InvalidArgument('choice is not a displayText object') # depends on [control=['if'], data=[]]
if identifier is None:
identifier = str(ObjectId()) # depends on [control=['if'], data=['identifier']]
current_identifiers = [c['id'] for c in self.my_osid_object_form._my_map['choices']]
if identifier not in current_identifiers:
choice = {'id': identifier, 'texts': [self._dict_display_text(choice)], 'name': name}
self.my_osid_object_form._my_map['choices'].append(choice) # depends on [control=['if'], data=['identifier']]
else:
for current_choice in self.my_osid_object_form._my_map['choices']:
if current_choice['id'] == identifier:
self.add_or_replace_value('texts', choice, dictionary=current_choice)
choice = current_choice # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['current_choice']]
return choice |
def _get_counts_in_1x(data_is_basepairs):
""" Read read length and genome size from the config and calculate
the approximate number of counts (or base pairs) in 1x of depth
"""
read_length = float(getattr(config, 'preseq', {}).get('read_length', 0))
genome_size = getattr(config, 'preseq', {}).get('genome_size')
if genome_size:
try:
genome_size = float(genome_size)
except ValueError:
presets = {'hg19_genome': 2897310462,
'hg38_genome': 3049315783,
'mm10_genome': 2652783500}
if genome_size in presets:
genome_size = presets[genome_size]
else:
log.warn('The size for genome ' + genome_size + ' is unknown to MultiQC, ' +
'please specify it explicitly or choose one of the following: ' +
', '.join(presets.keys()) + '. Falling back to molecule counts.')
genome_size = None
if genome_size:
if data_is_basepairs:
return genome_size
elif read_length:
return genome_size / read_length
else:
return None | def function[_get_counts_in_1x, parameter[data_is_basepairs]]:
constant[ Read read length and genome size from the config and calculate
the approximate number of counts (or base pairs) in 1x of depth
]
variable[read_length] assign[=] call[name[float], parameter[call[call[name[getattr], parameter[name[config], constant[preseq], dictionary[[], []]]].get, parameter[constant[read_length], constant[0]]]]]
variable[genome_size] assign[=] call[call[name[getattr], parameter[name[config], constant[preseq], dictionary[[], []]]].get, parameter[constant[genome_size]]]
if name[genome_size] begin[:]
<ast.Try object at 0x7da18f00fb20>
if name[genome_size] begin[:]
if name[data_is_basepairs] begin[:]
return[name[genome_size]] | keyword[def] identifier[_get_counts_in_1x] ( identifier[data_is_basepairs] ):
literal[string]
identifier[read_length] = identifier[float] ( identifier[getattr] ( identifier[config] , literal[string] ,{}). identifier[get] ( literal[string] , literal[int] ))
identifier[genome_size] = identifier[getattr] ( identifier[config] , literal[string] ,{}). identifier[get] ( literal[string] )
keyword[if] identifier[genome_size] :
keyword[try] :
identifier[genome_size] = identifier[float] ( identifier[genome_size] )
keyword[except] identifier[ValueError] :
identifier[presets] ={ literal[string] : literal[int] ,
literal[string] : literal[int] ,
literal[string] : literal[int] }
keyword[if] identifier[genome_size] keyword[in] identifier[presets] :
identifier[genome_size] = identifier[presets] [ identifier[genome_size] ]
keyword[else] :
identifier[log] . identifier[warn] ( literal[string] + identifier[genome_size] + literal[string] +
literal[string] +
literal[string] . identifier[join] ( identifier[presets] . identifier[keys] ())+ literal[string] )
identifier[genome_size] = keyword[None]
keyword[if] identifier[genome_size] :
keyword[if] identifier[data_is_basepairs] :
keyword[return] identifier[genome_size]
keyword[elif] identifier[read_length] :
keyword[return] identifier[genome_size] / identifier[read_length]
keyword[else] :
keyword[return] keyword[None] | def _get_counts_in_1x(data_is_basepairs):
""" Read read length and genome size from the config and calculate
the approximate number of counts (or base pairs) in 1x of depth
"""
read_length = float(getattr(config, 'preseq', {}).get('read_length', 0))
genome_size = getattr(config, 'preseq', {}).get('genome_size')
if genome_size:
try:
genome_size = float(genome_size) # depends on [control=['try'], data=[]]
except ValueError:
presets = {'hg19_genome': 2897310462, 'hg38_genome': 3049315783, 'mm10_genome': 2652783500}
if genome_size in presets:
genome_size = presets[genome_size] # depends on [control=['if'], data=['genome_size', 'presets']]
else:
log.warn('The size for genome ' + genome_size + ' is unknown to MultiQC, ' + 'please specify it explicitly or choose one of the following: ' + ', '.join(presets.keys()) + '. Falling back to molecule counts.')
genome_size = None # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]]
if genome_size:
if data_is_basepairs:
return genome_size # depends on [control=['if'], data=[]]
elif read_length:
return genome_size / read_length # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
else:
return None |
def diff(models, filename, pytest_args, exclusive, skip, solver,
experimental, custom_tests, custom_config):
"""
Take a snapshot of all the supplied models and generate a diff report.
MODELS: List of paths to two or more model files.
"""
if not any(a.startswith("--tb") for a in pytest_args):
pytest_args = ["--tb", "no"] + pytest_args
# Add further directories to search for tests.
pytest_args.extend(custom_tests)
config = ReportConfiguration.load()
# Update the default test configuration with custom ones (if any).
for custom in custom_config:
config.merge(ReportConfiguration.load(custom))
# Build the diff report specific data structure
diff_results = dict()
model_and_model_ver_tuple = list()
for model_path in models:
try:
model_filename = os.path.basename(model_path)
diff_results.setdefault(model_filename, dict())
model, model_ver, notifications = api.validate_model(model_path)
if model is None:
head, tail = os.path.split(filename)
report_path = os.path.join(
head, '{}_structural_report.html'.format(model_filename))
api.validation_report(
model_path, notifications, report_path)
LOGGER.critical(
"The model {} could not be loaded due to SBML errors "
"reported in {}.".format(model_filename, report_path))
continue
model.solver = solver
model_and_model_ver_tuple.append((model, model_ver))
except (IOError, SBMLError):
LOGGER.debug(exc_info=True)
LOGGER.warning("An error occurred while loading the model '%s'. "
"Skipping.", model_filename)
# Abort the diff report unless at least two models can be loaded
# successfully.
if len(model_and_model_ver_tuple) < 2:
LOGGER.critical(
"Out of the %d provided models only %d could be loaded. Please, "
"check if the models that could not be loaded are valid SBML. "
"Aborting.",
len(models), len(model_and_model_ver_tuple))
sys.exit(1)
# Running pytest in individual processes to avoid interference
partial_test_diff = partial(_test_diff, pytest_args=pytest_args,
skip=skip, exclusive=exclusive,
experimental=experimental)
pool = Pool(min(len(models), cpu_count()))
results = pool.map(partial_test_diff, model_and_model_ver_tuple)
for model_path, result in zip(models, results):
model_filename = os.path.basename(model_path)
diff_results[model_filename] = result
with open(filename, "w", encoding="utf-8") as file_handle:
LOGGER.info("Writing diff report to '%s'.", filename)
file_handle.write(api.diff_report(diff_results, config)) | def function[diff, parameter[models, filename, pytest_args, exclusive, skip, solver, experimental, custom_tests, custom_config]]:
constant[
Take a snapshot of all the supplied models and generate a diff report.
MODELS: List of paths to two or more model files.
]
if <ast.UnaryOp object at 0x7da1b0525990> begin[:]
variable[pytest_args] assign[=] binary_operation[list[[<ast.Constant object at 0x7da1b0624310>, <ast.Constant object at 0x7da1b06250c0>]] + name[pytest_args]]
call[name[pytest_args].extend, parameter[name[custom_tests]]]
variable[config] assign[=] call[name[ReportConfiguration].load, parameter[]]
for taget[name[custom]] in starred[name[custom_config]] begin[:]
call[name[config].merge, parameter[call[name[ReportConfiguration].load, parameter[name[custom]]]]]
variable[diff_results] assign[=] call[name[dict], parameter[]]
variable[model_and_model_ver_tuple] assign[=] call[name[list], parameter[]]
for taget[name[model_path]] in starred[name[models]] begin[:]
<ast.Try object at 0x7da20c76f100>
if compare[call[name[len], parameter[name[model_and_model_ver_tuple]]] less[<] constant[2]] begin[:]
call[name[LOGGER].critical, parameter[constant[Out of the %d provided models only %d could be loaded. Please, check if the models that could not be loaded are valid SBML. Aborting.], call[name[len], parameter[name[models]]], call[name[len], parameter[name[model_and_model_ver_tuple]]]]]
call[name[sys].exit, parameter[constant[1]]]
variable[partial_test_diff] assign[=] call[name[partial], parameter[name[_test_diff]]]
variable[pool] assign[=] call[name[Pool], parameter[call[name[min], parameter[call[name[len], parameter[name[models]]], call[name[cpu_count], parameter[]]]]]]
variable[results] assign[=] call[name[pool].map, parameter[name[partial_test_diff], name[model_and_model_ver_tuple]]]
for taget[tuple[[<ast.Name object at 0x7da1b0667580>, <ast.Name object at 0x7da1b0666c80>]]] in starred[call[name[zip], parameter[name[models], name[results]]]] begin[:]
variable[model_filename] assign[=] call[name[os].path.basename, parameter[name[model_path]]]
call[name[diff_results]][name[model_filename]] assign[=] name[result]
with call[name[open], parameter[name[filename], constant[w]]] begin[:]
call[name[LOGGER].info, parameter[constant[Writing diff report to '%s'.], name[filename]]]
call[name[file_handle].write, parameter[call[name[api].diff_report, parameter[name[diff_results], name[config]]]]] | keyword[def] identifier[diff] ( identifier[models] , identifier[filename] , identifier[pytest_args] , identifier[exclusive] , identifier[skip] , identifier[solver] ,
identifier[experimental] , identifier[custom_tests] , identifier[custom_config] ):
literal[string]
keyword[if] keyword[not] identifier[any] ( identifier[a] . identifier[startswith] ( literal[string] ) keyword[for] identifier[a] keyword[in] identifier[pytest_args] ):
identifier[pytest_args] =[ literal[string] , literal[string] ]+ identifier[pytest_args]
identifier[pytest_args] . identifier[extend] ( identifier[custom_tests] )
identifier[config] = identifier[ReportConfiguration] . identifier[load] ()
keyword[for] identifier[custom] keyword[in] identifier[custom_config] :
identifier[config] . identifier[merge] ( identifier[ReportConfiguration] . identifier[load] ( identifier[custom] ))
identifier[diff_results] = identifier[dict] ()
identifier[model_and_model_ver_tuple] = identifier[list] ()
keyword[for] identifier[model_path] keyword[in] identifier[models] :
keyword[try] :
identifier[model_filename] = identifier[os] . identifier[path] . identifier[basename] ( identifier[model_path] )
identifier[diff_results] . identifier[setdefault] ( identifier[model_filename] , identifier[dict] ())
identifier[model] , identifier[model_ver] , identifier[notifications] = identifier[api] . identifier[validate_model] ( identifier[model_path] )
keyword[if] identifier[model] keyword[is] keyword[None] :
identifier[head] , identifier[tail] = identifier[os] . identifier[path] . identifier[split] ( identifier[filename] )
identifier[report_path] = identifier[os] . identifier[path] . identifier[join] (
identifier[head] , literal[string] . identifier[format] ( identifier[model_filename] ))
identifier[api] . identifier[validation_report] (
identifier[model_path] , identifier[notifications] , identifier[report_path] )
identifier[LOGGER] . identifier[critical] (
literal[string]
literal[string] . identifier[format] ( identifier[model_filename] , identifier[report_path] ))
keyword[continue]
identifier[model] . identifier[solver] = identifier[solver]
identifier[model_and_model_ver_tuple] . identifier[append] (( identifier[model] , identifier[model_ver] ))
keyword[except] ( identifier[IOError] , identifier[SBMLError] ):
identifier[LOGGER] . identifier[debug] ( identifier[exc_info] = keyword[True] )
identifier[LOGGER] . identifier[warning] ( literal[string]
literal[string] , identifier[model_filename] )
keyword[if] identifier[len] ( identifier[model_and_model_ver_tuple] )< literal[int] :
identifier[LOGGER] . identifier[critical] (
literal[string]
literal[string]
literal[string] ,
identifier[len] ( identifier[models] ), identifier[len] ( identifier[model_and_model_ver_tuple] ))
identifier[sys] . identifier[exit] ( literal[int] )
identifier[partial_test_diff] = identifier[partial] ( identifier[_test_diff] , identifier[pytest_args] = identifier[pytest_args] ,
identifier[skip] = identifier[skip] , identifier[exclusive] = identifier[exclusive] ,
identifier[experimental] = identifier[experimental] )
identifier[pool] = identifier[Pool] ( identifier[min] ( identifier[len] ( identifier[models] ), identifier[cpu_count] ()))
identifier[results] = identifier[pool] . identifier[map] ( identifier[partial_test_diff] , identifier[model_and_model_ver_tuple] )
keyword[for] identifier[model_path] , identifier[result] keyword[in] identifier[zip] ( identifier[models] , identifier[results] ):
identifier[model_filename] = identifier[os] . identifier[path] . identifier[basename] ( identifier[model_path] )
identifier[diff_results] [ identifier[model_filename] ]= identifier[result]
keyword[with] identifier[open] ( identifier[filename] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[file_handle] :
identifier[LOGGER] . identifier[info] ( literal[string] , identifier[filename] )
identifier[file_handle] . identifier[write] ( identifier[api] . identifier[diff_report] ( identifier[diff_results] , identifier[config] )) | def diff(models, filename, pytest_args, exclusive, skip, solver, experimental, custom_tests, custom_config):
"""
Take a snapshot of all the supplied models and generate a diff report.
MODELS: List of paths to two or more model files.
"""
if not any((a.startswith('--tb') for a in pytest_args)):
pytest_args = ['--tb', 'no'] + pytest_args # depends on [control=['if'], data=[]]
# Add further directories to search for tests.
pytest_args.extend(custom_tests)
config = ReportConfiguration.load()
# Update the default test configuration with custom ones (if any).
for custom in custom_config:
config.merge(ReportConfiguration.load(custom)) # depends on [control=['for'], data=['custom']]
# Build the diff report specific data structure
diff_results = dict()
model_and_model_ver_tuple = list()
for model_path in models:
try:
model_filename = os.path.basename(model_path)
diff_results.setdefault(model_filename, dict())
(model, model_ver, notifications) = api.validate_model(model_path)
if model is None:
(head, tail) = os.path.split(filename)
report_path = os.path.join(head, '{}_structural_report.html'.format(model_filename))
api.validation_report(model_path, notifications, report_path)
LOGGER.critical('The model {} could not be loaded due to SBML errors reported in {}.'.format(model_filename, report_path))
continue # depends on [control=['if'], data=[]]
model.solver = solver
model_and_model_ver_tuple.append((model, model_ver)) # depends on [control=['try'], data=[]]
except (IOError, SBMLError):
LOGGER.debug(exc_info=True)
LOGGER.warning("An error occurred while loading the model '%s'. Skipping.", model_filename) # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['model_path']]
# Abort the diff report unless at least two models can be loaded
# successfully.
if len(model_and_model_ver_tuple) < 2:
LOGGER.critical('Out of the %d provided models only %d could be loaded. Please, check if the models that could not be loaded are valid SBML. Aborting.', len(models), len(model_and_model_ver_tuple))
sys.exit(1) # depends on [control=['if'], data=[]]
# Running pytest in individual processes to avoid interference
partial_test_diff = partial(_test_diff, pytest_args=pytest_args, skip=skip, exclusive=exclusive, experimental=experimental)
pool = Pool(min(len(models), cpu_count()))
results = pool.map(partial_test_diff, model_and_model_ver_tuple)
for (model_path, result) in zip(models, results):
model_filename = os.path.basename(model_path)
diff_results[model_filename] = result # depends on [control=['for'], data=[]]
with open(filename, 'w', encoding='utf-8') as file_handle:
LOGGER.info("Writing diff report to '%s'.", filename)
file_handle.write(api.diff_report(diff_results, config)) # depends on [control=['with'], data=['file_handle']] |
def save_work_request_and_close(self, ch, method, properties, body):
"""
Save message body and close connection
"""
self.work_request = pickle.loads(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
ch.stop_consuming()
self.connection.close() | def function[save_work_request_and_close, parameter[self, ch, method, properties, body]]:
constant[
Save message body and close connection
]
name[self].work_request assign[=] call[name[pickle].loads, parameter[name[body]]]
call[name[ch].basic_ack, parameter[]]
call[name[ch].stop_consuming, parameter[]]
call[name[self].connection.close, parameter[]] | keyword[def] identifier[save_work_request_and_close] ( identifier[self] , identifier[ch] , identifier[method] , identifier[properties] , identifier[body] ):
literal[string]
identifier[self] . identifier[work_request] = identifier[pickle] . identifier[loads] ( identifier[body] )
identifier[ch] . identifier[basic_ack] ( identifier[delivery_tag] = identifier[method] . identifier[delivery_tag] )
identifier[ch] . identifier[stop_consuming] ()
identifier[self] . identifier[connection] . identifier[close] () | def save_work_request_and_close(self, ch, method, properties, body):
"""
Save message body and close connection
"""
self.work_request = pickle.loads(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
ch.stop_consuming()
self.connection.close() |
def batch_write_spans(
self,
name,
spans,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Sends new spans to new or existing traces. You cannot update
existing spans.
Example:
>>> from google.cloud import trace_v2
>>>
>>> client = trace_v2.TraceServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `spans`:
>>> spans = []
>>>
>>> client.batch_write_spans(name, spans)
Args:
name (str): Required. The name of the project where the spans belong. The format is
``projects/[PROJECT_ID]``.
spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A list of new spans. The span names must not match existing
spans, or the results are undefined.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v2.types.Span`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "batch_write_spans" not in self._inner_api_calls:
self._inner_api_calls[
"batch_write_spans"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.batch_write_spans,
default_retry=self._method_configs["BatchWriteSpans"].retry,
default_timeout=self._method_configs["BatchWriteSpans"].timeout,
client_info=self._client_info,
)
request = tracing_pb2.BatchWriteSpansRequest(name=name, spans=spans)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("name", name)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
self._inner_api_calls["batch_write_spans"](
request, retry=retry, timeout=timeout, metadata=metadata
) | def function[batch_write_spans, parameter[self, name, spans, retry, timeout, metadata]]:
constant[
Sends new spans to new or existing traces. You cannot update
existing spans.
Example:
>>> from google.cloud import trace_v2
>>>
>>> client = trace_v2.TraceServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `spans`:
>>> spans = []
>>>
>>> client.batch_write_spans(name, spans)
Args:
name (str): Required. The name of the project where the spans belong. The format is
``projects/[PROJECT_ID]``.
spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A list of new spans. The span names must not match existing
spans, or the results are undefined.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v2.types.Span`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
]
if compare[constant[batch_write_spans] <ast.NotIn object at 0x7da2590d7190> name[self]._inner_api_calls] begin[:]
call[name[self]._inner_api_calls][constant[batch_write_spans]] assign[=] call[name[google].api_core.gapic_v1.method.wrap_method, parameter[name[self].transport.batch_write_spans]]
variable[request] assign[=] call[name[tracing_pb2].BatchWriteSpansRequest, parameter[]]
if compare[name[metadata] is constant[None]] begin[:]
variable[metadata] assign[=] list[[]]
variable[metadata] assign[=] call[name[list], parameter[name[metadata]]]
<ast.Try object at 0x7da204565330>
call[call[name[self]._inner_api_calls][constant[batch_write_spans]], parameter[name[request]]] | keyword[def] identifier[batch_write_spans] (
identifier[self] ,
identifier[name] ,
identifier[spans] ,
identifier[retry] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] ,
identifier[timeout] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] ,
identifier[metadata] = keyword[None] ,
):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[_inner_api_calls] :
identifier[self] . identifier[_inner_api_calls] [
literal[string]
]= identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[wrap_method] (
identifier[self] . identifier[transport] . identifier[batch_write_spans] ,
identifier[default_retry] = identifier[self] . identifier[_method_configs] [ literal[string] ]. identifier[retry] ,
identifier[default_timeout] = identifier[self] . identifier[_method_configs] [ literal[string] ]. identifier[timeout] ,
identifier[client_info] = identifier[self] . identifier[_client_info] ,
)
identifier[request] = identifier[tracing_pb2] . identifier[BatchWriteSpansRequest] ( identifier[name] = identifier[name] , identifier[spans] = identifier[spans] )
keyword[if] identifier[metadata] keyword[is] keyword[None] :
identifier[metadata] =[]
identifier[metadata] = identifier[list] ( identifier[metadata] )
keyword[try] :
identifier[routing_header] =[( literal[string] , identifier[name] )]
keyword[except] identifier[AttributeError] :
keyword[pass]
keyword[else] :
identifier[routing_metadata] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[routing_header] . identifier[to_grpc_metadata] (
identifier[routing_header]
)
identifier[metadata] . identifier[append] ( identifier[routing_metadata] )
identifier[self] . identifier[_inner_api_calls] [ literal[string] ](
identifier[request] , identifier[retry] = identifier[retry] , identifier[timeout] = identifier[timeout] , identifier[metadata] = identifier[metadata]
) | def batch_write_spans(self, name, spans, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
"""
Sends new spans to new or existing traces. You cannot update
existing spans.
Example:
>>> from google.cloud import trace_v2
>>>
>>> client = trace_v2.TraceServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initialize `spans`:
>>> spans = []
>>>
>>> client.batch_write_spans(name, spans)
Args:
name (str): Required. The name of the project where the spans belong. The format is
``projects/[PROJECT_ID]``.
spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A list of new spans. The span names must not match existing
spans, or the results are undefined.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.trace_v2.types.Span`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'batch_write_spans' not in self._inner_api_calls:
self._inner_api_calls['batch_write_spans'] = google.api_core.gapic_v1.method.wrap_method(self.transport.batch_write_spans, default_retry=self._method_configs['BatchWriteSpans'].retry, default_timeout=self._method_configs['BatchWriteSpans'].timeout, client_info=self._client_info) # depends on [control=['if'], data=[]]
request = tracing_pb2.BatchWriteSpansRequest(name=name, spans=spans)
if metadata is None:
metadata = [] # depends on [control=['if'], data=['metadata']]
metadata = list(metadata)
try:
routing_header = [('name', name)] # depends on [control=['try'], data=[]]
except AttributeError:
pass # depends on [control=['except'], data=[]]
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(routing_header)
metadata.append(routing_metadata)
self._inner_api_calls['batch_write_spans'](request, retry=retry, timeout=timeout, metadata=metadata) |
def pid(self):
"""Stop managing the current pid."""
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | def function[pid, parameter[self]]:
constant[Stop managing the current pid.]
<ast.Try object at 0x7da20c76c6a0> | keyword[def] identifier[pid] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[os] . identifier[remove] ( identifier[self] . identifier[pidfile] )
keyword[except] identifier[IOError] :
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[self] . identifier[pidfile] ):
keyword[return] keyword[None]
identifier[LOG] . identifier[exception] ( literal[string] . identifier[format] ( identifier[self] . identifier[pidfile] ))
identifier[sys] . identifier[exit] ( identifier[exit] . identifier[PIDFILE_INACCESSIBLE] ) | def pid(self):
"""Stop managing the current pid."""
try:
os.remove(self.pidfile) # depends on [control=['try'], data=[]]
except IOError:
if not os.path.isfile(self.pidfile):
return None # depends on [control=['if'], data=[]]
LOG.exception('Failed to clear pidfile {0}).'.format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) # depends on [control=['except'], data=[]] |
async def help(self, timeout: DefaultNumType = _default) -> str:
"""
Send the SMTP HELP command, which responds with help text.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"HELP", timeout=timeout)
success_codes = (
SMTPStatus.system_status_ok,
SMTPStatus.help_message,
SMTPStatus.completed,
)
if response.code not in success_codes:
raise SMTPResponseException(response.code, response.message)
return response.message | <ast.AsyncFunctionDef object at 0x7da20e9b2b90> | keyword[async] keyword[def] identifier[help] ( identifier[self] , identifier[timeout] : identifier[DefaultNumType] = identifier[_default] )-> identifier[str] :
literal[string]
keyword[await] identifier[self] . identifier[_ehlo_or_helo_if_needed] ()
keyword[async] keyword[with] identifier[self] . identifier[_command_lock] :
identifier[response] = keyword[await] identifier[self] . identifier[execute_command] ( literal[string] , identifier[timeout] = identifier[timeout] )
identifier[success_codes] =(
identifier[SMTPStatus] . identifier[system_status_ok] ,
identifier[SMTPStatus] . identifier[help_message] ,
identifier[SMTPStatus] . identifier[completed] ,
)
keyword[if] identifier[response] . identifier[code] keyword[not] keyword[in] identifier[success_codes] :
keyword[raise] identifier[SMTPResponseException] ( identifier[response] . identifier[code] , identifier[response] . identifier[message] )
keyword[return] identifier[response] . identifier[message] | async def help(self, timeout: DefaultNumType=_default) -> str:
"""
Send the SMTP HELP command, which responds with help text.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b'HELP', timeout=timeout)
success_codes = (SMTPStatus.system_status_ok, SMTPStatus.help_message, SMTPStatus.completed)
if response.code not in success_codes:
raise SMTPResponseException(response.code, response.message) # depends on [control=['if'], data=[]]
return response.message |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.