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) !... | 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 0x7da1b0f3a9... | 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] ):
... | 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... |
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 d... | 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
Serial... | 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] ... | 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.... |
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_r... | 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[=] c... | 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] . identi... | 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... |
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.SubElemen... | 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]]]
v... | 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] , l... | 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')
... |
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_executabl... | 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 0x... | 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] ... | 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... |
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
... | 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 th... | 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]
. identi... | 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
... |
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... | 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... | 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] ],... | 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_individ... |
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 n... | 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], paramet... | 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] . id... | 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 c... |
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("g... | 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[... | 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] ) ... | 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=['... |
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}; messag... | 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={!... | 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[... | 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};'... |
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_inst... | 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[instan... | 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]... | 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(sel... |
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`
an... | 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`
... | 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[imag... | 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 ... |
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]][con... | 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] = i... | 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))
secondha... | 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... | 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] identifi... | 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... |
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:
selecte... | 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 0x7da20c... | 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] :
... | 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._para... |
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,se... | 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] assig... | 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_r... | 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_sp... |
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
... | 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.Tupl... | 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] ,... | 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 ... |
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)
r... | 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]... | 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] )
... | 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=['... |
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 bri... | 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
:pa... | 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[_matr... | 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 brightn... |
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
... | 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... | 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[... | 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
""... |
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(
... | 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[des... | 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]... | 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, *... |
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_ar... | <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] ident... | 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_ar... |
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 ... | 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 ... | 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_fro... | 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 ... |
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 ... | 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_operati... | 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] . id... | 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._file... |
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
... | 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 ... | 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... | 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
acti... |
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 = i... | 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[cal... | 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] = identi... | 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 err... |
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_ch... | 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[wher... | 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: "
... | 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>]]
... | 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[logge... | 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... |
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), "inf... | 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]... | 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] ( li... | 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)... |
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, avoi... | 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 la... | 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[... | 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, avoi... |
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... | 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
]
var... | 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] [ lite... | 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 nod... |
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... | 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 m... | 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] ( ident... | 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... |
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 positiv... | 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)
... | 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[... | 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 positiv... |
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/maste... | 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... | 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] ... | 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... |
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... | 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.Modul... | 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] :
... | 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: th... |
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... | 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):... | 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]... | 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]
... | 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):... |
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!
Ex... | 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 f... | 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_s... | 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!
Ex... |
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'... | 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[:]
... | 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] :
ke... | 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']
... |
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 0x7d... | 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] . ident... | 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._laye... |
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._... | 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 0x7da204... | 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] :
... | 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) # depe... |
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... | 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.
:par... | 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 rac... | 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] ( ide... | 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 s... |
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 le... | 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... | 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]
k... | 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 length... |
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():... | 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[N... | 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] ():
keywor... | 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(... |
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: M... | 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 elemen... | 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[st... | 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:... |
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
"""
r... | 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.WebhookIns... | 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 We... |
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_roo... | 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[... | 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... | 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, r... |
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 a... | 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 overwr... | 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] ... | 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 alrea... |
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.setOnMenuItem... | 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
... | 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] . identifi... | 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())
... |
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... | 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:
... | 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[[]]
... | 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] (... | 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:
li... |
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 =... | 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_m... | 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[... | 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_to... |
def get_training_image_text_data_iters(source_root: str,
source: str, target: str,
validation_source_root: str,
validation_source: str, validation_target: str,
voca... | 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, preloa... | 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_targ... | 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_le... |
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 ... | 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 ... | 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[s... | 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... |
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... | 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
... | 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 soundi... | 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... | 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... |
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 t... | 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
... | 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] identi... | 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 p... |
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... | 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[:]
... | 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] ... | 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 c... |
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._rece... | 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, paramete... | 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[t... | 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,... |
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 * ... | 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[=] bin... | 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] , id... | 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... |
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 Type... | 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] ... | 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[... | 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 __in... |
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[pac... | 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[p... | 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],
... | 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] ],
... | 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] ... | 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.m... | 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[:]
ret... | 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] ... | 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'... |
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 l... | 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[:]
... | 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] ()):
... | 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 [c... |
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.... | 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[]]
var... | 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... | 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.k... |
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():
... | 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[customizatio... | 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] ide... | 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 custom... |
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.C... | 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... | 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] :
iden... | 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.con... |
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' % mor... | 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_cook... | 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[i... | 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 TypeE... |
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... | 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[proces... | 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... |
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 o... | 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 SH... | 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] :
... | 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 br... |
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>, <a... | 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[... | 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),
... | 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[par... | 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) el... |
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] = id... | 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(Constrai... | 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
... | 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] ()]
... | 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(ConstraintVi... |
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 /... | 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 b... | 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 / pat... |
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])
la... | 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 0x7da1b... | 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] . iden... | 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])
la... |
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.machineI... | 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[[], []]
... | 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] ... | 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 = {}
machine... |
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
... | 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] . ide... | 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 cont... |
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:
... | 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 0x7da20... | 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] :
... | 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_... |
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 = {}
... | 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 : stri... | 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] )
... | 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 = {}
... |
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(modu... | 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>]
... | 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] )... | 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 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()
... | 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[el... | 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_... |
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
... | 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 ... | 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[stri... | 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
... |
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 kill... | 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.
... | 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] ). i... | 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 conta... |
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]]]
... | 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] =... | 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.
... | 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[... | 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] . iden... | 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 = ... |
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 wit... | 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 (b... | 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]
key... | 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 St... |
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 ... | 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
---------... | 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]... | 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: st... |
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.... | 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... | 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... | 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'], da... |
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', {}).ge... | 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], param... | 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]... | 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', {}).ge... |
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... | 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 0x... | 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... | 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)):
... |
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[c... | 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[... | 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.
... | 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.Tr... | 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[gap... | 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_v... |
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... | 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] ... | 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}).'... |
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:
... | <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] identif... | 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 = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.