code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def draw_weights(W=None, second=10, saveable=True, shape=None, name='mnist', fig_idx=2396512):
"""Visualize every columns of the weight matrix to a group of Greyscale img.
Parameters
----------
W : numpy.array
The weight matrix
second : int
The display second(s) for the image(s), if... | def function[draw_weights, parameter[W, second, saveable, shape, name, fig_idx]]:
constant[Visualize every columns of the weight matrix to a group of Greyscale img.
Parameters
----------
W : numpy.array
The weight matrix
second : int
The display second(s) for the image(s), if sa... | keyword[def] identifier[draw_weights] ( identifier[W] = keyword[None] , identifier[second] = literal[int] , identifier[saveable] = keyword[True] , identifier[shape] = keyword[None] , identifier[name] = literal[string] , identifier[fig_idx] = literal[int] ):
literal[string]
keyword[if] identifier[shape] k... | def draw_weights(W=None, second=10, saveable=True, shape=None, name='mnist', fig_idx=2396512):
"""Visualize every columns of the weight matrix to a group of Greyscale img.
Parameters
----------
W : numpy.array
The weight matrix
second : int
The display second(s) for the image(s), if... |
def get_option_value(elem):
""" Get the value attribute, or if it doesn't exist the text
content.
<option value="foo">bar</option> => "foo"
<option>bar</option> => "bar"
:param elem: a soup element
"""
value = elem.get("value")
if value is None:
value = elem.text.... | def function[get_option_value, parameter[elem]]:
constant[ Get the value attribute, or if it doesn't exist the text
content.
<option value="foo">bar</option> => "foo"
<option>bar</option> => "bar"
:param elem: a soup element
]
variable[value] assign[=] call[name[elem]... | keyword[def] identifier[get_option_value] ( identifier[elem] ):
literal[string]
identifier[value] = identifier[elem] . identifier[get] ( literal[string] )
keyword[if] identifier[value] keyword[is] keyword[None] :
identifier[value] = identifier[elem] . identifier[text] . identifier[strip] (... | def get_option_value(elem):
""" Get the value attribute, or if it doesn't exist the text
content.
<option value="foo">bar</option> => "foo"
<option>bar</option> => "bar"
:param elem: a soup element
"""
value = elem.get('value')
if value is None:
value = elem.text.... |
def unquoted(cls, value, literal=False):
"""Helper to create a string with no quotes."""
return cls(value, quotes=None, literal=literal) | def function[unquoted, parameter[cls, value, literal]]:
constant[Helper to create a string with no quotes.]
return[call[name[cls], parameter[name[value]]]] | keyword[def] identifier[unquoted] ( identifier[cls] , identifier[value] , identifier[literal] = keyword[False] ):
literal[string]
keyword[return] identifier[cls] ( identifier[value] , identifier[quotes] = keyword[None] , identifier[literal] = identifier[literal] ) | def unquoted(cls, value, literal=False):
"""Helper to create a string with no quotes."""
return cls(value, quotes=None, literal=literal) |
def background_model(self, ignore_black=True, use_hsv=False, scale=8):
"""Creates a background model for the given image. The background
color is given by the modes of each channel's histogram.
Parameters
----------
ignore_black : bool
If True, the zero pixels will b... | def function[background_model, parameter[self, ignore_black, use_hsv, scale]]:
constant[Creates a background model for the given image. The background
color is given by the modes of each channel's histogram.
Parameters
----------
ignore_black : bool
If True, the zero... | keyword[def] identifier[background_model] ( identifier[self] , identifier[ignore_black] = keyword[True] , identifier[use_hsv] = keyword[False] , identifier[scale] = literal[int] ):
literal[string]
identifier[data] = identifier[self] . identifier[data]
keyword[if] identifier[use_... | def background_model(self, ignore_black=True, use_hsv=False, scale=8):
"""Creates a background model for the given image. The background
color is given by the modes of each channel's histogram.
Parameters
----------
ignore_black : bool
If True, the zero pixels will be ig... |
def print_stdout(self, always_print=False):
"""
Prints the stdout to console - if there is any stdout, otherwise does nothing.
:param always_print: print the stdout, even if there is nothing in the buffer (default: false)
"""
if self.__stdout or always_print:
self._... | def function[print_stdout, parameter[self, always_print]]:
constant[
Prints the stdout to console - if there is any stdout, otherwise does nothing.
:param always_print: print the stdout, even if there is nothing in the buffer (default: false)
]
if <ast.BoolOp object at 0x7da1b0... | keyword[def] identifier[print_stdout] ( identifier[self] , identifier[always_print] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[__stdout] keyword[or] identifier[always_print] :
identifier[self] . identifier[__echo] . identifier[info] ( literal[strin... | def print_stdout(self, always_print=False):
"""
Prints the stdout to console - if there is any stdout, otherwise does nothing.
:param always_print: print the stdout, even if there is nothing in the buffer (default: false)
"""
if self.__stdout or always_print:
self.__echo.info('... |
def load(self, typedef, value, **kwargs):
"""
Return the result of the bound load method for a typedef
Looks up the load function that was bound to the engine for a typedef,
and return the result of passing the given `value` and any `context`
to that function.
Parameter... | def function[load, parameter[self, typedef, value]]:
constant[
Return the result of the bound load method for a typedef
Looks up the load function that was bound to the engine for a typedef,
and return the result of passing the given `value` and any `context`
to that function.
... | keyword[def] identifier[load] ( identifier[self] , identifier[typedef] , identifier[value] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[bound_type] = identifier[self] . identifier[bound_types] [ identifier[typedef] ]
keyword[except] identifier[KeyError]... | def load(self, typedef, value, **kwargs):
"""
Return the result of the bound load method for a typedef
Looks up the load function that was bound to the engine for a typedef,
and return the result of passing the given `value` and any `context`
to that function.
Parameters
... |
def get_paginated_catalog_courses(self, catalog_id, querystring=None):
"""
Return paginated response for all catalog courses.
Returns:
dict: API response with links to next and previous pages.
"""
return self._load_data(
self.CATALOGS_COURSES_ENDPOINT.fo... | def function[get_paginated_catalog_courses, parameter[self, catalog_id, querystring]]:
constant[
Return paginated response for all catalog courses.
Returns:
dict: API response with links to next and previous pages.
]
return[call[name[self]._load_data, parameter[call[nam... | keyword[def] identifier[get_paginated_catalog_courses] ( identifier[self] , identifier[catalog_id] , identifier[querystring] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_load_data] (
identifier[self] . identifier[CATALOGS_COURSES_ENDPOINT] . identifier... | def get_paginated_catalog_courses(self, catalog_id, querystring=None):
"""
Return paginated response for all catalog courses.
Returns:
dict: API response with links to next and previous pages.
"""
return self._load_data(self.CATALOGS_COURSES_ENDPOINT.format(catalog_id), def... |
def build_functional(self, *pattern, **kwargs):
"""
Builds a new functional pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._functional_defaults, kwargs)
set_defaults(self.... | def function[build_functional, parameter[self]]:
constant[
Builds a new functional pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
]
call[name[set_defaults], parameter[name[self]._functional_defaults, n... | keyword[def] identifier[build_functional] ( identifier[self] ,* identifier[pattern] ,** identifier[kwargs] ):
literal[string]
identifier[set_defaults] ( identifier[self] . identifier[_functional_defaults] , identifier[kwargs] )
identifier[set_defaults] ( identifier[self] . identifier[_defa... | def build_functional(self, *pattern, **kwargs):
"""
Builds a new functional pattern
:param pattern:
:type pattern:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
set_defaults(self._functional_defaults, kwargs)
set_defaults(self._defaults, k... |
def unpack_binary(data_pointer, definitions, data):
"""Unpack binary data using ``struct.unpack``
:param data_pointer: metadata for the ``data_pointer`` attribute for this data stream
:type data_pointer: ``ahds.header.Block``
:param definitions: definitions specified in the header
:type definit... | def function[unpack_binary, parameter[data_pointer, definitions, data]]:
constant[Unpack binary data using ``struct.unpack``
:param data_pointer: metadata for the ``data_pointer`` attribute for this data stream
:type data_pointer: ``ahds.header.Block``
:param definitions: definitions specified ... | keyword[def] identifier[unpack_binary] ( identifier[data_pointer] , identifier[definitions] , identifier[data] ):
literal[string]
keyword[if] identifier[data_pointer] . identifier[data_dimension] :
identifier[data_dimension] = identifier[data_pointer] . identifier[data_dimension]
keyword[e... | def unpack_binary(data_pointer, definitions, data):
"""Unpack binary data using ``struct.unpack``
:param data_pointer: metadata for the ``data_pointer`` attribute for this data stream
:type data_pointer: ``ahds.header.Block``
:param definitions: definitions specified in the header
:type definit... |
def html_to_tags(code):
"""
Convert HTML code to tags.
``code`` is a string containing HTML code. The return value is a
list of corresponding instances of ``TagBase``.
"""
code = ('<div>' + code + '</div>').encode('utf8')
el = ET.fromstring(code)
return [tag_from_element(c) for c in el] | def function[html_to_tags, parameter[code]]:
constant[
Convert HTML code to tags.
``code`` is a string containing HTML code. The return value is a
list of corresponding instances of ``TagBase``.
]
variable[code] assign[=] call[binary_operation[binary_operation[constant[<div>] + name[cod... | keyword[def] identifier[html_to_tags] ( identifier[code] ):
literal[string]
identifier[code] =( literal[string] + identifier[code] + literal[string] ). identifier[encode] ( literal[string] )
identifier[el] = identifier[ET] . identifier[fromstring] ( identifier[code] )
keyword[return] [ identifier... | def html_to_tags(code):
"""
Convert HTML code to tags.
``code`` is a string containing HTML code. The return value is a
list of corresponding instances of ``TagBase``.
"""
code = ('<div>' + code + '</div>').encode('utf8')
el = ET.fromstring(code)
return [tag_from_element(c) for c in el] |
def copy_logstore(self, from_project, from_logstore, to_logstore, to_project=None, to_client=None):
"""
copy logstore, index, logtail config to target logstore, machine group are not included yet.
the target logstore will be crated if not existing
:type from_project: string
... | def function[copy_logstore, parameter[self, from_project, from_logstore, to_logstore, to_project, to_client]]:
constant[
copy logstore, index, logtail config to target logstore, machine group are not included yet.
the target logstore will be crated if not existing
:type from_project: st... | keyword[def] identifier[copy_logstore] ( identifier[self] , identifier[from_project] , identifier[from_logstore] , identifier[to_logstore] , identifier[to_project] = keyword[None] , identifier[to_client] = keyword[None] ):
literal[string]
keyword[return] identifier[copy_logstore] ( identifier[se... | def copy_logstore(self, from_project, from_logstore, to_logstore, to_project=None, to_client=None):
"""
copy logstore, index, logtail config to target logstore, machine group are not included yet.
the target logstore will be crated if not existing
:type from_project: string
:param f... |
def _parse(self, e):
"""Parses an exception, returns its message."""
# MySQL
matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
if matches:
return matches.group(1)
# PostgreSQL
matches = re.search(r"^\(psycopg2\.Opera... | def function[_parse, parameter[self, e]]:
constant[Parses an exception, returns its message.]
variable[matches] assign[=] call[name[re].search, parameter[constant[^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$], call[name[str], parameter[name[e]]]]]
if name[matches] begin[:]
... | keyword[def] identifier[_parse] ( identifier[self] , identifier[e] ):
literal[string]
identifier[matches] = identifier[re] . identifier[search] ( literal[string] , identifier[str] ( identifier[e] ))
keyword[if] identifier[matches] :
keyword[return] identifier[match... | def _parse(self, e):
"""Parses an exception, returns its message."""
# MySQL
matches = re.search('^\\(_mysql_exceptions\\.OperationalError\\) \\(\\d+, \\"(.+)\\"\\)$', str(e))
if matches:
return matches.group(1) # depends on [control=['if'], data=[]]
# PostgreSQL
matches = re.search('^\... |
def check_dirty(self):
'''
.. versionchanged:: 0.20
Do not log size change.
'''
if self._dirty_size is None:
if self._dirty_render:
self.render()
self._dirty_render = False
if self._dirty_draw:
self.draw(... | def function[check_dirty, parameter[self]]:
constant[
.. versionchanged:: 0.20
Do not log size change.
]
if compare[name[self]._dirty_size is constant[None]] begin[:]
if name[self]._dirty_render begin[:]
call[name[self].render, paramete... | keyword[def] identifier[check_dirty] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_dirty_size] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[_dirty_render] :
identifier[self] . identifier[render] ()
... | def check_dirty(self):
"""
.. versionchanged:: 0.20
Do not log size change.
"""
if self._dirty_size is None:
if self._dirty_render:
self.render()
self._dirty_render = False # depends on [control=['if'], data=[]]
if self._dirty_draw:
... |
def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: diction... | def function[convert_squeeze, parameter[params, w_name, scope_name, inputs, layers, weights, names]]:
constant[
Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node... | keyword[def] identifier[convert_squeeze] ( identifier[params] , identifier[w_name] , identifier[scope_name] , identifier[inputs] , identifier[layers] , identifier[weights] , identifier[names] ):
literal[string]
identifier[print] ( literal[string] )
keyword[if] identifier[len] ( identifier[params] [ ... | def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: diction... |
def proper_case_section(self, section):
"""Verify proper casing is retrieved, when available, for each
dependency in the section.
"""
# Casing for section.
changed_values = False
unknown_names = [k for k in section.keys() if k not in set(self.proper_names)]
# Repl... | def function[proper_case_section, parameter[self, section]]:
constant[Verify proper casing is retrieved, when available, for each
dependency in the section.
]
variable[changed_values] assign[=] constant[False]
variable[unknown_names] assign[=] <ast.ListComp object at 0x7da1b1e8ee... | keyword[def] identifier[proper_case_section] ( identifier[self] , identifier[section] ):
literal[string]
identifier[changed_values] = keyword[False]
identifier[unknown_names] =[ identifier[k] keyword[for] identifier[k] keyword[in] identifier[section] . identifier[keys] () key... | def proper_case_section(self, section):
"""Verify proper casing is retrieved, when available, for each
dependency in the section.
"""
# Casing for section.
changed_values = False
unknown_names = [k for k in section.keys() if k not in set(self.proper_names)]
# Replace each package wit... |
def get_label(self):
"""Get the label of the Dataset.
Returns
-------
label : numpy array or None
The label information from the Dataset.
"""
if self.label is None:
self.label = self.get_field('label')
return self.label | def function[get_label, parameter[self]]:
constant[Get the label of the Dataset.
Returns
-------
label : numpy array or None
The label information from the Dataset.
]
if compare[name[self].label is constant[None]] begin[:]
name[self].label ass... | keyword[def] identifier[get_label] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[label] keyword[is] keyword[None] :
identifier[self] . identifier[label] = identifier[self] . identifier[get_field] ( literal[string] )
keyword[return] identif... | def get_label(self):
"""Get the label of the Dataset.
Returns
-------
label : numpy array or None
The label information from the Dataset.
"""
if self.label is None:
self.label = self.get_field('label') # depends on [control=['if'], data=[]]
return self.l... |
def remove_child(self, child):
"""
Remove a child widget from this widget.
:param child: Object inheriting :class:`BaseElement`
"""
self.children.remove(child)
child.parent = None
if self.view and self.view.is_loaded:
self.view.dispatch({
... | def function[remove_child, parameter[self, child]]:
constant[
Remove a child widget from this widget.
:param child: Object inheriting :class:`BaseElement`
]
call[name[self].children.remove, parameter[name[child]]]
name[child].parent assign[=] constant[None]
if <a... | keyword[def] identifier[remove_child] ( identifier[self] , identifier[child] ):
literal[string]
identifier[self] . identifier[children] . identifier[remove] ( identifier[child] )
identifier[child] . identifier[parent] = keyword[None]
keyword[if] identifier[self] . identifier[vi... | def remove_child(self, child):
"""
Remove a child widget from this widget.
:param child: Object inheriting :class:`BaseElement`
"""
self.children.remove(child)
child.parent = None
if self.view and self.view.is_loaded:
self.view.dispatch({'name': 'remove', 'selector': '#'... |
def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object
... | def function[save, parameter[self, obj]]:
constant[ Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
]
if <ast.BoolOp object at 0x7da1b0e3ada0> begin[:]
if compare[name[o... | keyword[def] identifier[save] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[self] . identifier[np] . identifier[ndarray] ) keyword[and] keyword[not] identifier[obj] . identifier[dtype] . identifier[hasobject] :
... | def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and (not obj.dtype.hasobject):
# Compute a hash of the object
# ... |
def _series(self, name, interval, config, buckets, **kws):
'''
Fetch a series of buckets.
'''
pipe = self._client.pipeline(transaction=False)
step = config['step']
resolution = config.get('resolution',step)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') o... | def function[_series, parameter[self, name, interval, config, buckets]]:
constant[
Fetch a series of buckets.
]
variable[pipe] assign[=] call[name[self]._client.pipeline, parameter[]]
variable[step] assign[=] call[name[config]][constant[step]]
variable[resolution] assign[=] call[... | keyword[def] identifier[_series] ( identifier[self] , identifier[name] , identifier[interval] , identifier[config] , identifier[buckets] ,** identifier[kws] ):
literal[string]
identifier[pipe] = identifier[self] . identifier[_client] . identifier[pipeline] ( identifier[transaction] = keyword[False] )
... | def _series(self, name, interval, config, buckets, **kws):
"""
Fetch a series of buckets.
"""
pipe = self._client.pipeline(transaction=False)
step = config['step']
resolution = config.get('resolution', step)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') ... |
def peakSpectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, window='hann'):
"""
analyses the source to generate the max values per bin per segment
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mo... | def function[peakSpectrum, parameter[self, ref, segmentLengthMultiplier, mode, window]]:
constant[
analyses the source to generate the max values per bin per segment
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:... | keyword[def] identifier[peakSpectrum] ( identifier[self] , identifier[ref] = keyword[None] , identifier[segmentLengthMultiplier] = literal[int] , identifier[mode] = keyword[None] , identifier[window] = literal[string] ):
literal[string]
keyword[def] identifier[analysisFunc] ( identifier[x] , iden... | def peakSpectrum(self, ref=None, segmentLengthMultiplier=1, mode=None, window='hann'):
"""
analyses the source to generate the max values per bin per segment
:param ref: the reference value for dB purposes.
:param segmentLengthMultiplier: allow for increased resolution.
:param mode: ... |
def main(): # pragma: no cover
"""Main entry point."""
try:
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError:
# SIGPIPE is not available on Windows.
pass
try:
return _main(sys.argv,
standard_out=sys.... | def function[main, parameter[]]:
constant[Main entry point.]
<ast.Try object at 0x7da1b26ad390>
<ast.Try object at 0x7da1b26acbe0> | keyword[def] identifier[main] ():
literal[string]
keyword[try] :
identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIGPIPE] , identifier[signal] . identifier[SIG_DFL] )
keyword[except] identifier[AttributeError] :
keyword[pass]
keyword[try] :... | def main(): # pragma: no cover
'Main entry point.'
try:
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # depends on [control=['try'], data=[]]
except AttributeError:
# SIGPIPE is not available on Windows.
pass # depends on [control=['except'], data=[]... |
def glir(self):
""" The GLIR queue corresponding to the current canvas
"""
canvas = get_current_canvas()
if canvas is None:
msg = ("If you want to use gloo without vispy.app, " +
"use a gloo.context.FakeCanvas.")
raise RuntimeError('Gloo requir... | def function[glir, parameter[self]]:
constant[ The GLIR queue corresponding to the current canvas
]
variable[canvas] assign[=] call[name[get_current_canvas], parameter[]]
if compare[name[canvas] is constant[None]] begin[:]
variable[msg] assign[=] binary_operation[constant... | keyword[def] identifier[glir] ( identifier[self] ):
literal[string]
identifier[canvas] = identifier[get_current_canvas] ()
keyword[if] identifier[canvas] keyword[is] keyword[None] :
identifier[msg] =( literal[string] +
literal[string] )
keyword[rai... | def glir(self):
""" The GLIR queue corresponding to the current canvas
"""
canvas = get_current_canvas()
if canvas is None:
msg = 'If you want to use gloo without vispy.app, ' + 'use a gloo.context.FakeCanvas.'
raise RuntimeError('Gloo requires a Canvas to run.\n' + msg) # depends o... |
def enable_backups(self):
"""
Enable Backups for this Instance. When enabled, we will automatically
backup your Instance's data so that it can be restored at a later date.
For more information on Instance's Backups service and pricing, see our
`Backups Page`_
.. _Backup... | def function[enable_backups, parameter[self]]:
constant[
Enable Backups for this Instance. When enabled, we will automatically
backup your Instance's data so that it can be restored at a later date.
For more information on Instance's Backups service and pricing, see our
`Backups... | keyword[def] identifier[enable_backups] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_client] . identifier[post] ( literal[string] . identifier[format] ( identifier[Instance] . identifier[api_endpoint] ), identifier[model] = identifier[self] )
identifier[self] . iden... | def enable_backups(self):
"""
Enable Backups for this Instance. When enabled, we will automatically
backup your Instance's data so that it can be restored at a later date.
For more information on Instance's Backups service and pricing, see our
`Backups Page`_
.. _Backups Pa... |
async def dispatch(self, request, **kwargs):
"""Dispatch a request."""
# Authorize request
self.auth = await self.authorize(request)
# Load collection
self.collection = await self.load_many(request)
# Load resource
self.resource = await self.load_one(request)
... | <ast.AsyncFunctionDef object at 0x7da18f00c5e0> | keyword[async] keyword[def] identifier[dispatch] ( identifier[self] , identifier[request] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[auth] = keyword[await] identifier[self] . identifier[authorize] ( identifier[request] )
identifier[self] . ... | async def dispatch(self, request, **kwargs):
"""Dispatch a request."""
# Authorize request
self.auth = await self.authorize(request)
# Load collection
self.collection = await self.load_many(request)
# Load resource
self.resource = await self.load_one(request)
if request.method == 'GET' a... |
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.up... | def function[convert_attrs_to_uppercase, parameter[obj, attrs]]:
constant[
Converts the specified attributes of an object to upper case, modifying
the object in place.
]
for taget[name[a]] in starred[name[attrs]] begin[:]
variable[value] assign[=] call[name[getattr], paramete... | keyword[def] identifier[convert_attrs_to_uppercase] ( identifier[obj] : identifier[Any] , identifier[attrs] : identifier[Iterable] [ identifier[str] ])-> keyword[None] :
literal[string]
keyword[for] identifier[a] keyword[in] identifier[attrs] :
identifier[value] = identifier[getattr] ( identifi... | def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue # depends on [control=['if'], d... |
def flatten(self, df, column_name):
"""Flatten a column in the dataframe that contains lists"""
_exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list]
return pd.DataFrame(_exp_list, columns=['md5',column_name]) | def function[flatten, parameter[self, df, column_name]]:
constant[Flatten a column in the dataframe that contains lists]
variable[_exp_list] assign[=] <ast.ListComp object at 0x7da20c7cbb20>
return[call[name[pd].DataFrame, parameter[name[_exp_list]]]] | keyword[def] identifier[flatten] ( identifier[self] , identifier[df] , identifier[column_name] ):
literal[string]
identifier[_exp_list] =[[ identifier[md5] , identifier[x] ] keyword[for] identifier[md5] , identifier[value_list] keyword[in] identifier[zip] ( identifier[df] [ literal[string] ], id... | def flatten(self, df, column_name):
"""Flatten a column in the dataframe that contains lists"""
_exp_list = [[md5, x] for (md5, value_list) in zip(df['md5'], df[column_name]) for x in value_list]
return pd.DataFrame(_exp_list, columns=['md5', column_name]) |
def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages | def function[check_messages, parameter[]]:
constant[decorator to store messages that are handled by a checker method]
def function[store_messages, parameter[func]]:
name[func].checks_msgs assign[=] name[messages]
return[name[func]]
return[name[store_messages]] | keyword[def] identifier[check_messages] (* identifier[messages] : identifier[str] )-> identifier[Callable] :
literal[string]
keyword[def] identifier[store_messages] ( identifier[func] ):
identifier[func] . identifier[checks_msgs] = identifier[messages]
keyword[return] identifier[func]... | def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages |
def xpath(source_xml, xpath_expr, req_format='string'):
""" Filter xml based on an xpath expression.
Purpose: This function applies an Xpath expression to the XML
| supplied by source_xml. Returns a string subtree or
| subtrees that match the Xpath expression. It can also return
... | def function[xpath, parameter[source_xml, xpath_expr, req_format]]:
constant[ Filter xml based on an xpath expression.
Purpose: This function applies an Xpath expression to the XML
| supplied by source_xml. Returns a string subtree or
| subtrees that match the Xpath expression. It can... | keyword[def] identifier[xpath] ( identifier[source_xml] , identifier[xpath_expr] , identifier[req_format] = literal[string] ):
literal[string]
identifier[tree] = identifier[source_xml]
keyword[if] keyword[not] identifier[isinstance] ( identifier[source_xml] , identifier[ET] . identifier[Element] ):... | def xpath(source_xml, xpath_expr, req_format='string'):
""" Filter xml based on an xpath expression.
Purpose: This function applies an Xpath expression to the XML
| supplied by source_xml. Returns a string subtree or
| subtrees that match the Xpath expression. It can also return
... |
def get_emails(self, mailinglist_dir, all, exclude_lists):
"""Generator function that get the emails from each mailing
list dump dirctory. If `all` is set to True all the emails in the
mbox will be imported if not it will just resume from the last
message previously imported. The lists s... | def function[get_emails, parameter[self, mailinglist_dir, all, exclude_lists]]:
constant[Generator function that get the emails from each mailing
list dump dirctory. If `all` is set to True all the emails in the
mbox will be imported if not it will just resume from the last
message previ... | keyword[def] identifier[get_emails] ( identifier[self] , identifier[mailinglist_dir] , identifier[all] , identifier[exclude_lists] ):
literal[string]
identifier[self] . identifier[log] ( literal[string] % identifier[mailinglist_dir] )
identifier[mailing_lists_mboxes] =( identifie... | def get_emails(self, mailinglist_dir, all, exclude_lists):
"""Generator function that get the emails from each mailing
list dump dirctory. If `all` is set to True all the emails in the
mbox will be imported if not it will just resume from the last
message previously imported. The lists set i... |
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
expr = self.children[1].sym(nested_scope)
return operation(expr) | def function[sym, parameter[self, nested_scope]]:
constant[Return the correspond symbolic number.]
variable[operation] assign[=] call[call[name[self].children][constant[0]].operation, parameter[]]
variable[expr] assign[=] call[call[name[self].children][constant[1]].sym, parameter[name[nested_sco... | keyword[def] identifier[sym] ( identifier[self] , identifier[nested_scope] = keyword[None] ):
literal[string]
identifier[operation] = identifier[self] . identifier[children] [ literal[int] ]. identifier[operation] ()
identifier[expr] = identifier[self] . identifier[children] [ literal[int]... | def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
expr = self.children[1].sym(nested_scope)
return operation(expr) |
def options(parser, help_menu=False):
"""
Summary:
parse cli parameter options
Returns:
TYPE: argparse object, parser argument set
"""
parser.add_argument("-p", "--profile", nargs='?', default="default",
required=False, help="type (default: %(default)s)"... | def function[options, parameter[parser, help_menu]]:
constant[
Summary:
parse cli parameter options
Returns:
TYPE: argparse object, parser argument set
]
call[name[parser].add_argument, parameter[constant[-p], constant[--profile]]]
call[name[parser].add_argument, para... | keyword[def] identifier[options] ( identifier[parser] , identifier[help_menu] = keyword[False] ):
literal[string]
identifier[parser] . identifier[add_argument] ( literal[string] , literal[string] , identifier[nargs] = literal[string] , identifier[default] = literal[string] ,
identifier[required] = key... | def options(parser, help_menu=False):
"""
Summary:
parse cli parameter options
Returns:
TYPE: argparse object, parser argument set
"""
parser.add_argument('-p', '--profile', nargs='?', default='default', required=False, help='type (default: %(default)s)')
parser.add_argument('-i'... |
def set_site():
"""
This method is part of the prepare_data helper.
Sets the site. Default implementation uses localhost.
For production settings refine this helper.
:return:
"""
from django.contrib.sites.models import Site
from django.conf import settings
# Initially set localhost a... | def function[set_site, parameter[]]:
constant[
This method is part of the prepare_data helper.
Sets the site. Default implementation uses localhost.
For production settings refine this helper.
:return:
]
from relative_module[django.contrib.sites.models] import module[Site]
from relat... | keyword[def] identifier[set_site] ():
literal[string]
keyword[from] identifier[django] . identifier[contrib] . identifier[sites] . identifier[models] keyword[import] identifier[Site]
keyword[from] identifier[django] . identifier[conf] keyword[import] identifier[settings]
identif... | def set_site():
"""
This method is part of the prepare_data helper.
Sets the site. Default implementation uses localhost.
For production settings refine this helper.
:return:
"""
from django.contrib.sites.models import Site
from django.conf import settings
# Initially set localhost a... |
def getLinkInterfaces(self, node1, node2):
'''
Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given).
'''
linkdata = self.getLink(node1,node2)
return linkdata[node... | def function[getLinkInterfaces, parameter[self, node1, node2]]:
constant[
Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given).
]
variable[linkdata] assign[=] call[name[s... | keyword[def] identifier[getLinkInterfaces] ( identifier[self] , identifier[node1] , identifier[node2] ):
literal[string]
identifier[linkdata] = identifier[self] . identifier[getLink] ( identifier[node1] , identifier[node2] )
keyword[return] identifier[linkdata] [ identifier[node1] ], iden... | def getLinkInterfaces(self, node1, node2):
"""
Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given).
"""
linkdata = self.getLink(node1, node2)
return (linkdata[node1], linkda... |
def matches(self, new, old):
''' Whether two parameters match values.
If either ``new`` or ``old`` is a NumPy array or Pandas Series or Index,
then the result of ``np.array_equal`` will determine if the values match.
Otherwise, the result of standard Python equality will be returned.
... | def function[matches, parameter[self, new, old]]:
constant[ Whether two parameters match values.
If either ``new`` or ``old`` is a NumPy array or Pandas Series or Index,
then the result of ``np.array_equal`` will determine if the values match.
Otherwise, the result of standard Python e... | keyword[def] identifier[matches] ( identifier[self] , identifier[new] , identifier[old] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[new] , identifier[np] . identifier[ndarray] ) keyword[or] identifier[isinstance] ( identifier[old] , identifier[np] . identifier[ndarray] ):
... | def matches(self, new, old):
""" Whether two parameters match values.
If either ``new`` or ``old`` is a NumPy array or Pandas Series or Index,
then the result of ``np.array_equal`` will determine if the values match.
Otherwise, the result of standard Python equality will be returned.
... |
def __value_compare(self, target):
"""
Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean
"""
if self.expectation == "__ANY__":
return True
elif self.expectation == "__DEFINED__":
return True if targ... | def function[__value_compare, parameter[self, target]]:
constant[
Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean
]
if compare[name[self].expectation equal[==] constant[__ANY__]] begin[:]
return[constant[True]] | keyword[def] identifier[__value_compare] ( identifier[self] , identifier[target] ):
literal[string]
keyword[if] identifier[self] . identifier[expectation] == literal[string] :
keyword[return] keyword[True]
keyword[elif] identifier[self] . identifier[expectation] == literal... | def __value_compare(self, target):
"""
Comparing result based on expectation if arg_type is "VALUE"
Args: Anything
Return: Boolean
"""
if self.expectation == '__ANY__':
return True # depends on [control=['if'], data=[]]
elif self.expectation == '__DEFINED__':
... |
def close(self):
"""Close the pooled shared connection."""
# Instead of actually closing the connection,
# unshare it and/or return it to the pool.
if self._con:
self._pool.unshare(self._shared_con)
self._shared_con = self._con = None | def function[close, parameter[self]]:
constant[Close the pooled shared connection.]
if name[self]._con begin[:]
call[name[self]._pool.unshare, parameter[name[self]._shared_con]]
name[self]._shared_con assign[=] constant[None] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_con] :
identifier[self] . identifier[_pool] . identifier[unshare] ( identifier[self] . identifier[_shared_con] )
identifier[self] . identifier... | def close(self):
"""Close the pooled shared connection."""
# Instead of actually closing the connection,
# unshare it and/or return it to the pool.
if self._con:
self._pool.unshare(self._shared_con)
self._shared_con = self._con = None # depends on [control=['if'], data=[]] |
def set_final_window_rect(cls, settings, window):
"""Sets the final size and location of the main window of guake. The height
is the window_height property, width is window_width and the
horizontal alignment is given by window_alignment.
"""
# fetch settings
height_percen... | def function[set_final_window_rect, parameter[cls, settings, window]]:
constant[Sets the final size and location of the main window of guake. The height
is the window_height property, width is window_width and the
horizontal alignment is given by window_alignment.
]
variable[heig... | keyword[def] identifier[set_final_window_rect] ( identifier[cls] , identifier[settings] , identifier[window] ):
literal[string]
identifier[height_percents] = identifier[settings] . identifier[general] . identifier[get_int] ( literal[string] )
identifier[width_percents] = identifi... | def set_final_window_rect(cls, settings, window):
"""Sets the final size and location of the main window of guake. The height
is the window_height property, width is window_width and the
horizontal alignment is given by window_alignment.
"""
# fetch settings
height_percents = setting... |
def handle(self):
"""
Creates a child process that is fully controlled by this
request handler, and serves data to and from it via the
protocol handler.
"""
pid, fd = pty.fork()
if pid:
protocol = TelnetServerProtocolHandler(self.request, f... | def function[handle, parameter[self]]:
constant[
Creates a child process that is fully controlled by this
request handler, and serves data to and from it via the
protocol handler.
]
<ast.Tuple object at 0x7da20c6c66b0> assign[=] call[name[pty].fork, parameter[... | keyword[def] identifier[handle] ( identifier[self] ):
literal[string]
identifier[pid] , identifier[fd] = identifier[pty] . identifier[fork] ()
keyword[if] identifier[pid] :
identifier[protocol] = identifier[TelnetServerProtocolHandler] ( identifier[self] . identifier[request]... | def handle(self):
"""
Creates a child process that is fully controlled by this
request handler, and serves data to and from it via the
protocol handler.
"""
(pid, fd) = pty.fork()
if pid:
protocol = TelnetServerProtocolHandler(self.request, fd)
pro... |
def intersects(self, other):
'''Returns True iff this record's reference positions overlap
the other record reference positions (and are on same chromosome)'''
return self.CHROM == other.CHROM and self.POS <= other.ref_end_pos() and other.POS <= self.ref_end_pos() | def function[intersects, parameter[self, other]]:
constant[Returns True iff this record's reference positions overlap
the other record reference positions (and are on same chromosome)]
return[<ast.BoolOp object at 0x7da1b1da4dc0>] | keyword[def] identifier[intersects] ( identifier[self] , identifier[other] ):
literal[string]
keyword[return] identifier[self] . identifier[CHROM] == identifier[other] . identifier[CHROM] keyword[and] identifier[self] . identifier[POS] <= identifier[other] . identifier[ref_end_pos] () keyword[an... | def intersects(self, other):
"""Returns True iff this record's reference positions overlap
the other record reference positions (and are on same chromosome)"""
return self.CHROM == other.CHROM and self.POS <= other.ref_end_pos() and (other.POS <= self.ref_end_pos()) |
def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2]... | def function[as_dict, parameter[self]]:
constant[
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
... | keyword[def] identifier[as_dict] ( identifier[self] ):
literal[string]
identifier[dict_body] =[]
keyword[for] identifier[row] keyword[in] identifier[self] . identifier[rows] :
keyword[if] keyword[not] identifier[row] :
keyword[continue]
id... | def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3... |
def save(hdf5_filename, array):
"""
Export a numpy array to a HDF5 file.
Arguments:
hdf5_filename (str): A filename to which to save the HDF5 data
array (numpy.ndarray): The numpy array to save to HDF5
Returns:
String. The expanded filename that now holds the HDF5 data
"""
... | def function[save, parameter[hdf5_filename, array]]:
constant[
Export a numpy array to a HDF5 file.
Arguments:
hdf5_filename (str): A filename to which to save the HDF5 data
array (numpy.ndarray): The numpy array to save to HDF5
Returns:
String. The expanded filename that n... | keyword[def] identifier[save] ( identifier[hdf5_filename] , identifier[array] ):
literal[string]
identifier[hdf5_filename] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[hdf5_filename] )
keyword[try] :
identifier[h] = identifier[h5py] . identifier[File] ( iden... | def save(hdf5_filename, array):
"""
Export a numpy array to a HDF5 file.
Arguments:
hdf5_filename (str): A filename to which to save the HDF5 data
array (numpy.ndarray): The numpy array to save to HDF5
Returns:
String. The expanded filename that now holds the HDF5 data
"""
... |
def get_row_data(self, row, name=None):
""" Returns a dict with all available data for a row in the extension
Parameters
----------
row : tuple, list, string
A valid index for the extension DataFrames
name : string, optional
If given, adds a key 'name' wi... | def function[get_row_data, parameter[self, row, name]]:
constant[ Returns a dict with all available data for a row in the extension
Parameters
----------
row : tuple, list, string
A valid index for the extension DataFrames
name : string, optional
If given... | keyword[def] identifier[get_row_data] ( identifier[self] , identifier[row] , identifier[name] = keyword[None] ):
literal[string]
identifier[retdict] ={}
keyword[for] identifier[rowname] , identifier[data] keyword[in] identifier[zip] ( identifier[self] . identifier[get_DataFrame] (),
... | def get_row_data(self, row, name=None):
""" Returns a dict with all available data for a row in the extension
Parameters
----------
row : tuple, list, string
A valid index for the extension DataFrames
name : string, optional
If given, adds a key 'name' with t... |
def _reset(self):
""" Rebuilds structure for AST and resets internal data.
"""
self._filename = None
self._block_map = {}
self._ast = []
self._ast.append(None) # header
self._ast.append([]) # options list
self._ast.append([]) | def function[_reset, parameter[self]]:
constant[ Rebuilds structure for AST and resets internal data.
]
name[self]._filename assign[=] constant[None]
name[self]._block_map assign[=] dictionary[[], []]
name[self]._ast assign[=] list[[]]
call[name[self]._ast.append, par... | keyword[def] identifier[_reset] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_filename] = keyword[None]
identifier[self] . identifier[_block_map] ={}
identifier[self] . identifier[_ast] =[]
identifier[self] . identifier[_ast] . identifier[append] ... | def _reset(self):
""" Rebuilds structure for AST and resets internal data.
"""
self._filename = None
self._block_map = {}
self._ast = []
self._ast.append(None) # header
self._ast.append([]) # options list
self._ast.append([]) |
def computeGaussKernel(x):
"""Compute the gaussian kernel on a 1D vector."""
xnorm = np.power(euclidean_distances(x, x), 2)
return np.exp(-xnorm / (2.0)) | def function[computeGaussKernel, parameter[x]]:
constant[Compute the gaussian kernel on a 1D vector.]
variable[xnorm] assign[=] call[name[np].power, parameter[call[name[euclidean_distances], parameter[name[x], name[x]]], constant[2]]]
return[call[name[np].exp, parameter[binary_operation[<ast.UnaryOp... | keyword[def] identifier[computeGaussKernel] ( identifier[x] ):
literal[string]
identifier[xnorm] = identifier[np] . identifier[power] ( identifier[euclidean_distances] ( identifier[x] , identifier[x] ), literal[int] )
keyword[return] identifier[np] . identifier[exp] (- identifier[xnorm] /( literal[in... | def computeGaussKernel(x):
"""Compute the gaussian kernel on a 1D vector."""
xnorm = np.power(euclidean_distances(x, x), 2)
return np.exp(-xnorm / 2.0) |
def find_prime_polynomials(generator=2, c_exp=8, fast_primes=False, single=False):
'''Compute the list of prime polynomials for the given generator and galois field characteristic exponent.'''
# fast_primes will output less results but will be significantly faster.
# single will output the first prime polyn... | def function[find_prime_polynomials, parameter[generator, c_exp, fast_primes, single]]:
constant[Compute the list of prime polynomials for the given generator and galois field characteristic exponent.]
variable[root_charac] assign[=] constant[2]
variable[field_charac] assign[=] call[name[int], p... | keyword[def] identifier[find_prime_polynomials] ( identifier[generator] = literal[int] , identifier[c_exp] = literal[int] , identifier[fast_primes] = keyword[False] , identifier[single] = keyword[False] ):
literal[string]
identifier[root_charac] = litera... | def find_prime_polynomials(generator=2, c_exp=8, fast_primes=False, single=False):
"""Compute the list of prime polynomials for the given generator and galois field characteristic exponent."""
# fast_primes will output less results but will be significantly faster.
# single will output the first prime polyn... |
def _identify_surface_sites(self, thickness):
"""Label surface sites and add ports above them. """
for atom in self.particles():
if len(self.bond_graph.neighbors(atom)) == 1:
if atom.name == 'O' and atom.pos[2] > thickness:
atom.name = 'OS'
... | def function[_identify_surface_sites, parameter[self, thickness]]:
constant[Label surface sites and add ports above them. ]
for taget[name[atom]] in starred[call[name[self].particles, parameter[]]] begin[:]
if compare[call[name[len], parameter[call[name[self].bond_graph.neighbors, parame... | keyword[def] identifier[_identify_surface_sites] ( identifier[self] , identifier[thickness] ):
literal[string]
keyword[for] identifier[atom] keyword[in] identifier[self] . identifier[particles] ():
keyword[if] identifier[len] ( identifier[self] . identifier[bond_graph] . identifier... | def _identify_surface_sites(self, thickness):
"""Label surface sites and add ports above them. """
for atom in self.particles():
if len(self.bond_graph.neighbors(atom)) == 1:
if atom.name == 'O' and atom.pos[2] > thickness:
atom.name = 'OS'
port = mb.Port(anch... |
def _ivy_jvm_options(self, repo):
"""Get the JVM options for ivy authentication, if needed."""
# Get authentication for the publish repo if needed.
if not repo.get('auth'):
# No need to copy here, as this list isn't modified by the caller.
return self._jvm_options
# Create a copy of the opt... | def function[_ivy_jvm_options, parameter[self, repo]]:
constant[Get the JVM options for ivy authentication, if needed.]
if <ast.UnaryOp object at 0x7da1b1e8cdf0> begin[:]
return[name[self]._jvm_options]
variable[jvm_options] assign[=] call[name[copy], parameter[name[self]._jvm_options]]
... | keyword[def] identifier[_ivy_jvm_options] ( identifier[self] , identifier[repo] ):
literal[string]
keyword[if] keyword[not] identifier[repo] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifier[_jvm_options]
identifier[jvm_options] = identif... | def _ivy_jvm_options(self, repo):
"""Get the JVM options for ivy authentication, if needed."""
# Get authentication for the publish repo if needed.
if not repo.get('auth'):
# No need to copy here, as this list isn't modified by the caller.
return self._jvm_options # depends on [control=['if... |
def are_values_same_type(first_val, second_val):
""" Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False.
... | def function[are_values_same_type, parameter[first_val, second_val]]:
constant[ Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belon... | keyword[def] identifier[are_values_same_type] ( identifier[first_val] , identifier[second_val] ):
literal[string]
identifier[first_val_type] = identifier[type] ( identifier[first_val] )
identifier[second_val_type] = identifier[type] ( identifier[second_val] )
keyword[if] identifier[isinstance] ( id... | def are_values_same_type(first_val, second_val):
""" Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False... |
def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(shebang_parts + cmd,
... | def function[_run_cmd, parameter[cmd]]:
constant[Run command specified by :cmd: and return stdout, stderr and code.]
if <ast.UnaryOp object at 0x7da20e955120> begin[:]
call[name[cmd]][constant[0]] assign[=] call[name[shutil].which, parameter[call[name[cmd]][constant[0]]]]
assert[... | keyword[def] identifier[_run_cmd] ( identifier[cmd] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[cmd] [ literal[int] ]):
identifier[cmd] [ literal[int] ]= identifier[shutil] . identifier[which] ( identifier[cmd] [ literal[int] ])... | def _run_cmd(cmd):
"""Run command specified by :cmd: and return stdout, stderr and code."""
if not os.path.exists(cmd[0]):
cmd[0] = shutil.which(cmd[0])
assert cmd[0] is not None # depends on [control=['if'], data=[]]
shebang_parts = parseshebang.parse(cmd[0])
proc = subprocess.Popen(sh... |
def handle_block(
mediator_state: MediatorTransferState,
state_change: Block,
channelidentifiers_to_channels: ChannelMap,
pseudo_random_generator: random.Random,
) -> TransitionResult[MediatorTransferState]:
""" After Raiden learns about a new block this function must be called to
... | def function[handle_block, parameter[mediator_state, state_change, channelidentifiers_to_channels, pseudo_random_generator]]:
constant[ After Raiden learns about a new block this function must be called to
handle expiration of the hash time locks.
Args:
state: The current state.
Return:
... | keyword[def] identifier[handle_block] (
identifier[mediator_state] : identifier[MediatorTransferState] ,
identifier[state_change] : identifier[Block] ,
identifier[channelidentifiers_to_channels] : identifier[ChannelMap] ,
identifier[pseudo_random_generator] : identifier[random] . identifier[Random] ,
)-> identifi... | def handle_block(mediator_state: MediatorTransferState, state_change: Block, channelidentifiers_to_channels: ChannelMap, pseudo_random_generator: random.Random) -> TransitionResult[MediatorTransferState]:
""" After Raiden learns about a new block this function must be called to
handle expiration of the hash tim... |
def _map_reduce(self, map, reduce, out, session, read_pref, **kwargs):
"""Internal mapReduce helper."""
cmd = SON([("mapReduce", self.__name),
("map", map),
("reduce", reduce),
("out", out)])
collation = validate_collation_or_none(kwargs.p... | def function[_map_reduce, parameter[self, map, reduce, out, session, read_pref]]:
constant[Internal mapReduce helper.]
variable[cmd] assign[=] call[name[SON], parameter[list[[<ast.Tuple object at 0x7da20e9b1990>, <ast.Tuple object at 0x7da20e9b19c0>, <ast.Tuple object at 0x7da20e9b16c0>, <ast.Tuple obje... | keyword[def] identifier[_map_reduce] ( identifier[self] , identifier[map] , identifier[reduce] , identifier[out] , identifier[session] , identifier[read_pref] ,** identifier[kwargs] ):
literal[string]
identifier[cmd] = identifier[SON] ([( literal[string] , identifier[self] . identifier[__name] ),
... | def _map_reduce(self, map, reduce, out, session, read_pref, **kwargs):
"""Internal mapReduce helper."""
cmd = SON([('mapReduce', self.__name), ('map', map), ('reduce', reduce), ('out', out)])
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
inline = 'inline' i... |
def find_commands_module(app_name):
"""
Find the commands module in each app (if it exists) and return the path
app_name : The name of an app in the INSTALLED_APPS setting
return - path to the app
"""
parts = app_name.split('.')
parts.append('commands')
parts.reverse()
part = parts.p... | def function[find_commands_module, parameter[app_name]]:
constant[
Find the commands module in each app (if it exists) and return the path
app_name : The name of an app in the INSTALLED_APPS setting
return - path to the app
]
variable[parts] assign[=] call[name[app_name].split, parameter... | keyword[def] identifier[find_commands_module] ( identifier[app_name] ):
literal[string]
identifier[parts] = identifier[app_name] . identifier[split] ( literal[string] )
identifier[parts] . identifier[append] ( literal[string] )
identifier[parts] . identifier[reverse] ()
identifier[part] = id... | def find_commands_module(app_name):
"""
Find the commands module in each app (if it exists) and return the path
app_name : The name of an app in the INSTALLED_APPS setting
return - path to the app
"""
parts = app_name.split('.')
parts.append('commands')
parts.reverse()
part = parts.p... |
def update_access_key_full(self, access_key_id, name, is_active, permitted, options):
"""
Replaces the 'name', 'is_active', 'permitted', and 'options' values of a given key.
A master key must be set first.
:param access_key_id: the 'key' value of the access key for which the values will... | def function[update_access_key_full, parameter[self, access_key_id, name, is_active, permitted, options]]:
constant[
Replaces the 'name', 'is_active', 'permitted', and 'options' values of a given key.
A master key must be set first.
:param access_key_id: the 'key' value of the access ke... | keyword[def] identifier[update_access_key_full] ( identifier[self] , identifier[access_key_id] , identifier[name] , identifier[is_active] , identifier[permitted] , identifier[options] ):
literal[string]
keyword[return] identifier[self] . identifier[api] . identifier[update_access_key_full] ( ident... | def update_access_key_full(self, access_key_id, name, is_active, permitted, options):
"""
Replaces the 'name', 'is_active', 'permitted', and 'options' values of a given key.
A master key must be set first.
:param access_key_id: the 'key' value of the access key for which the values will be ... |
def _set_receive(self, v, load=False):
"""
Setter method for receive, mapped from YANG variable /routing_system/ipv6/receive (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_receive is considered as a private
method. Backends looking to populate this varia... | def function[_set_receive, parameter[self, v, load]]:
constant[
Setter method for receive, mapped from YANG variable /routing_system/ipv6/receive (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_receive is considered as a private
method. Backends looki... | keyword[def] identifier[_set_receive] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identi... | def _set_receive(self, v, load=False):
"""
Setter method for receive, mapped from YANG variable /routing_system/ipv6/receive (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_receive is considered as a private
method. Backends looking to populate this varia... |
def leading_whitespace(self, inputstring):
"""Count leading whitespace."""
count = 0
for i, c in enumerate(inputstring):
if c == " ":
count += 1
elif c == "\t":
count += tabworth - (i % tabworth)
else:
break
... | def function[leading_whitespace, parameter[self, inputstring]]:
constant[Count leading whitespace.]
variable[count] assign[=] constant[0]
for taget[tuple[[<ast.Name object at 0x7da20c990250>, <ast.Name object at 0x7da20c990df0>]]] in starred[call[name[enumerate], parameter[name[inputstring]]]] b... | keyword[def] identifier[leading_whitespace] ( identifier[self] , identifier[inputstring] ):
literal[string]
identifier[count] = literal[int]
keyword[for] identifier[i] , identifier[c] keyword[in] identifier[enumerate] ( identifier[inputstring] ):
keyword[if] identifier[c]... | def leading_whitespace(self, inputstring):
"""Count leading whitespace."""
count = 0
for (i, c) in enumerate(inputstring):
if c == ' ':
count += 1 # depends on [control=['if'], data=[]]
elif c == '\t':
count += tabworth - i % tabworth # depends on [control=['if'], d... |
def make_img_widget(cls, img, layout=Layout(), format='jpg'):
"Returns an image widget for specified file name `img`."
return widgets.Image(value=img, format=format, layout=layout) | def function[make_img_widget, parameter[cls, img, layout, format]]:
constant[Returns an image widget for specified file name `img`.]
return[call[name[widgets].Image, parameter[]]] | keyword[def] identifier[make_img_widget] ( identifier[cls] , identifier[img] , identifier[layout] = identifier[Layout] (), identifier[format] = literal[string] ):
literal[string]
keyword[return] identifier[widgets] . identifier[Image] ( identifier[value] = identifier[img] , identifier[format] = id... | def make_img_widget(cls, img, layout=Layout(), format='jpg'):
"""Returns an image widget for specified file name `img`."""
return widgets.Image(value=img, format=format, layout=layout) |
def dataset_prepare(self):
'''Subcommand of dataset for processing a corpus into a dataset'''
# Initialize the prepare subcommand's argparser
parser = argparse.ArgumentParser(description='Preprocess a raw dialogue corpus into a dsrt dataset')
self.init_dataset_prepare_args(parser)
... | def function[dataset_prepare, parameter[self]]:
constant[Subcommand of dataset for processing a corpus into a dataset]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[self].init_dataset_prepare_args, parameter[name[parser]]]
variable[args] assign[=] ... | keyword[def] identifier[dataset_prepare] ( identifier[self] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = literal[string] )
identifier[self] . identifier[init_dataset_prepare_args] ( identifier[parser] )
... | def dataset_prepare(self):
"""Subcommand of dataset for processing a corpus into a dataset"""
# Initialize the prepare subcommand's argparser
parser = argparse.ArgumentParser(description='Preprocess a raw dialogue corpus into a dsrt dataset')
self.init_dataset_prepare_args(parser)
# Parse the args w... |
def header(fname, sep="\t"):
"""
just grab the header from a given file
"""
fh = iter(nopen(fname))
h = tokens(next(fh), sep)
h[0] = h[0].lstrip("#")
return h | def function[header, parameter[fname, sep]]:
constant[
just grab the header from a given file
]
variable[fh] assign[=] call[name[iter], parameter[call[name[nopen], parameter[name[fname]]]]]
variable[h] assign[=] call[name[tokens], parameter[call[name[next], parameter[name[fh]]], name[sep... | keyword[def] identifier[header] ( identifier[fname] , identifier[sep] = literal[string] ):
literal[string]
identifier[fh] = identifier[iter] ( identifier[nopen] ( identifier[fname] ))
identifier[h] = identifier[tokens] ( identifier[next] ( identifier[fh] ), identifier[sep] )
identifier[h] [ liter... | def header(fname, sep='\t'):
"""
just grab the header from a given file
"""
fh = iter(nopen(fname))
h = tokens(next(fh), sep)
h[0] = h[0].lstrip('#')
return h |
def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"... | def function[_safe_get_element_date, parameter[self, path, root]]:
constant[Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.d... | keyword[def] identifier[_safe_get_element_date] ( identifier[self] , identifier[path] , identifier[root] = keyword[None] ):
literal[string]
identifier[value] = identifier[self] . identifier[_safe_get_element_text] ( identifier[path] = identifier[path] , identifier[root] = identifier[root] )
... | def _safe_get_element_date(self, path, root=None):
"""Safe get elemnent date.
Get element as datetime.date or None,
:param root:
Lxml element.
:param path:
String path (i.e. 'Items.Item.Offers.Offer').
:return:
datetime.date or None.
"""
... |
def download_article_from_ids(**id_dict):
"""Download an article in XML format from Elsevier matching the set of ids.
Parameters
----------
<id_type> : str
You can enter any combination of eid, doi, pmid, and/or pii. Ids will be
checked in that order, until either content has been found... | def function[download_article_from_ids, parameter[]]:
constant[Download an article in XML format from Elsevier matching the set of ids.
Parameters
----------
<id_type> : str
You can enter any combination of eid, doi, pmid, and/or pii. Ids will be
checked in that order, until either ... | keyword[def] identifier[download_article_from_ids] (** identifier[id_dict] ):
literal[string]
identifier[valid_id_types] =[ literal[string] , literal[string] , literal[string] , literal[string] ]
keyword[assert] identifier[all] ([ identifier[k] keyword[in] identifier[valid_id_types] keyword[for] ... | def download_article_from_ids(**id_dict):
"""Download an article in XML format from Elsevier matching the set of ids.
Parameters
----------
<id_type> : str
You can enter any combination of eid, doi, pmid, and/or pii. Ids will be
checked in that order, until either content has been found... |
def lex(self, text):
""" Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
"""
for match in self.regex.finditer(text):
for name, _ in self.lexicon:
m = match.group(name)
... | def function[lex, parameter[self, text]]:
constant[ Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
]
for taget[name[match]] in starred[call[name[self].regex.finditer, parameter[name[text]]]] begin... | keyword[def] identifier[lex] ( identifier[self] , identifier[text] ):
literal[string]
keyword[for] identifier[match] keyword[in] identifier[self] . identifier[regex] . identifier[finditer] ( identifier[text] ):
keyword[for] identifier[name] , identifier[_] keyword[in] identifier[... | def lex(self, text):
""" Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
"""
for match in self.regex.finditer(text):
for (name, _) in self.lexicon:
m = match.group(name)
if ... |
def status(self, job_ids):
''' Get the status of a list of jobs identified by their ids.
Args:
- job_ids (List of ids) : List of identifiers for the jobs
Returns:
- List of status codes.
'''
logging.debug("Checking status of : {0}".format(job_ids))
... | def function[status, parameter[self, job_ids]]:
constant[ Get the status of a list of jobs identified by their ids.
Args:
- job_ids (List of ids) : List of identifiers for the jobs
Returns:
- List of status codes.
]
call[name[logging].debug, parameter[... | keyword[def] identifier[status] ( identifier[self] , identifier[job_ids] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[job_ids] ))
keyword[for] identifier[job_id] keyword[in] identifier[self] . identifier[resources] :
... | def status(self, job_ids):
""" Get the status of a list of jobs identified by their ids.
Args:
- job_ids (List of ids) : List of identifiers for the jobs
Returns:
- List of status codes.
"""
logging.debug('Checking status of : {0}'.format(job_ids))
for job... |
def semantic_distance(go_id1, go_id2, godag, branch_dist=None):
'''
Finds the semantic distance (minimum number of connecting branches)
between two GO terms.
'''
return min_branch_length(go_id1, go_id2, godag, branch_dist) | def function[semantic_distance, parameter[go_id1, go_id2, godag, branch_dist]]:
constant[
Finds the semantic distance (minimum number of connecting branches)
between two GO terms.
]
return[call[name[min_branch_length], parameter[name[go_id1], name[go_id2], name[godag], name[branch_dist]]... | keyword[def] identifier[semantic_distance] ( identifier[go_id1] , identifier[go_id2] , identifier[godag] , identifier[branch_dist] = keyword[None] ):
literal[string]
keyword[return] identifier[min_branch_length] ( identifier[go_id1] , identifier[go_id2] , identifier[godag] , identifier[branch_dist] ) | def semantic_distance(go_id1, go_id2, godag, branch_dist=None):
"""
Finds the semantic distance (minimum number of connecting branches)
between two GO terms.
"""
return min_branch_length(go_id1, go_id2, godag, branch_dist) |
def get_src_or_dst_path(prompt, count):
"""
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
"""
_path = ""
print(prompt)
option = input("Option: ")
print("\n")
if option == '1':
# Set th... | def function[get_src_or_dst_path, parameter[prompt, count]]:
constant[
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
]
variable[_path] assign[=] constant[]
call[name[print], parameter[name[pro... | keyword[def] identifier[get_src_or_dst_path] ( identifier[prompt] , identifier[count] ):
literal[string]
identifier[_path] = literal[string]
identifier[print] ( identifier[prompt] )
identifier[option] = identifier[input] ( literal[string] )
identifier[print] ( literal[string] )
keyword... | def get_src_or_dst_path(prompt, count):
"""
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
"""
_path = ''
print(prompt)
option = input('Option: ')
print('\n')
if option == '1':
# Set th... |
def input(self, str):
""" Defines input string, removing current lexer.
"""
self.input_data = str
self.lex = lex.lex(object=self)
self.lex.input(self.input_data) | def function[input, parameter[self, str]]:
constant[ Defines input string, removing current lexer.
]
name[self].input_data assign[=] name[str]
name[self].lex assign[=] call[name[lex].lex, parameter[]]
call[name[self].lex.input, parameter[name[self].input_data]] | keyword[def] identifier[input] ( identifier[self] , identifier[str] ):
literal[string]
identifier[self] . identifier[input_data] = identifier[str]
identifier[self] . identifier[lex] = identifier[lex] . identifier[lex] ( identifier[object] = identifier[self] )
identifier[self] . i... | def input(self, str):
""" Defines input string, removing current lexer.
"""
self.input_data = str
self.lex = lex.lex(object=self)
self.lex.input(self.input_data) |
def dump_raw_data(filename, data):
""" Write the data into a raw format file. Big endian is always used.
Parameters
----------
filename: str
Path to the output file
data: numpy.ndarray
n-dimensional image data array.
"""
if data.ndim == 3:
# Begin 3D fix
dat... | def function[dump_raw_data, parameter[filename, data]]:
constant[ Write the data into a raw format file. Big endian is always used.
Parameters
----------
filename: str
Path to the output file
data: numpy.ndarray
n-dimensional image data array.
]
if compare[name[data... | keyword[def] identifier[dump_raw_data] ( identifier[filename] , identifier[data] ):
literal[string]
keyword[if] identifier[data] . identifier[ndim] == literal[int] :
identifier[data] = identifier[data] . identifier[reshape] ([ identifier[data] . identifier[shape] [ literal[int] ], identifier... | def dump_raw_data(filename, data):
""" Write the data into a raw format file. Big endian is always used.
Parameters
----------
filename: str
Path to the output file
data: numpy.ndarray
n-dimensional image data array.
"""
if data.ndim == 3:
# Begin 3D fix
dat... |
def _context_source_file_url(path_or_url):
"""
Returns a URL for a remote or local context CSV file
"""
if path_or_url.startswith('http'):
# Remote CSV. Just return the URL
return path_or_url
if path_or_url.startswith('/'):
# Absolute path
return "file://" + path_or_... | def function[_context_source_file_url, parameter[path_or_url]]:
constant[
Returns a URL for a remote or local context CSV file
]
if call[name[path_or_url].startswith, parameter[constant[http]]] begin[:]
return[name[path_or_url]]
if call[name[path_or_url].startswith, parameter[con... | keyword[def] identifier[_context_source_file_url] ( identifier[path_or_url] ):
literal[string]
keyword[if] identifier[path_or_url] . identifier[startswith] ( literal[string] ):
keyword[return] identifier[path_or_url]
keyword[if] identifier[path_or_url] . identifier[startswith] ( lit... | def _context_source_file_url(path_or_url):
"""
Returns a URL for a remote or local context CSV file
"""
if path_or_url.startswith('http'):
# Remote CSV. Just return the URL
return path_or_url # depends on [control=['if'], data=[]]
if path_or_url.startswith('/'):
# Absolute p... |
def apply_changes(self):
"""Apply changes callback"""
if self.is_modified:
self.save_to_conf()
if self.apply_callback is not None:
self.apply_callback()
# Since the language cannot be retrieved by CONF and the language
# is needed ... | def function[apply_changes, parameter[self]]:
constant[Apply changes callback]
if name[self].is_modified begin[:]
call[name[self].save_to_conf, parameter[]]
if compare[name[self].apply_callback is_not constant[None]] begin[:]
call[name[self].apply_... | keyword[def] identifier[apply_changes] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_modified] :
identifier[self] . identifier[save_to_conf] ()
keyword[if] identifier[self] . identifier[apply_callback] keyword[is] keyword[not] ... | def apply_changes(self):
"""Apply changes callback"""
if self.is_modified:
self.save_to_conf()
if self.apply_callback is not None:
self.apply_callback() # depends on [control=['if'], data=[]] # Since the language cannot be retrieved by CONF and the language
# is needed befo... |
def remove_tag(tag_id):
'''
Delete the records of certain tag.
'''
entry = TabPost2Tag.delete().where(
TabPost2Tag.tag_id == tag_id
)
entry.execute() | def function[remove_tag, parameter[tag_id]]:
constant[
Delete the records of certain tag.
]
variable[entry] assign[=] call[call[name[TabPost2Tag].delete, parameter[]].where, parameter[compare[name[TabPost2Tag].tag_id equal[==] name[tag_id]]]]
call[name[entry].execute, parameter[]... | keyword[def] identifier[remove_tag] ( identifier[tag_id] ):
literal[string]
identifier[entry] = identifier[TabPost2Tag] . identifier[delete] (). identifier[where] (
identifier[TabPost2Tag] . identifier[tag_id] == identifier[tag_id]
)
identifier[entry] . identifier[execute... | def remove_tag(tag_id):
"""
Delete the records of certain tag.
"""
entry = TabPost2Tag.delete().where(TabPost2Tag.tag_id == tag_id)
entry.execute() |
def apns_send_bulk_message(
registration_ids, alert, application_id=None, certfile=None, **kwargs
):
"""
Sends an APNS notification to one or more registration_ids.
The registration_ids argument needs to be a list.
Note that if set alert should always be a string. If it is not set,
it won"t be included in the no... | def function[apns_send_bulk_message, parameter[registration_ids, alert, application_id, certfile]]:
constant[
Sends an APNS notification to one or more registration_ids.
The registration_ids argument needs to be a list.
Note that if set alert should always be a string. If it is not set,
it won"t be include... | keyword[def] identifier[apns_send_bulk_message] (
identifier[registration_ids] , identifier[alert] , identifier[application_id] = keyword[None] , identifier[certfile] = keyword[None] ,** identifier[kwargs]
):
literal[string]
identifier[results] = identifier[_apns_send] (
identifier[registration_ids] , ident... | def apns_send_bulk_message(registration_ids, alert, application_id=None, certfile=None, **kwargs):
"""
Sends an APNS notification to one or more registration_ids.
The registration_ids argument needs to be a list.
Note that if set alert should always be a string. If it is not set,
it won"t be included in the no... |
def add_measurement(self, exp_name, meas_num, spec_name=None, er_data=None, pmag_data=None):
"""
Find actual data object for specimen.
Then create a measurement belonging to that specimen and add it to the data object
"""
specimen = self.find_by_name(spec_name, self.specimens)
... | def function[add_measurement, parameter[self, exp_name, meas_num, spec_name, er_data, pmag_data]]:
constant[
Find actual data object for specimen.
Then create a measurement belonging to that specimen and add it to the data object
]
variable[specimen] assign[=] call[name[self].fin... | keyword[def] identifier[add_measurement] ( identifier[self] , identifier[exp_name] , identifier[meas_num] , identifier[spec_name] = keyword[None] , identifier[er_data] = keyword[None] , identifier[pmag_data] = keyword[None] ):
literal[string]
identifier[specimen] = identifier[self] . identifier[fin... | def add_measurement(self, exp_name, meas_num, spec_name=None, er_data=None, pmag_data=None):
"""
Find actual data object for specimen.
Then create a measurement belonging to that specimen and add it to the data object
"""
specimen = self.find_by_name(spec_name, self.specimens)
measur... |
def swap_args(self, new_args, new_length=None):
"""
This returns the same AST, with the arguments swapped out for new_args.
"""
if len(self.args) == len(new_args) and all(a is b for a,b in zip(self.args, new_args)):
return self
#symbolic = any(a.symbolic for a in ne... | def function[swap_args, parameter[self, new_args, new_length]]:
constant[
This returns the same AST, with the arguments swapped out for new_args.
]
if <ast.BoolOp object at 0x7da1b1d4e590> begin[:]
return[name[self]]
variable[length] assign[=] <ast.IfExp object at 0x7da1b... | keyword[def] identifier[swap_args] ( identifier[self] , identifier[new_args] , identifier[new_length] = keyword[None] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[args] )== identifier[len] ( identifier[new_args] ) keyword[and] identifier[all] ( identifier[a] ke... | def swap_args(self, new_args, new_length=None):
"""
This returns the same AST, with the arguments swapped out for new_args.
"""
if len(self.args) == len(new_args) and all((a is b for (a, b) in zip(self.args, new_args))):
return self # depends on [control=['if'], data=[]]
#symbolic =... |
def index(self, doc, index, doc_type, id=None, parent=None, force_insert=False,
op_type=None, bulk=False, version=None, querystring_args=None, ttl=None):
"""
Index a typed JSON document into a specific index and make it searchable.
"""
if querystring_args is None:
... | def function[index, parameter[self, doc, index, doc_type, id, parent, force_insert, op_type, bulk, version, querystring_args, ttl]]:
constant[
Index a typed JSON document into a specific index and make it searchable.
]
if compare[name[querystring_args] is constant[None]] begin[:]
... | keyword[def] identifier[index] ( identifier[self] , identifier[doc] , identifier[index] , identifier[doc_type] , identifier[id] = keyword[None] , identifier[parent] = keyword[None] , identifier[force_insert] = keyword[False] ,
identifier[op_type] = keyword[None] , identifier[bulk] = keyword[False] , identifier[versi... | def index(self, doc, index, doc_type, id=None, parent=None, force_insert=False, op_type=None, bulk=False, version=None, querystring_args=None, ttl=None):
"""
Index a typed JSON document into a specific index and make it searchable.
"""
if querystring_args is None:
querystring_args = {} ... |
def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
... | def function[get_manager_state, parameter[drop_defaults, widgets]]:
constant[Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
... | keyword[def] identifier[get_manager_state] ( identifier[drop_defaults] = keyword[False] , identifier[widgets] = keyword[None] ):
literal[string]
identifier[state] ={}
keyword[if] identifier[widgets] keyword[is] keyword[None] :
identifier[widgets] = identifier[Widget] . iden... | def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
"""... |
def edit_message_text(self, chat_id, message_id, text, **options):
"""
Edit a text message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param options:... | def function[edit_message_text, parameter[self, chat_id, message_id, text]]:
constant[
Edit a text message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
... | keyword[def] identifier[edit_message_text] ( identifier[self] , identifier[chat_id] , identifier[message_id] , identifier[text] ,** identifier[options] ):
literal[string]
keyword[return] identifier[self] . identifier[api_call] (
literal[string] ,
identifier[chat_id] = identifier[... | def edit_message_text(self, chat_id, message_id, text, **options):
"""
Edit a text message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str text: Text to edit the message to
:param options: Add... |
def emailUser(video, error=None):
"""Emails the author of the video that it has finished processing"""
html = render_to_string('frog/video_email.html', {
'user': video.author,
'error': error,
'video': video,
'SITE_URL': FROG_SITE_URL,
})
subject, from_email, to = 'Video P... | def function[emailUser, parameter[video, error]]:
constant[Emails the author of the video that it has finished processing]
variable[html] assign[=] call[name[render_to_string], parameter[constant[frog/video_email.html], dictionary[[<ast.Constant object at 0x7da20e960af0>, <ast.Constant object at 0x7da20... | keyword[def] identifier[emailUser] ( identifier[video] , identifier[error] = keyword[None] ):
literal[string]
identifier[html] = identifier[render_to_string] ( literal[string] ,{
literal[string] : identifier[video] . identifier[author] ,
literal[string] : identifier[error] ,
literal[string] ... | def emailUser(video, error=None):
"""Emails the author of the video that it has finished processing"""
html = render_to_string('frog/video_email.html', {'user': video.author, 'error': error, 'video': video, 'SITE_URL': FROG_SITE_URL})
(subject, from_email, to) = ('Video Processing Finished{}'.format(error o... |
def propagate(self, date):
"""Compute state of orbit at a given date, past or future
Args:
date (Date)
Return:
Orbit:
"""
i0, Ω0, e0, ω0, M0, n0 = self.tle
n0 *= 60 # conversion to min⁻¹
if isinstance(date, Date):
t0 = self.t... | def function[propagate, parameter[self, date]]:
constant[Compute state of orbit at a given date, past or future
Args:
date (Date)
Return:
Orbit:
]
<ast.Tuple object at 0x7da1b0cebd30> assign[=] name[self].tle
<ast.AugAssign object at 0x7da1b0cebb50>
... | keyword[def] identifier[propagate] ( identifier[self] , identifier[date] ):
literal[string]
identifier[i0] , identifier[Ω0] , identifier[e0] , identifier[ω0] , identifier[M0] , identifier[n0] = identifier[self] . identifier[tle]
identifier[n0] *= literal[int]
keyword[if] ident... | def propagate(self, date):
"""Compute state of orbit at a given date, past or future
Args:
date (Date)
Return:
Orbit:
"""
(i0, Ω0, e0, ω0, M0, n0) = self.tle
n0 *= 60 # conversion to min⁻¹
if isinstance(date, Date):
t0 = self.tle.date.datetime
... |
def issue_reactions(self, issue_number):
"""Get reactions of an issue"""
payload = {
'per_page': PER_PAGE,
'direction': 'asc',
'sort': 'updated'
}
path = urijoin("issues", str(issue_number), "reactions")
return self.fetch_items(path, payload) | def function[issue_reactions, parameter[self, issue_number]]:
constant[Get reactions of an issue]
variable[payload] assign[=] dictionary[[<ast.Constant object at 0x7da1b0351900>, <ast.Constant object at 0x7da1b0351810>, <ast.Constant object at 0x7da1b0351360>], [<ast.Name object at 0x7da1b0352e60>, <ast... | keyword[def] identifier[issue_reactions] ( identifier[self] , identifier[issue_number] ):
literal[string]
identifier[payload] ={
literal[string] : identifier[PER_PAGE] ,
literal[string] : literal[string] ,
literal[string] : literal[string]
}
identifier... | def issue_reactions(self, issue_number):
"""Get reactions of an issue"""
payload = {'per_page': PER_PAGE, 'direction': 'asc', 'sort': 'updated'}
path = urijoin('issues', str(issue_number), 'reactions')
return self.fetch_items(path, payload) |
def _kl_divergence(self, other_locs, other_weights, kernel=None, delta=1e-2):
"""
Finds the KL divergence between this and another particle
distribution by using a kernel density estimator to smooth over the
other distribution's particles.
"""
if kernel is None:
... | def function[_kl_divergence, parameter[self, other_locs, other_weights, kernel, delta]]:
constant[
Finds the KL divergence between this and another particle
distribution by using a kernel density estimator to smooth over the
other distribution's particles.
]
if compare[na... | keyword[def] identifier[_kl_divergence] ( identifier[self] , identifier[other_locs] , identifier[other_weights] , identifier[kernel] = keyword[None] , identifier[delta] = literal[int] ):
literal[string]
keyword[if] identifier[kernel] keyword[is] keyword[None] :
identifier[kernel] = ... | def _kl_divergence(self, other_locs, other_weights, kernel=None, delta=0.01):
"""
Finds the KL divergence between this and another particle
distribution by using a kernel density estimator to smooth over the
other distribution's particles.
"""
if kernel is None:
kernel = ... |
def remove(self,
package,
shutit_pexpect_child=None,
options=None,
echo=None,
timeout=shutit_global.shutit_global_object.default_timeout,
note=None):
"""Distro-independent remove function.
Takes a package name and runs relevant remove function.... | def function[remove, parameter[self, package, shutit_pexpect_child, options, echo, timeout, note]]:
constant[Distro-independent remove function.
Takes a package name and runs relevant remove function.
@param package: Package to remove, which is run through package_map.
@param shutit_pexpect_child: Se... | keyword[def] identifier[remove] ( identifier[self] ,
identifier[package] ,
identifier[shutit_pexpect_child] = keyword[None] ,
identifier[options] = keyword[None] ,
identifier[echo] = keyword[None] ,
identifier[timeout] = identifier[shutit_global] . identifier[shutit_global_object] . identifier[default_timeout] ,... | def remove(self, package, shutit_pexpect_child=None, options=None, echo=None, timeout=shutit_global.shutit_global_object.default_timeout, note=None):
"""Distro-independent remove function.
Takes a package name and runs relevant remove function.
@param package: Package to remove, which is run through package_m... |
def simplify(self, e=None):
"""
Simplifies `e`. If `e` is None, simplifies the constraints of this
state.
"""
if e is None:
return self._solver.simplify()
elif isinstance(e, (int, float, bool)):
return e
elif isinstance(e, claripy.ast.Base)... | def function[simplify, parameter[self, e]]:
constant[
Simplifies `e`. If `e` is None, simplifies the constraints of this
state.
]
if compare[name[e] is constant[None]] begin[:]
return[call[name[self]._solver.simplify, parameter[]]] | keyword[def] identifier[simplify] ( identifier[self] , identifier[e] = keyword[None] ):
literal[string]
keyword[if] identifier[e] keyword[is] keyword[None] :
keyword[return] identifier[self] . identifier[_solver] . identifier[simplify] ()
keyword[elif] identifier[isinstan... | def simplify(self, e=None):
"""
Simplifies `e`. If `e` is None, simplifies the constraints of this
state.
"""
if e is None:
return self._solver.simplify() # depends on [control=['if'], data=[]]
elif isinstance(e, (int, float, bool)):
return e # depends on [control=[... |
def authorized_purchase_object(self, oid, price, huid):
"""Does delegated (pre-authorized) purchase of `oid` in the name of
`huid`, at price `price` (vingd transferred from `huid` to consumer's
acc).
:raises GeneralException:
:resource: ``objects/<oid>/purchases``
... | def function[authorized_purchase_object, parameter[self, oid, price, huid]]:
constant[Does delegated (pre-authorized) purchase of `oid` in the name of
`huid`, at price `price` (vingd transferred from `huid` to consumer's
acc).
:raises GeneralException:
:resource: ``objec... | keyword[def] identifier[authorized_purchase_object] ( identifier[self] , identifier[oid] , identifier[price] , identifier[huid] ):
literal[string]
keyword[return] identifier[self] . identifier[request] (
literal[string] ,
identifier[safeformat] ( literal[string] , identifier[oid]... | def authorized_purchase_object(self, oid, price, huid):
"""Does delegated (pre-authorized) purchase of `oid` in the name of
`huid`, at price `price` (vingd transferred from `huid` to consumer's
acc).
:raises GeneralException:
:resource: ``objects/<oid>/purchases``
... |
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
'''Implement the FileCookieJar abstract method.'''
if filename is None:
if self.filename is not None:
filename = self.filename
else:
raise ValueError(cookiejar.MISSING_FILEN... | def function[save, parameter[self, filename, ignore_discard, ignore_expires]]:
constant[Implement the FileCookieJar abstract method.]
if compare[name[filename] is constant[None]] begin[:]
if compare[name[self].filename is_not constant[None]] begin[:]
variable[file... | keyword[def] identifier[save] ( identifier[self] , identifier[filename] = keyword[None] , identifier[ignore_discard] = keyword[False] , identifier[ignore_expires] = keyword[False] ):
literal[string]
keyword[if] identifier[filename] keyword[is] keyword[None] :
keyword[if] identifier... | def save(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Implement the FileCookieJar abstract method."""
if filename is None:
if self.filename is not None:
filename = self.filename # depends on [control=['if'], data=[]]
else:
raise ValueError(cookiej... |
def update(self, user, name=None, password=None, host=None):
"""
Allows you to change one or more of the user's username, password, or
host.
"""
if not any((name, password, host)):
raise exc.MissingDBUserParameters("You must supply at least one of "
... | def function[update, parameter[self, user, name, password, host]]:
constant[
Allows you to change one or more of the user's username, password, or
host.
]
if <ast.UnaryOp object at 0x7da1b055aa40> begin[:]
<ast.Raise object at 0x7da1b055aef0>
if <ast.UnaryOp objec... | keyword[def] identifier[update] ( identifier[self] , identifier[user] , identifier[name] = keyword[None] , identifier[password] = keyword[None] , identifier[host] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[any] (( identifier[name] , identifier[password] , identifier[ho... | def update(self, user, name=None, password=None, host=None):
"""
Allows you to change one or more of the user's username, password, or
host.
"""
if not any((name, password, host)):
raise exc.MissingDBUserParameters('You must supply at least one of the following: new username, new... |
def send(self, message_id, stm_id, args=[], kwargs={}):
"""
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earl... | def function[send, parameter[self, message_id, stm_id, args, kwargs]]:
constant[
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of... | keyword[def] identifier[send] ( identifier[self] , identifier[message_id] , identifier[stm_id] , identifier[args] =[], identifier[kwargs] ={}):
literal[string]
keyword[if] identifier[stm_id] keyword[not] keyword[in] identifier[Driver] . identifier[_stms_by_id] :
identifier[self] . ... | def send(self, message_id, stm_id, args=[], kwargs={}):
"""
Send a message to a state machine handled by this driver.
If you have a reference to the state machine, you can also send it
directly to it by using `stmpy.Machine.send`.
`stm_id` must be the id of a state machine earlier ... |
def truncate_schema(self):
""" Will delete all data in schema. Only for test use!"""
assert self.server == 'localhost'
con = self.connection or self._connect()
self._initialize(con)
cur = con.cursor()
cur.execute('DELETE FROM publication;')
cur.execute('TRUNCATE... | def function[truncate_schema, parameter[self]]:
constant[ Will delete all data in schema. Only for test use!]
assert[compare[name[self].server equal[==] constant[localhost]]]
variable[con] assign[=] <ast.BoolOp object at 0x7da20e74b0a0>
call[name[self]._initialize, parameter[name[con]]]
... | keyword[def] identifier[truncate_schema] ( identifier[self] ):
literal[string]
keyword[assert] identifier[self] . identifier[server] == literal[string]
identifier[con] = identifier[self] . identifier[connection] keyword[or] identifier[self] . identifier[_connect] ()
identifie... | def truncate_schema(self):
""" Will delete all data in schema. Only for test use!"""
assert self.server == 'localhost'
con = self.connection or self._connect()
self._initialize(con)
cur = con.cursor()
cur.execute('DELETE FROM publication;')
cur.execute('TRUNCATE systems CASCADE;')
con.co... |
def _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file):
"""
Write the bvals from the sorted dicom files to a bval file
"""
# get the bvals and bvecs
bvals, bvecs = _get_bvals_bvecs(grouped_dicoms)
# save the found bvecs to the file
common.write_bval_file(bvals, bval_file)
common... | def function[_create_bvals_bvecs, parameter[grouped_dicoms, bval_file, bvec_file]]:
constant[
Write the bvals from the sorted dicom files to a bval file
]
<ast.Tuple object at 0x7da1b1307d60> assign[=] call[name[_get_bvals_bvecs], parameter[name[grouped_dicoms]]]
call[name[common].write_... | keyword[def] identifier[_create_bvals_bvecs] ( identifier[grouped_dicoms] , identifier[bval_file] , identifier[bvec_file] ):
literal[string]
identifier[bvals] , identifier[bvecs] = identifier[_get_bvals_bvecs] ( identifier[grouped_dicoms] )
identifier[common] . identifier[write_bval_file] ... | def _create_bvals_bvecs(grouped_dicoms, bval_file, bvec_file):
"""
Write the bvals from the sorted dicom files to a bval file
"""
# get the bvals and bvecs
(bvals, bvecs) = _get_bvals_bvecs(grouped_dicoms)
# save the found bvecs to the file
common.write_bval_file(bvals, bval_file)
common... |
def _create(cls, repo, path, resolve, reference, force, logmsg=None):
"""internal method used to create a new symbolic reference.
If resolve is False, the reference will be taken as is, creating
a proper symbolic reference. Otherwise it will be resolved to the
corresponding object and a ... | def function[_create, parameter[cls, repo, path, resolve, reference, force, logmsg]]:
constant[internal method used to create a new symbolic reference.
If resolve is False, the reference will be taken as is, creating
a proper symbolic reference. Otherwise it will be resolved to the
corre... | keyword[def] identifier[_create] ( identifier[cls] , identifier[repo] , identifier[path] , identifier[resolve] , identifier[reference] , identifier[force] , identifier[logmsg] = keyword[None] ):
literal[string]
identifier[git_dir] = identifier[_git_dir] ( identifier[repo] , identifier[path] )
... | def _create(cls, repo, path, resolve, reference, force, logmsg=None):
"""internal method used to create a new symbolic reference.
If resolve is False, the reference will be taken as is, creating
a proper symbolic reference. Otherwise it will be resolved to the
corresponding object and a deta... |
def lstrip(self, chars=None):
""" Like str.lstrip, except it returns the Colr instance. """
return self.__class__(
self._str_strip('lstrip', chars),
no_closing=chars and (closing_code in chars),
) | def function[lstrip, parameter[self, chars]]:
constant[ Like str.lstrip, except it returns the Colr instance. ]
return[call[name[self].__class__, parameter[call[name[self]._str_strip, parameter[constant[lstrip], name[chars]]]]]] | keyword[def] identifier[lstrip] ( identifier[self] , identifier[chars] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[__class__] (
identifier[self] . identifier[_str_strip] ( literal[string] , identifier[chars] ),
identifier[no_closing] = identif... | def lstrip(self, chars=None):
""" Like str.lstrip, except it returns the Colr instance. """
return self.__class__(self._str_strip('lstrip', chars), no_closing=chars and closing_code in chars) |
def headerData(self, section, orientation, role):
"""Return the header data
Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the
given section (column) and role for horizontal orientations.
Vertical orientations are numbered.
:param section: the section in th... | def function[headerData, parameter[self, section, orientation, role]]:
constant[Return the header data
Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the
given section (column) and role for horizontal orientations.
Vertical orientations are numbered.
:param... | keyword[def] identifier[headerData] ( identifier[self] , identifier[section] , identifier[orientation] , identifier[role] ):
literal[string]
keyword[if] identifier[orientation] == identifier[QtCore] . identifier[Qt] . identifier[Horizontal] :
identifier[d] = identifier[self] . identif... | def headerData(self, section, orientation, role):
"""Return the header data
Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the
given section (column) and role for horizontal orientations.
Vertical orientations are numbered.
:param section: the section in the he... |
def _get_match_and_classification(self, urls):
"""Get classification for all matching URLs.
:param urls: a sequence of URLs to test
:return: a tuple containing matching URL and classification
string pertaining to it
"""
for url_list, response in self._query(urls):
... | def function[_get_match_and_classification, parameter[self, urls]]:
constant[Get classification for all matching URLs.
:param urls: a sequence of URLs to test
:return: a tuple containing matching URL and classification
string pertaining to it
]
for taget[tuple[[<ast.Name... | keyword[def] identifier[_get_match_and_classification] ( identifier[self] , identifier[urls] ):
literal[string]
keyword[for] identifier[url_list] , identifier[response] keyword[in] identifier[self] . identifier[_query] ( identifier[urls] ):
identifier[classification_set] = identifie... | def _get_match_and_classification(self, urls):
"""Get classification for all matching URLs.
:param urls: a sequence of URLs to test
:return: a tuple containing matching URL and classification
string pertaining to it
"""
for (url_list, response) in self._query(urls):
clas... |
def mi_chain_rule(X, y):
'''
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: iterable of symbols
... | def function[mi_chain_rule, parameter[X, y]]:
constant[
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: ... | keyword[def] identifier[mi_chain_rule] ( identifier[X] , identifier[y] ):
literal[string]
identifier[chain] = identifier[np] . identifier[zeros] ( identifier[len] ( identifier[X] ))
identifier[chain] [ literal[int] ]= identifier[mi] ( identifier[X] [ literal[int] ], identifier[y] )
k... | def mi_chain_rule(X, y):
"""
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: iterable of symbols
... |
def profiles(self):
"""
A list of all profiles on this web property. You may
select a specific profile using its name, its id
or an index.
```python
property.profiles[0]
property.profiles['9234823']
property.profiles['marketing profile']
```
... | def function[profiles, parameter[self]]:
constant[
A list of all profiles on this web property. You may
select a specific profile using its name, its id
or an index.
```python
property.profiles[0]
property.profiles['9234823']
property.profiles['marketing ... | keyword[def] identifier[profiles] ( identifier[self] ):
literal[string]
identifier[raw_profiles] = identifier[self] . identifier[account] . identifier[service] . identifier[management] (). identifier[profiles] (). identifier[list] (
identifier[accountId] = identifier[self] . identifier[acc... | def profiles(self):
"""
A list of all profiles on this web property. You may
select a specific profile using its name, its id
or an index.
```python
property.profiles[0]
property.profiles['9234823']
property.profiles['marketing profile']
```
"... |
def tauchen(N, mu, rho, sigma, m=2):
"""
Approximate an AR1 process by a finite markov chain using Tauchen's method.
:param N: scalar, number of nodes for Z
:param mu: scalar, unconditional mean of process
:param rho: scalar
:param sigma: scalar, std. dev. of epsilons
:param m: max +- std. ... | def function[tauchen, parameter[N, mu, rho, sigma, m]]:
constant[
Approximate an AR1 process by a finite markov chain using Tauchen's method.
:param N: scalar, number of nodes for Z
:param mu: scalar, unconditional mean of process
:param rho: scalar
:param sigma: scalar, std. dev. of epsilo... | keyword[def] identifier[tauchen] ( identifier[N] , identifier[mu] , identifier[rho] , identifier[sigma] , identifier[m] = literal[int] ):
literal[string]
identifier[Z] = identifier[np] . identifier[zeros] (( identifier[N] , literal[int] ))
identifier[Zprob] = identifier[np] . identifier[zeros] (( iden... | def tauchen(N, mu, rho, sigma, m=2):
"""
Approximate an AR1 process by a finite markov chain using Tauchen's method.
:param N: scalar, number of nodes for Z
:param mu: scalar, unconditional mean of process
:param rho: scalar
:param sigma: scalar, std. dev. of epsilons
:param m: max +- std. ... |
def strip_extras_markers_from_requirement(req):
# type: (TRequirement) -> TRequirement
"""
Given a :class:`~packaging.requirements.Requirement` instance with markers defining
*extra == 'name'*, strip out the extras from the markers and return the cleaned
requirement
:param PackagingRequirement ... | def function[strip_extras_markers_from_requirement, parameter[req]]:
constant[
Given a :class:`~packaging.requirements.Requirement` instance with markers defining
*extra == 'name'*, strip out the extras from the markers and return the cleaned
requirement
:param PackagingRequirement req: A packa... | keyword[def] identifier[strip_extras_markers_from_requirement] ( identifier[req] ):
literal[string]
keyword[if] identifier[req] keyword[is] keyword[None] :
keyword[raise] identifier[TypeError] ( literal[string] . identifier[format] ( identifier[req] ))
keyword[if] identifier[getattr] ( ... | def strip_extras_markers_from_requirement(req):
# type: (TRequirement) -> TRequirement
"\n Given a :class:`~packaging.requirements.Requirement` instance with markers defining\n *extra == 'name'*, strip out the extras from the markers and return the cleaned\n requirement\n\n :param PackagingRequireme... |
def QA_SU_save_deal(dealist, client=DATABASE):
"""存储order_handler的deal_status
Arguments:
dealist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
if isinstance(dealist, pd.DataFrame):
collection = client.deal
... | def function[QA_SU_save_deal, parameter[dealist, client]]:
constant[存储order_handler的deal_status
Arguments:
dealist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
]
if call[name[isinstance], parameter[name[dealist], n... | keyword[def] identifier[QA_SU_save_deal] ( identifier[dealist] , identifier[client] = identifier[DATABASE] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[dealist] , identifier[pd] . identifier[DataFrame] ):
identifier[collection] = identifier[client] . identifier[deal]
... | def QA_SU_save_deal(dealist, client=DATABASE):
"""存储order_handler的deal_status
Arguments:
dealist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
if isinstance(dealist, pd.DataFrame):
collection = client.deal
... |
def determine_api_port(public_port, singlenode_mode=False):
'''
Determine correct API server listening port based on
existence of HTTPS reverse proxy and/or haproxy.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
... | def function[determine_api_port, parameter[public_port, singlenode_mode]]:
constant[
Determine correct API server listening port based on
existence of HTTPS reverse proxy and/or haproxy.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only ... | keyword[def] identifier[determine_api_port] ( identifier[public_port] , identifier[singlenode_mode] = keyword[False] ):
literal[string]
identifier[i] = literal[int]
keyword[if] identifier[singlenode_mode] :
identifier[i] += literal[int]
keyword[elif] identifier[len] ( identifier[peer... | def determine_api_port(public_port, singlenode_mode=False):
"""
Determine correct API server listening port based on
existence of HTTPS reverse proxy and/or haproxy.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
... |
def construct_request_uri(local_dir, base_path, **kwargs):
"""
Constructs a special redirect_uri to be used when communicating with
one OP. Each OP should get their own redirect_uris.
:param local_dir: Local directory in which to place the file
:param base_path: Base URL to start with
:para... | def function[construct_request_uri, parameter[local_dir, base_path]]:
constant[
Constructs a special redirect_uri to be used when communicating with
one OP. Each OP should get their own redirect_uris.
:param local_dir: Local directory in which to place the file
:param base_path: Base URL to... | keyword[def] identifier[construct_request_uri] ( identifier[local_dir] , identifier[base_path] ,** identifier[kwargs] ):
literal[string]
identifier[_filedir] = identifier[local_dir]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[_filedir] ):
ide... | def construct_request_uri(local_dir, base_path, **kwargs):
"""
Constructs a special redirect_uri to be used when communicating with
one OP. Each OP should get their own redirect_uris.
:param local_dir: Local directory in which to place the file
:param base_path: Base URL to start with
:para... |
def cli(env, identifier):
"""Cancel global IP."""
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
name='global ip')
if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)):
... | def function[cli, parameter[env, identifier]]:
constant[Cancel global IP.]
variable[mgr] assign[=] call[name[SoftLayer].NetworkManager, parameter[name[env].client]]
variable[global_ip_id] assign[=] call[name[helpers].resolve_id, parameter[name[mgr].resolve_global_ip_ids, name[identifier]]]
... | keyword[def] identifier[cli] ( identifier[env] , identifier[identifier] ):
literal[string]
identifier[mgr] = identifier[SoftLayer] . identifier[NetworkManager] ( identifier[env] . identifier[client] )
identifier[global_ip_id] = identifier[helpers] . identifier[resolve_id] ( identifier[mgr] . identifi... | def cli(env, identifier):
"""Cancel global IP."""
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip')
if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)):
raise exceptions.CLIAbort('Aborted') ... |
def all_sample_md5s(self, type_tag=None):
"""Return a list of all md5 matching the type_tag ('exe','pdf', etc).
Args:
type_tag: the type of sample.
Returns:
a list of matching samples.
"""
if type_tag:
cursor = self.database[self.sample_coll... | def function[all_sample_md5s, parameter[self, type_tag]]:
constant[Return a list of all md5 matching the type_tag ('exe','pdf', etc).
Args:
type_tag: the type of sample.
Returns:
a list of matching samples.
]
if name[type_tag] begin[:]
va... | keyword[def] identifier[all_sample_md5s] ( identifier[self] , identifier[type_tag] = keyword[None] ):
literal[string]
keyword[if] identifier[type_tag] :
identifier[cursor] = identifier[self] . identifier[database] [ identifier[self] . identifier[sample_collection] ]. identifier[find]... | def all_sample_md5s(self, type_tag=None):
"""Return a list of all md5 matching the type_tag ('exe','pdf', etc).
Args:
type_tag: the type of sample.
Returns:
a list of matching samples.
"""
if type_tag:
cursor = self.database[self.sample_collection].find(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.