code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def iteritems(self, **options):
'''Return a query interator with (id, object) pairs.'''
iter = self.query(**options)
while True:
obj = iter.next()
yield (obj.id, obj) | def function[iteritems, parameter[self]]:
constant[Return a query interator with (id, object) pairs.]
variable[iter] assign[=] call[name[self].query, parameter[]]
while constant[True] begin[:]
variable[obj] assign[=] call[name[iter].next, parameter[]]
<ast.Yield o... | keyword[def] identifier[iteritems] ( identifier[self] ,** identifier[options] ):
literal[string]
identifier[iter] = identifier[self] . identifier[query] (** identifier[options] )
keyword[while] keyword[True] :
identifier[obj] = identifier[iter] . identifier[next] ()
... | def iteritems(self, **options):
"""Return a query interator with (id, object) pairs."""
iter = self.query(**options)
while True:
obj = iter.next()
yield (obj.id, obj) # depends on [control=['while'], data=[]] |
def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None,
path=None, selected=None, info=None, properties=None,
context_menu=None, replace_context_menu=False,
is_playable=None, info_type='video', stream_info=None):
'''A ListItem constructor for ... | def function[from_dict, parameter[cls, label, label2, icon, thumbnail, path, selected, info, properties, context_menu, replace_context_menu, is_playable, info_type, stream_info]]:
constant[A ListItem constructor for setting a lot of properties not
available in the regular __init__ method. Useful to coll... | keyword[def] identifier[from_dict] ( identifier[cls] , identifier[label] = keyword[None] , identifier[label2] = keyword[None] , identifier[icon] = keyword[None] , identifier[thumbnail] = keyword[None] ,
identifier[path] = keyword[None] , identifier[selected] = keyword[None] , identifier[info] = keyword[None] , ident... | def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None, path=None, selected=None, info=None, properties=None, context_menu=None, replace_context_menu=False, is_playable=None, info_type='video', stream_info=None):
"""A ListItem constructor for setting a lot of properties not
available in the r... |
def buses_of_vlvl(network, voltage_level):
""" Get bus-ids of given voltage level(s).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
voltage_level: list
Returns
-------
list
List containing bus-ids.
"""
mask = network.buses.v_n... | def function[buses_of_vlvl, parameter[network, voltage_level]]:
constant[ Get bus-ids of given voltage level(s).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
voltage_level: list
Returns
-------
list
List containing bus-ids.
]
... | keyword[def] identifier[buses_of_vlvl] ( identifier[network] , identifier[voltage_level] ):
literal[string]
identifier[mask] = identifier[network] . identifier[buses] . identifier[v_nom] . identifier[isin] ( identifier[voltage_level] )
identifier[df] = identifier[network] . identifier[buses] [ identi... | def buses_of_vlvl(network, voltage_level):
""" Get bus-ids of given voltage level(s).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
voltage_level: list
Returns
-------
list
List containing bus-ids.
"""
mask = network.buses.v_no... |
def validate_file(file_type, file_path):
"""
Validates a file against a schema
Parameters
----------
file_type : str
Type of file to read. May be 'component', 'element', 'table', or 'references'
file_path:
Full path to the file to be validated
Raises
------
RuntimeE... | def function[validate_file, parameter[file_type, file_path]]:
constant[
Validates a file against a schema
Parameters
----------
file_type : str
Type of file to read. May be 'component', 'element', 'table', or 'references'
file_path:
Full path to the file to be validated
... | keyword[def] identifier[validate_file] ( identifier[file_type] , identifier[file_path] ):
literal[string]
identifier[file_data] = identifier[fileio] . identifier[_read_plain_json] ( identifier[file_path] , keyword[False] )
identifier[validate_data] ( identifier[file_type] , identifier[file_data] ) | def validate_file(file_type, file_path):
"""
Validates a file against a schema
Parameters
----------
file_type : str
Type of file to read. May be 'component', 'element', 'table', or 'references'
file_path:
Full path to the file to be validated
Raises
------
RuntimeE... |
def _create_tag_lowlevel(self, tag_name, message=None, force=True,
patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commi... | def function[_create_tag_lowlevel, parameter[self, tag_name, message, force, patch]]:
constant[Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and the... | keyword[def] identifier[_create_tag_lowlevel] ( identifier[self] , identifier[tag_name] , identifier[message] = keyword[None] , identifier[force] = keyword[True] ,
identifier[patch] = keyword[False] ):
literal[string]
... | def _create_tag_lowlevel(self, tag_name, message=None, force=True, patch=False):
"""Create a tag on the toplevel or patch repo
If the tag exists, and force is False, no tag is made. If force is True,
and a tag exists, but it is a direct ancestor of the current commit,
and there is no differ... |
def md5(self):
"""
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
"""
result = str(self._updated) + str(self.base_frame)
return result | def function[md5, parameter[self]]:
constant[
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
]
variable[result] assign[=] binary_operation[call[name[str], parameter[name[self]._updated]] + call[name[str], parameter[nam... | keyword[def] identifier[md5] ( identifier[self] ):
literal[string]
identifier[result] = identifier[str] ( identifier[self] . identifier[_updated] )+ identifier[str] ( identifier[self] . identifier[base_frame] )
keyword[return] identifier[result] | def md5(self):
"""
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
"""
result = str(self._updated) + str(self.base_frame)
return result |
def _from_objects(cls, objects):
"""
Private constructor: create graph from the given Python objects.
The constructor examines the referents of each given object to build up
a graph showing the objects and their links.
"""
vertices = ElementTransformSet(transform=id)
... | def function[_from_objects, parameter[cls, objects]]:
constant[
Private constructor: create graph from the given Python objects.
The constructor examines the referents of each given object to build up
a graph showing the objects and their links.
]
variable[vertices] ass... | keyword[def] identifier[_from_objects] ( identifier[cls] , identifier[objects] ):
literal[string]
identifier[vertices] = identifier[ElementTransformSet] ( identifier[transform] = identifier[id] )
identifier[out_edges] = identifier[KeyTransformDict] ( identifier[transform] = identifier[id] ... | def _from_objects(cls, objects):
"""
Private constructor: create graph from the given Python objects.
The constructor examines the referents of each given object to build up
a graph showing the objects and their links.
"""
vertices = ElementTransformSet(transform=id)
out_ed... |
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSys... | def function[show_blob_service_properties, parameter[kwargs, storage_conn, call]]:
constant[
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
]
if compare[name[call] not_equal... | keyword[def] identifier[show_blob_service_properties] ( identifier[kwargs] = keyword[None] , identifier[storage_conn] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
... | def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
"""
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
"""
if call != 'function':
raise SaltCloudSys... |
def add_cmd_to_checkplot(
cpx,
cmdpkl,
require_cmd_magcolor=True,
save_cmd_pngs=False
):
'''This adds CMD figures to a checkplot dict or pickle.
Looks up the CMDs in `cmdpkl`, adds the object from `cpx` as a gold(-ish)
star in the plot, and then saves the figure to a base64 ... | def function[add_cmd_to_checkplot, parameter[cpx, cmdpkl, require_cmd_magcolor, save_cmd_pngs]]:
constant[This adds CMD figures to a checkplot dict or pickle.
Looks up the CMDs in `cmdpkl`, adds the object from `cpx` as a gold(-ish)
star in the plot, and then saves the figure to a base64 encoded PNG, w... | keyword[def] identifier[add_cmd_to_checkplot] (
identifier[cpx] ,
identifier[cmdpkl] ,
identifier[require_cmd_magcolor] = keyword[True] ,
identifier[save_cmd_pngs] = keyword[False]
):
literal[string]
keyword[if] identifier[isinstance] ( identifier[cpx] , identifier[str] ) keyword[and] identifi... | def add_cmd_to_checkplot(cpx, cmdpkl, require_cmd_magcolor=True, save_cmd_pngs=False):
"""This adds CMD figures to a checkplot dict or pickle.
Looks up the CMDs in `cmdpkl`, adds the object from `cpx` as a gold(-ish)
star in the plot, and then saves the figure to a base64 encoded PNG, which
can then be... |
def destroy_window(window):
'''
Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window);
'''
_glfw.glfwDestroyWindow(window)
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_ulong)).con... | def function[destroy_window, parameter[window]]:
constant[
Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window);
]
call[name[_glfw].glfwDestroyWindow, parameter[name[window]]]
variable[window_addr] assign[=] call[name[ctypes]... | keyword[def] identifier[destroy_window] ( identifier[window] ):
literal[string]
identifier[_glfw] . identifier[glfwDestroyWindow] ( identifier[window] )
identifier[window_addr] = identifier[ctypes] . identifier[cast] ( identifier[ctypes] . identifier[pointer] ( identifier[window] ),
identifier[ct... | def destroy_window(window):
"""
Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window);
"""
_glfw.glfwDestroyWindow(window)
window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_ulong)).contents.value
for callback_r... |
def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") | def function[storeByteArray, parameter[self, context, page, len, data, returnError]]:
constant[please override]
name[returnError].contents.value assign[=] name[self].IllegalStateError
<ast.Raise object at 0x7da1b05c88e0> | keyword[def] identifier[storeByteArray] ( identifier[self] , identifier[context] , identifier[page] , identifier[len] , identifier[data] , identifier[returnError] ):
literal[string]
identifier[returnError] . identifier[contents] . identifier[value] = identifier[self] . identifier[IllegalStateError]... | def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError('You must override this method.') |
def reset_highlights(self):
"""
Remove red outlines from all buttons
"""
for dtype in ["specimens", "samples", "sites", "locations", "ages"]:
wind = self.FindWindowByName(dtype + '_btn')
wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button)
self.Refresh... | def function[reset_highlights, parameter[self]]:
constant[
Remove red outlines from all buttons
]
for taget[name[dtype]] in starred[list[[<ast.Constant object at 0x7da20e956950>, <ast.Constant object at 0x7da20e9578b0>, <ast.Constant object at 0x7da20e955ae0>, <ast.Constant object at 0x7... | keyword[def] identifier[reset_highlights] ( identifier[self] ):
literal[string]
keyword[for] identifier[dtype] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]:
identifier[wind] = identifier[self] . identifier[FindWindowByName] (... | def reset_highlights(self):
"""
Remove red outlines from all buttons
"""
for dtype in ['specimens', 'samples', 'sites', 'locations', 'ages']:
wind = self.FindWindowByName(dtype + '_btn')
wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button) # depends on [control=['for'], data... |
def DbPutClassAttributeProperty2(self, argin):
""" This command adds support for array properties compared to the previous one
called DbPutClassAttributeProperty. The old comman is still there for compatibility reason
:param argin: Str[0] = Tango class name
Str[1] = Attribute number
... | def function[DbPutClassAttributeProperty2, parameter[self, argin]]:
constant[ This command adds support for array properties compared to the previous one
called DbPutClassAttributeProperty. The old comman is still there for compatibility reason
:param argin: Str[0] = Tango class name
St... | keyword[def] identifier[DbPutClassAttributeProperty2] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
identifier[class_name] = identifier[argin] [ literal[int] ]
identifier[nb_attributes] = ident... | def DbPutClassAttributeProperty2(self, argin):
""" This command adds support for array properties compared to the previous one
called DbPutClassAttributeProperty. The old comman is still there for compatibility reason
:param argin: Str[0] = Tango class name
Str[1] = Attribute number
... |
def walknset_vars(self, task_class=None, *args, **kwargs):
"""
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:
... | def function[walknset_vars, parameter[self, task_class]]:
constant[
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:... | keyword[def] identifier[walknset_vars] ( identifier[self] , identifier[task_class] = keyword[None] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[change_task] ( identifier[task] ):
keyword[if] identifier[task_class] keyword[is] keyword[not] k... | def walknset_vars(self, task_class=None, *args, **kwargs):
"""
Set the values of the ABINIT variables in the input files of the nodes
Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.
Example:
... |
def make_filter(self, fieldname, query_func, expct_value):
''' makes a filter that will be appliead to an object's property based
on query_func '''
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
... | def function[make_filter, parameter[self, fieldname, query_func, expct_value]]:
constant[ makes a filter that will be appliead to an object's property based
on query_func ]
def function[actual_filter, parameter[item]]:
variable[value] assign[=] call[name[getattr], parameter[name[... | keyword[def] identifier[make_filter] ( identifier[self] , identifier[fieldname] , identifier[query_func] , identifier[expct_value] ):
literal[string]
keyword[def] identifier[actual_filter] ( identifier[item] ):
identifier[value] = identifier[getattr] ( identifier[item] , identifier[f... | def make_filter(self, fieldname, query_func, expct_value):
""" makes a filter that will be appliead to an object's property based
on query_func """
def actual_filter(item):
value = getattr(item, fieldname)
if query_func in NULL_AFFECTED_FILTERS and value is None:
return Fals... |
def has_parent_vaults(self, vault_id):
"""Tests if the ``Vault`` has any parents.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (boolean) - ``true`` if the vault has parents, ``false``
otherwise
raise: NotFound - ``vault_id`` is not found
raise: NullArg... | def function[has_parent_vaults, parameter[self, vault_id]]:
constant[Tests if the ``Vault`` has any parents.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (boolean) - ``true`` if the vault has parents, ``false``
otherwise
raise: NotFound - ``vault_id`` is not fo... | keyword[def] identifier[has_parent_vaults] ( identifier[self] , identifier[vault_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_catalog_ses... | def has_parent_vaults(self, vault_id):
"""Tests if the ``Vault`` has any parents.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (boolean) - ``true`` if the vault has parents, ``false``
otherwise
raise: NotFound - ``vault_id`` is not found
raise: NullArgumen... |
def date_in_range(date1, date2, range):
"""Check if two date objects are within a specific range"""
date_obj1 = convert_date(date1)
date_obj2 = convert_date(date2)
return (date_obj2 - date_obj1).days <= range | def function[date_in_range, parameter[date1, date2, range]]:
constant[Check if two date objects are within a specific range]
variable[date_obj1] assign[=] call[name[convert_date], parameter[name[date1]]]
variable[date_obj2] assign[=] call[name[convert_date], parameter[name[date2]]]
return[co... | keyword[def] identifier[date_in_range] ( identifier[date1] , identifier[date2] , identifier[range] ):
literal[string]
identifier[date_obj1] = identifier[convert_date] ( identifier[date1] )
identifier[date_obj2] = identifier[convert_date] ( identifier[date2] )
keyword[return] ( identifier[date_obj... | def date_in_range(date1, date2, range):
"""Check if two date objects are within a specific range"""
date_obj1 = convert_date(date1)
date_obj2 = convert_date(date2)
return (date_obj2 - date_obj1).days <= range |
def rollback(self, project_id, transaction):
"""Perform a ``rollback`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction: bytes
:param transaction: Th... | def function[rollback, parameter[self, project_id, transaction]]:
constant[Perform a ``rollback`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction: bytes
... | keyword[def] identifier[rollback] ( identifier[self] , identifier[project_id] , identifier[transaction] ):
literal[string]
identifier[request_pb] = identifier[_datastore_pb2] . identifier[RollbackRequest] (
identifier[project_id] = identifier[project_id] , identifier[transaction] = identif... | def rollback(self, project_id, transaction):
"""Perform a ``rollback`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type transaction: bytes
:param transaction: The tr... |
def add_done_callback(self, fn):
"""Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
will always be called ... | def function[add_done_callback, parameter[self, fn]]:
constant[Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
... | keyword[def] identifier[add_done_callback] ( identifier[self] , identifier[fn] ):
literal[string]
keyword[with] identifier[self] . identifier[_condition] :
keyword[if] identifier[self] . identifier[_state] keyword[not] keyword[in] [ identifier[CANCELLED] , identifier[CANCELLED_AND_... | def add_done_callback(self, fn):
"""Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
will always be called by a... |
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
fapp = paste.fileapp.FileApp(path)
return fapp(request.environ, self.start_response) | def function[_serve_file, parameter[self, path]]:
constant[Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
]
variable[fapp] assign[=] call[name[paste].fileapp.FileApp, parameter[name[path]]]
return[call[name[fapp], parameter[name[request].environ, na... | keyword[def] identifier[_serve_file] ( identifier[self] , identifier[path] ):
literal[string]
identifier[fapp] = identifier[paste] . identifier[fileapp] . identifier[FileApp] ( identifier[path] )
keyword[return] identifier[fapp] ( identifier[request] . identifier[environ] , identifier[... | def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
fapp = paste.fileapp.FileApp(path)
return fapp(request.environ, self.start_response) |
def fetch_binary(self, fetch_request):
"""Fulfill a binary fetch request."""
bootstrap_dir = os.path.realpath(os.path.expanduser(self._bootstrap_dir))
bootstrapped_binary_path = os.path.join(bootstrap_dir, fetch_request.download_path)
logger.debug("bootstrapped_binary_path: {}".format(bootstrapped_binar... | def function[fetch_binary, parameter[self, fetch_request]]:
constant[Fulfill a binary fetch request.]
variable[bootstrap_dir] assign[=] call[name[os].path.realpath, parameter[call[name[os].path.expanduser, parameter[name[self]._bootstrap_dir]]]]
variable[bootstrapped_binary_path] assign[=] call[... | keyword[def] identifier[fetch_binary] ( identifier[self] , identifier[fetch_request] ):
literal[string]
identifier[bootstrap_dir] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[self] . identifier[_bootstrap_dir] ))
i... | def fetch_binary(self, fetch_request):
"""Fulfill a binary fetch request."""
bootstrap_dir = os.path.realpath(os.path.expanduser(self._bootstrap_dir))
bootstrapped_binary_path = os.path.join(bootstrap_dir, fetch_request.download_path)
logger.debug('bootstrapped_binary_path: {}'.format(bootstrapped_binar... |
def hist(self):
"""Draw normed histogram of the data using :attr:`bins`
.. plot::
>>> from scipy import stats
>>> data = stats.gamma.rvs(2, loc=1.5, scale=2, size=20000)
>>> # We then create the Fitter object
>>> import fitter
>>> fitter.Fitt... | def function[hist, parameter[self]]:
constant[Draw normed histogram of the data using :attr:`bins`
.. plot::
>>> from scipy import stats
>>> data = stats.gamma.rvs(2, loc=1.5, scale=2, size=20000)
>>> # We then create the Fitter object
>>> import fitter
... | keyword[def] identifier[hist] ( identifier[self] ):
literal[string]
identifier[_] = identifier[pylab] . identifier[hist] ( identifier[self] . identifier[_data] , identifier[bins] = identifier[self] . identifier[bins] , identifier[density] = keyword[True] )
identifier[pylab] . identifier[gr... | def hist(self):
"""Draw normed histogram of the data using :attr:`bins`
.. plot::
>>> from scipy import stats
>>> data = stats.gamma.rvs(2, loc=1.5, scale=2, size=20000)
>>> # We then create the Fitter object
>>> import fitter
>>> fitter.Fitter(d... |
def from_path(path: str, encoding: str = 'utf-8', **kwargs) -> BELGraph:
"""Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`.
:param path: A file path
:param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the pytho... | def function[from_path, parameter[path, encoding]]:
constant[Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`.
:param path: A file path
:param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the python
`doc... | keyword[def] identifier[from_path] ( identifier[path] : identifier[str] , identifier[encoding] : identifier[str] = literal[string] ,** identifier[kwargs] )-> identifier[BELGraph] :
literal[string]
identifier[log] . identifier[info] ( literal[string] , identifier[path] )
identifier[graph] = identifier[... | def from_path(path: str, encoding: str='utf-8', **kwargs) -> BELGraph:
"""Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`.
:param path: A file path
:param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the python
... |
def fetch_push_logs():
"""
Run several fetch_hg_push_log subtasks, one per repository
"""
for repo in Repository.objects.filter(dvcs_type='hg',
active_status="active"):
fetch_hg_push_log.apply_async(
args=(repo.name, repo.url),
qu... | def function[fetch_push_logs, parameter[]]:
constant[
Run several fetch_hg_push_log subtasks, one per repository
]
for taget[name[repo]] in starred[call[name[Repository].objects.filter, parameter[]]] begin[:]
call[name[fetch_hg_push_log].apply_async, parameter[]] | keyword[def] identifier[fetch_push_logs] ():
literal[string]
keyword[for] identifier[repo] keyword[in] identifier[Repository] . identifier[objects] . identifier[filter] ( identifier[dvcs_type] = literal[string] ,
identifier[active_status] = literal[string] ):
identifier[fetch_hg_push_log] ... | def fetch_push_logs():
"""
Run several fetch_hg_push_log subtasks, one per repository
"""
for repo in Repository.objects.filter(dvcs_type='hg', active_status='active'):
fetch_hg_push_log.apply_async(args=(repo.name, repo.url), queue='pushlog') # depends on [control=['for'], data=['repo']] |
def updateratio(ctx, symbol, ratio, account):
""" Update the collateral ratio of a call positions
"""
from bitshares.dex import Dex
dex = Dex(bitshares_instance=ctx.bitshares)
print_tx(dex.adjust_collateral_ratio(symbol, ratio, account=account)) | def function[updateratio, parameter[ctx, symbol, ratio, account]]:
constant[ Update the collateral ratio of a call positions
]
from relative_module[bitshares.dex] import module[Dex]
variable[dex] assign[=] call[name[Dex], parameter[]]
call[name[print_tx], parameter[call[name[dex].adjust_... | keyword[def] identifier[updateratio] ( identifier[ctx] , identifier[symbol] , identifier[ratio] , identifier[account] ):
literal[string]
keyword[from] identifier[bitshares] . identifier[dex] keyword[import] identifier[Dex]
identifier[dex] = identifier[Dex] ( identifier[bitshares_instance] = ident... | def updateratio(ctx, symbol, ratio, account):
""" Update the collateral ratio of a call positions
"""
from bitshares.dex import Dex
dex = Dex(bitshares_instance=ctx.bitshares)
print_tx(dex.adjust_collateral_ratio(symbol, ratio, account=account)) |
def save_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_data = self.maybe_patch_segment_data(f, segment.data)
f.write(struct.pack('<II', segment.addr, len(segment_data)))
f.write(segment_data)
... | def function[save_segment, parameter[self, f, segment, checksum]]:
constant[ Save the next segment to the image file, return next checksum value if provided ]
variable[segment_data] assign[=] call[name[self].maybe_patch_segment_data, parameter[name[f], name[segment].data]]
call[name[f].write, pa... | keyword[def] identifier[save_segment] ( identifier[self] , identifier[f] , identifier[segment] , identifier[checksum] = keyword[None] ):
literal[string]
identifier[segment_data] = identifier[self] . identifier[maybe_patch_segment_data] ( identifier[f] , identifier[segment] . identifier[data] )
... | def save_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_data = self.maybe_patch_segment_data(f, segment.data)
f.write(struct.pack('<II', segment.addr, len(segment_data)))
f.write(segment_data)
if checksum is n... |
def _parse_kexgss_hostkey(self, m):
"""
Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode).
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message
"""
# client mode
host_key = m.get_string()
self.transport.host_key = host_key
sig = m... | def function[_parse_kexgss_hostkey, parameter[self, m]]:
constant[
Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode).
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message
]
variable[host_key] assign[=] call[name[m].get_string, parameter[]]
name[s... | keyword[def] identifier[_parse_kexgss_hostkey] ( identifier[self] , identifier[m] ):
literal[string]
identifier[host_key] = identifier[m] . identifier[get_string] ()
identifier[self] . identifier[transport] . identifier[host_key] = identifier[host_key]
identifier[sig] = ... | def _parse_kexgss_hostkey(self, m):
"""
Parse the SSH2_MSG_KEXGSS_HOSTKEY message (client mode).
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_HOSTKEY message
"""
# client mode
host_key = m.get_string()
self.transport.host_key = host_key
sig = m.get_string()
se... |
def rsdl(self):
"""Compute fixed point residual in Fourier domain."""
diff = self.Xf - self.Yfprv
return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN) | def function[rsdl, parameter[self]]:
constant[Compute fixed point residual in Fourier domain.]
variable[diff] assign[=] binary_operation[name[self].Xf - name[self].Yfprv]
return[call[name[sl].rfl2norm2, parameter[name[diff], name[self].X.shape]]] | keyword[def] identifier[rsdl] ( identifier[self] ):
literal[string]
identifier[diff] = identifier[self] . identifier[Xf] - identifier[self] . identifier[Yfprv]
keyword[return] identifier[sl] . identifier[rfl2norm2] ( identifier[diff] , identifier[self] . identifier[X] . identifier[shape... | def rsdl(self):
"""Compute fixed point residual in Fourier domain."""
diff = self.Xf - self.Yfprv
return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN) |
def attach_par_subdivision(par_name, par_times):
"""
Manual assignment of a collection of (stopped) Times objects as a parallel
subdivision of a running timer.
Notes:
An example sequence of proper usage:
1. Stamp in master process.
2. Run timed sub-processes.
... | def function[attach_par_subdivision, parameter[par_name, par_times]]:
constant[
Manual assignment of a collection of (stopped) Times objects as a parallel
subdivision of a running timer.
Notes:
An example sequence of proper usage:
1. Stamp in master process.
2. Run ... | keyword[def] identifier[attach_par_subdivision] ( identifier[par_name] , identifier[par_times] ):
literal[string]
identifier[t] = identifier[timer] ()
keyword[if] keyword[not] identifier[isinstance] ( identifier[par_times] ,( identifier[list] , identifier[tuple] )):
keyword[raise] identifi... | def attach_par_subdivision(par_name, par_times):
"""
Manual assignment of a collection of (stopped) Times objects as a parallel
subdivision of a running timer.
Notes:
An example sequence of proper usage:
1. Stamp in master process.
2. Run timed sub-processes.
... |
def should_include_node(ctx, directives):
# type: (ExecutionContext, Optional[List[Directive]]) -> bool
"""Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include."""
# TODO: Refactor based on latest code
if directives:
... | def function[should_include_node, parameter[ctx, directives]]:
constant[Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include.]
if name[directives] begin[:]
variable[skip_ast] assign[=] constant[None]
... | keyword[def] identifier[should_include_node] ( identifier[ctx] , identifier[directives] ):
literal[string]
keyword[if] identifier[directives] :
identifier[skip_ast] = keyword[None]
keyword[for] identifier[directive] keyword[in] identifier[directives] :
keyword[if]... | def should_include_node(ctx, directives):
# type: (ExecutionContext, Optional[List[Directive]]) -> bool
'Determines if a field should be included based on the @include and\n @skip directives, where @skip has higher precidence than @include.'
# TODO: Refactor based on latest code
if directives:
... |
def graphiter(self, graph, target, ascendants=0, descendants=1):
""" Iter on a graph to finds object connected
:param graph: Graph to serialize
:type graph: Graph
:param target: Node to iterate over
:type target: Node
:param ascendants: Number of level to iter over upwar... | def function[graphiter, parameter[self, graph, target, ascendants, descendants]]:
constant[ Iter on a graph to finds object connected
:param graph: Graph to serialize
:type graph: Graph
:param target: Node to iterate over
:type target: Node
:param ascendants: Number of l... | keyword[def] identifier[graphiter] ( identifier[self] , identifier[graph] , identifier[target] , identifier[ascendants] = literal[int] , identifier[descendants] = literal[int] ):
literal[string]
identifier[asc] = literal[int] + identifier[ascendants]
keyword[if] identifier[asc] != liter... | def graphiter(self, graph, target, ascendants=0, descendants=1):
""" Iter on a graph to finds object connected
:param graph: Graph to serialize
:type graph: Graph
:param target: Node to iterate over
:type target: Node
:param ascendants: Number of level to iter over upwards (... |
def process_minter(value):
"""Load minter from PIDStore registry based on given value.
:param value: Name of the minter.
:returns: The minter.
"""
try:
return current_pidstore.minters[value]
except KeyError:
raise click.BadParameter(
'Unknown minter {0}. Please use o... | def function[process_minter, parameter[value]]:
constant[Load minter from PIDStore registry based on given value.
:param value: Name of the minter.
:returns: The minter.
]
<ast.Try object at 0x7da1afe1a4a0> | keyword[def] identifier[process_minter] ( identifier[value] ):
literal[string]
keyword[try] :
keyword[return] identifier[current_pidstore] . identifier[minters] [ identifier[value] ]
keyword[except] identifier[KeyError] :
keyword[raise] identifier[click] . identifier[BadParameter]... | def process_minter(value):
"""Load minter from PIDStore registry based on given value.
:param value: Name of the minter.
:returns: The minter.
"""
try:
return current_pidstore.minters[value] # depends on [control=['try'], data=[]]
except KeyError:
raise click.BadParameter('Unkn... |
def _init_w_transforms(data, features):
"""Initialize the mappings (Wi) for the SRM with random orthogonal matrices.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
features : int
... | def function[_init_w_transforms, parameter[data, features]]:
constant[Initialize the mappings (Wi) for the SRM with random orthogonal matrices.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one sub... | keyword[def] identifier[_init_w_transforms] ( identifier[data] , identifier[features] ):
literal[string]
identifier[w] =[]
identifier[subjects] = identifier[len] ( identifier[data] )
identifier[voxels] = identifier[np] . identifier[empty] ( identifier[subjects] , identifier[dtype] = identifier[in... | def _init_w_transforms(data, features):
"""Initialize the mappings (Wi) for the SRM with random orthogonal matrices.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
features : int
... |
def p_expression_uxor(self, p):
'expression : XOR expression %prec UXOR'
p[0] = Uxor(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | def function[p_expression_uxor, parameter[self, p]]:
constant[expression : XOR expression %prec UXOR]
call[name[p]][constant[0]] assign[=] call[name[Uxor], parameter[call[name[p]][constant[2]]]]
call[name[p].set_lineno, parameter[constant[0], call[name[p].lineno, parameter[constant[1]]]]] | keyword[def] identifier[p_expression_uxor] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[Uxor] ( identifier[p] [ literal[int] ], identifier[lineno] = identifier[p] . identifier[lineno] ( literal[int] ))
identifier[p] . identifier[set_linen... | def p_expression_uxor(self, p):
"""expression : XOR expression %prec UXOR"""
p[0] = Uxor(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def get_path(self, dir=None):
"""Return path relative to the current working directory of the
Node.FS.Base object that owns us."""
if not dir:
dir = self.fs.getcwd()
if self == dir:
return '.'
path_elems = self.get_path_elements()
pathname = ''
... | def function[get_path, parameter[self, dir]]:
constant[Return path relative to the current working directory of the
Node.FS.Base object that owns us.]
if <ast.UnaryOp object at 0x7da20c6c79a0> begin[:]
variable[dir] assign[=] call[name[self].fs.getcwd, parameter[]]
if com... | keyword[def] identifier[get_path] ( identifier[self] , identifier[dir] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[dir] :
identifier[dir] = identifier[self] . identifier[fs] . identifier[getcwd] ()
keyword[if] identifier[self] == identifier[dir] :... | def get_path(self, dir=None):
"""Return path relative to the current working directory of the
Node.FS.Base object that owns us."""
if not dir:
dir = self.fs.getcwd() # depends on [control=['if'], data=[]]
if self == dir:
return '.' # depends on [control=['if'], data=[]]
path_el... |
def get_edxml(self):
"""stub"""
if self.has_raw_edxml():
has_python = False
my_files = self.my_osid_object.object_map['fileIds']
raw_text = self.get_text('edxml').text
soup = BeautifulSoup(raw_text, 'xml')
# replace all file listings with an ap... | def function[get_edxml, parameter[self]]:
constant[stub]
if call[name[self].has_raw_edxml, parameter[]] begin[:]
variable[has_python] assign[=] constant[False]
variable[my_files] assign[=] call[name[self].my_osid_object.object_map][constant[fileIds]]
varia... | keyword[def] identifier[get_edxml] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[has_raw_edxml] ():
identifier[has_python] = keyword[False]
identifier[my_files] = identifier[self] . identifier[my_osid_object] . identifier[object_map] [ l... | def get_edxml(self):
"""stub"""
if self.has_raw_edxml():
has_python = False
my_files = self.my_osid_object.object_map['fileIds']
raw_text = self.get_text('edxml').text
soup = BeautifulSoup(raw_text, 'xml')
# replace all file listings with an appropriate path...
at... |
def get_kubernetes_configuration(self, mount_point='kubernetes'):
"""GET /auth/<mount_point>/config
:param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes".
:type mount_point: str.
:return: Parsed JSON response from the config GET req... | def function[get_kubernetes_configuration, parameter[self, mount_point]]:
constant[GET /auth/<mount_point>/config
:param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes".
:type mount_point: str.
:return: Parsed JSON response from the ... | keyword[def] identifier[get_kubernetes_configuration] ( identifier[self] , identifier[mount_point] = literal[string] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[mount_point] )
keyword[return] identifier[self] . identifier[_adapter] . identifier[... | def get_kubernetes_configuration(self, mount_point='kubernetes'):
"""GET /auth/<mount_point>/config
:param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes".
:type mount_point: str.
:return: Parsed JSON response from the config GET request... |
def load_acknowledge_config(self, file_id):
"""
Loads the CWR acknowledge config
:return: the values matrix
"""
if self._cwr_defaults is None:
self._cwr_defaults = self._reader.read_yaml_file(
'acknowledge_config_%s.yml' % file_id)
return self... | def function[load_acknowledge_config, parameter[self, file_id]]:
constant[
Loads the CWR acknowledge config
:return: the values matrix
]
if compare[name[self]._cwr_defaults is constant[None]] begin[:]
name[self]._cwr_defaults assign[=] call[name[self]._reader.read... | keyword[def] identifier[load_acknowledge_config] ( identifier[self] , identifier[file_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_cwr_defaults] keyword[is] keyword[None] :
identifier[self] . identifier[_cwr_defaults] = identifier[self] . identifier[_reader] . i... | def load_acknowledge_config(self, file_id):
"""
Loads the CWR acknowledge config
:return: the values matrix
"""
if self._cwr_defaults is None:
self._cwr_defaults = self._reader.read_yaml_file('acknowledge_config_%s.yml' % file_id) # depends on [control=['if'], data=[]]
retur... |
def load(self, profile_args):
"""Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format.
"""
for key, value in profile_args.items():
self.add(key, value) | def function[load, parameter[self, profile_args]]:
constant[Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format.
]
for taget[tuple[[<ast.Name object at 0x7da2041d9900>, <ast.Name object at 0x7da2041d89d0>]]] in starred[call[name[profile_args].it... | keyword[def] identifier[load] ( identifier[self] , identifier[profile_args] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[profile_args] . identifier[items] ():
identifier[self] . identifier[add] ( identifier[key] , identifier[value] ) | def load(self, profile_args):
"""Load provided CLI Args.
Args:
args (dict): Dictionary of args in key/value format.
"""
for (key, value) in profile_args.items():
self.add(key, value) # depends on [control=['for'], data=[]] |
def em_rates_from_E_DA_mix(em_rates_tot, E_values):
"""D and A emission rates for two populations.
"""
em_rates_d, em_rates_a = [], []
for em_rate_tot, E_value in zip(em_rates_tot, E_values):
em_rate_di, em_rate_ai = em_rates_from_E_DA(em_rate_tot, E_value)
em_rates_d.append(em_rate_di)
... | def function[em_rates_from_E_DA_mix, parameter[em_rates_tot, E_values]]:
constant[D and A emission rates for two populations.
]
<ast.Tuple object at 0x7da204347340> assign[=] tuple[[<ast.List object at 0x7da204347f40>, <ast.List object at 0x7da2043457b0>]]
for taget[tuple[[<ast.Name object a... | keyword[def] identifier[em_rates_from_E_DA_mix] ( identifier[em_rates_tot] , identifier[E_values] ):
literal[string]
identifier[em_rates_d] , identifier[em_rates_a] =[],[]
keyword[for] identifier[em_rate_tot] , identifier[E_value] keyword[in] identifier[zip] ( identifier[em_rates_tot] , identifier[... | def em_rates_from_E_DA_mix(em_rates_tot, E_values):
"""D and A emission rates for two populations.
"""
(em_rates_d, em_rates_a) = ([], [])
for (em_rate_tot, E_value) in zip(em_rates_tot, E_values):
(em_rate_di, em_rate_ai) = em_rates_from_E_DA(em_rate_tot, E_value)
em_rates_d.append(em_r... |
def scan_mem(self, data_to_find):
"""
Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.
:param bytes data_to_find: String to locate
:return:
"""
# TODO: for the moment we just treat symbolic bytes as bytes that don't match.
... | def function[scan_mem, parameter[self, data_to_find]]:
constant[
Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.
:param bytes data_to_find: String to locate
:return:
]
if call[name[isinstance], parameter[name[data_to_find], name... | keyword[def] identifier[scan_mem] ( identifier[self] , identifier[data_to_find] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data_to_find] , identifier[bytes] ):
identifier[data_to_find] =[ identifier[bytes]... | def scan_mem(self, data_to_find):
"""
Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.
:param bytes data_to_find: String to locate
:return:
"""
# TODO: for the moment we just treat symbolic bytes as bytes that don't match.
# for our ... |
def _try_parse_datetime(time_str, fmts):
'''
A helper function that attempts to parse the input time_str as a date.
Args:
time_str (str): A string representing the time
fmts (list): A list of date format strings
Returns:
datetime: Returns a datetime object if parsed properly,... | def function[_try_parse_datetime, parameter[time_str, fmts]]:
constant[
A helper function that attempts to parse the input time_str as a date.
Args:
time_str (str): A string representing the time
fmts (list): A list of date format strings
Returns:
datetime: Returns a date... | keyword[def] identifier[_try_parse_datetime] ( identifier[time_str] , identifier[fmts] ):
literal[string]
identifier[result] = keyword[None]
keyword[for] identifier[fmt] keyword[in] identifier[fmts] :
keyword[try] :
identifier[result] = identifier[datetime] . identifier[strpt... | def _try_parse_datetime(time_str, fmts):
"""
A helper function that attempts to parse the input time_str as a date.
Args:
time_str (str): A string representing the time
fmts (list): A list of date format strings
Returns:
datetime: Returns a datetime object if parsed properly,... |
def save_image(xdata: DataAndMetadata.DataAndMetadata, file):
"""
Saves the nparray data to the file-like object (or string) file.
"""
# we need to create a basic DM tree suitable for an image
# we'll try the minimum: just an data list
# doesn't work. Do we need a ImageSourceList too?
# and ... | def function[save_image, parameter[xdata, file]]:
constant[
Saves the nparray data to the file-like object (or string) file.
]
variable[data] assign[=] name[xdata].data
variable[data_descriptor] assign[=] name[xdata].data_descriptor
variable[dimensional_calibrations] assign[=] na... | keyword[def] identifier[save_image] ( identifier[xdata] : identifier[DataAndMetadata] . identifier[DataAndMetadata] , identifier[file] ):
literal[string]
identifier[data] = identifier[xdata] . identifier[data]
identifier[data_descriptor] = identifier[xdata] . identifier[data_desc... | def save_image(xdata: DataAndMetadata.DataAndMetadata, file):
"""
Saves the nparray data to the file-like object (or string) file.
"""
# we need to create a basic DM tree suitable for an image
# we'll try the minimum: just an data list
# doesn't work. Do we need a ImageSourceList too?
# and ... |
def Interpolate(time, mask, y):
'''
Masks certain elements in the array `y` and linearly
interpolates over them, returning an array `y'` of the
same length.
:param array_like time: The time array
:param array_like mask: The indices to be interpolated over
:param array_like y: The dependent ... | def function[Interpolate, parameter[time, mask, y]]:
constant[
Masks certain elements in the array `y` and linearly
interpolates over them, returning an array `y'` of the
same length.
:param array_like time: The time array
:param array_like mask: The indices to be interpolated over
:par... | keyword[def] identifier[Interpolate] ( identifier[time] , identifier[mask] , identifier[y] ):
literal[string]
identifier[yy] = identifier[np] . identifier[array] ( identifier[y] )
identifier[t_] = identifier[np] . identifier[delete] ( identifier[time] , identifier[mask] )
identifier[y_] = i... | def Interpolate(time, mask, y):
"""
Masks certain elements in the array `y` and linearly
interpolates over them, returning an array `y'` of the
same length.
:param array_like time: The time array
:param array_like mask: The indices to be interpolated over
:param array_like y: The dependent ... |
def corruptDenseVector(vector, noiseLevel):
"""
Corrupts a binary vector by inverting noiseLevel percent of its bits.
@param vector (array) binary vector to be corrupted
@param noiseLevel (float) amount of noise to be applied on the vector.
"""
size = len(vector)
for i in range(size):
rnd = rando... | def function[corruptDenseVector, parameter[vector, noiseLevel]]:
constant[
Corrupts a binary vector by inverting noiseLevel percent of its bits.
@param vector (array) binary vector to be corrupted
@param noiseLevel (float) amount of noise to be applied on the vector.
]
variable[size] assign... | keyword[def] identifier[corruptDenseVector] ( identifier[vector] , identifier[noiseLevel] ):
literal[string]
identifier[size] = identifier[len] ( identifier[vector] )
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[size] ):
identifier[rnd] = identifier[random] . identifier[rand... | def corruptDenseVector(vector, noiseLevel):
"""
Corrupts a binary vector by inverting noiseLevel percent of its bits.
@param vector (array) binary vector to be corrupted
@param noiseLevel (float) amount of noise to be applied on the vector.
"""
size = len(vector)
for i in range(size):
r... |
def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise... | def function[is_image_format, parameter[self]]:
constant[ Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image ... | keyword[def] identifier[is_image_format] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] keyword[in] identifier[frozenset] ([ identifier[MimeType] . identifier[TIFF] , identifier[MimeType] . identifier[TIFF_d8] , identifier[MimeType] . identifier[TIFF_d16] , identifier[Mim... | def is_image_format(self):
""" Checks whether file format is an image format
Example: ``MimeType.PNG.is_image_format()`` or ``MimeType.is_image_format(MimeType.PNG)``
:param self: File format
:type self: MimeType
:return: ``True`` if file is in image format, ``False`` otherwise
... |
def set_alt(self, i, alt, break_alt=None, change_time=True):
'''set rally point altitude(s)'''
if i < 1 or i > self.rally_count():
print("Inavlid rally point number %u" % i)
return
self.rally_points[i-1].alt = int(alt)
if (break_alt != None):
self.rall... | def function[set_alt, parameter[self, i, alt, break_alt, change_time]]:
constant[set rally point altitude(s)]
if <ast.BoolOp object at 0x7da1b17de980> begin[:]
call[name[print], parameter[binary_operation[constant[Inavlid rally point number %u] <ast.Mod object at 0x7da2590d6920> name[i]]... | keyword[def] identifier[set_alt] ( identifier[self] , identifier[i] , identifier[alt] , identifier[break_alt] = keyword[None] , identifier[change_time] = keyword[True] ):
literal[string]
keyword[if] identifier[i] < literal[int] keyword[or] identifier[i] > identifier[self] . identifier[rally_coun... | def set_alt(self, i, alt, break_alt=None, change_time=True):
"""set rally point altitude(s)"""
if i < 1 or i > self.rally_count():
print('Inavlid rally point number %u' % i)
return # depends on [control=['if'], data=[]]
self.rally_points[i - 1].alt = int(alt)
if break_alt != None:
... |
def _wrap_key(function, args, kws):
'''
get the key from the function input.
'''
return hashlib.md5(pickle.dumps((_from_file(function) + function.__name__, args, kws))).hexdigest() | def function[_wrap_key, parameter[function, args, kws]]:
constant[
get the key from the function input.
]
return[call[call[name[hashlib].md5, parameter[call[name[pickle].dumps, parameter[tuple[[<ast.BinOp object at 0x7da1b0ff01f0>, <ast.Name object at 0x7da1b0ff0e20>, <ast.Name object at 0x7da1b0ff1a80>]]... | keyword[def] identifier[_wrap_key] ( identifier[function] , identifier[args] , identifier[kws] ):
literal[string]
keyword[return] identifier[hashlib] . identifier[md5] ( identifier[pickle] . identifier[dumps] (( identifier[_from_file] ( identifier[function] )+ identifier[function] . identifier[__name__] , ident... | def _wrap_key(function, args, kws):
"""
get the key from the function input.
"""
return hashlib.md5(pickle.dumps((_from_file(function) + function.__name__, args, kws))).hexdigest() |
def uncompress_file(inputfile, filename):
"""
Uncompress this file using gzip and change its name.
:param inputfile: File to compress
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with file and new file's name
:rtype: :class... | def function[uncompress_file, parameter[inputfile, filename]]:
constant[
Uncompress this file using gzip and change its name.
:param inputfile: File to compress
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with file and new... | keyword[def] identifier[uncompress_file] ( identifier[inputfile] , identifier[filename] ):
literal[string]
identifier[zipfile] = identifier[gzip] . identifier[GzipFile] ( identifier[fileobj] = identifier[inputfile] , identifier[mode] = literal[string] )
keyword[try] :
identifier[outputfile] =... | def uncompress_file(inputfile, filename):
"""
Uncompress this file using gzip and change its name.
:param inputfile: File to compress
:type inputfile: ``file`` like object
:param filename: File's name
:type filename: ``str``
:returns: Tuple with file and new file's name
:rtype: :class... |
def get_component_exceptions(cluster, environ, topology, component, role=None):
'''
Get exceptions for 'component' for 'topology'
:param cluster:
:param environ:
:param topology:
:param component:
:param role:
:return:
'''
params = dict(
cluster=cluster,
environ=environ,
topology=t... | def function[get_component_exceptions, parameter[cluster, environ, topology, component, role]]:
constant[
Get exceptions for 'component' for 'topology'
:param cluster:
:param environ:
:param topology:
:param component:
:param role:
:return:
]
variable[params] assign[=] call[name[dict], p... | keyword[def] identifier[get_component_exceptions] ( identifier[cluster] , identifier[environ] , identifier[topology] , identifier[component] , identifier[role] = keyword[None] ):
literal[string]
identifier[params] = identifier[dict] (
identifier[cluster] = identifier[cluster] ,
identifier[environ] = iden... | def get_component_exceptions(cluster, environ, topology, component, role=None):
"""
Get exceptions for 'component' for 'topology'
:param cluster:
:param environ:
:param topology:
:param component:
:param role:
:return:
"""
params = dict(cluster=cluster, environ=environ, topology=topology, compon... |
def parse_acl(acl_string):
""" Parse raw string :acl_string: of RAML-defined ACLs.
If :acl_string: is blank or None, all permissions are given.
Values of ACL action and principal are parsed using `actions` and
`special_principals` maps and are looked up after `strip()` and
`lower()`.
ACEs in :... | def function[parse_acl, parameter[acl_string]]:
constant[ Parse raw string :acl_string: of RAML-defined ACLs.
If :acl_string: is blank or None, all permissions are given.
Values of ACL action and principal are parsed using `actions` and
`special_principals` maps and are looked up after `strip()` an... | keyword[def] identifier[parse_acl] ( identifier[acl_string] ):
literal[string]
keyword[if] keyword[not] identifier[acl_string] :
keyword[return] [ identifier[ALLOW_ALL] ]
identifier[aces_list] = identifier[acl_string] . identifier[replace] ( literal[string] , literal[string] ). identifier[... | def parse_acl(acl_string):
""" Parse raw string :acl_string: of RAML-defined ACLs.
If :acl_string: is blank or None, all permissions are given.
Values of ACL action and principal are parsed using `actions` and
`special_principals` maps and are looked up after `strip()` and
`lower()`.
ACEs in :... |
def _ycbcr2rgb(self, mode):
"""Convert the image from YCbCr mode to RGB.
"""
self._check_modes(("YCbCr", "YCbCrA"))
(self.channels[0], self.channels[1], self.channels[2]) = \
ycbcr2rgb(self.channels[0],
self.channels[1],
self.chan... | def function[_ycbcr2rgb, parameter[self, mode]]:
constant[Convert the image from YCbCr mode to RGB.
]
call[name[self]._check_modes, parameter[tuple[[<ast.Constant object at 0x7da1b0528f10>, <ast.Constant object at 0x7da1b0529000>]]]]
<ast.Tuple object at 0x7da1b0528fd0> assign[=] call[na... | keyword[def] identifier[_ycbcr2rgb] ( identifier[self] , identifier[mode] ):
literal[string]
identifier[self] . identifier[_check_modes] (( literal[string] , literal[string] ))
( identifier[self] . identifier[channels] [ literal[int] ], identifier[self] . identifier[channels] [ literal[in... | def _ycbcr2rgb(self, mode):
"""Convert the image from YCbCr mode to RGB.
"""
self._check_modes(('YCbCr', 'YCbCrA'))
(self.channels[0], self.channels[1], self.channels[2]) = ycbcr2rgb(self.channels[0], self.channels[1], self.channels[2])
if self.fill_value is not None:
self.fill_value[0:3... |
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule... | def function[_get_rule_changes, parameter[rules, _rules]]:
constant[
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
]
variable[to_delete] assign[=] list[[]]
variable[to_create] assign[=] list[[]... | keyword[def] identifier[_get_rule_changes] ( identifier[rules] , identifier[_rules] ):
literal[string]
identifier[to_delete] =[]
identifier[to_create] =[]
keyword[for] identifier[rule] keyword[in] identifier[rules] :
keyword[try] :
identifier[ip_protocol] =... | def _get_rule_changes(rules, _rules):
"""
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
"""
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule... |
def missing_host_key(self, client, hostname, key):
"""
Called when an `.SSHClient` receives a server key for a server that
isn't in either the system or local `.HostKeys` object. To accept
the key, simply return. To reject, raised an exception (which will
be passed to the calli... | def function[missing_host_key, parameter[self, client, hostname, key]]:
constant[
Called when an `.SSHClient` receives a server key for a server that
isn't in either the system or local `.HostKeys` object. To accept
the key, simply return. To reject, raised an exception (which will
... | keyword[def] identifier[missing_host_key] ( identifier[self] , identifier[client] , identifier[hostname] , identifier[key] ):
literal[string]
identifier[self] . identifier[host_key] = identifier[key] . identifier[get_base64] ()
identifier[print] ( literal[string] % identifier[self] . ident... | def missing_host_key(self, client, hostname, key):
"""
Called when an `.SSHClient` receives a server key for a server that
isn't in either the system or local `.HostKeys` object. To accept
the key, simply return. To reject, raised an exception (which will
be passed to the calling a... |
def _general_error_handler(http_error):
''' Simple error handler for azure.'''
message = str(http_error)
if http_error.respbody is not None:
message += '\n' + http_error.respbody.decode('utf-8-sig')
raise AzureHttpError(message, http_error.status) | def function[_general_error_handler, parameter[http_error]]:
constant[ Simple error handler for azure.]
variable[message] assign[=] call[name[str], parameter[name[http_error]]]
if compare[name[http_error].respbody is_not constant[None]] begin[:]
<ast.AugAssign object at 0x7da1b23458a0>
... | keyword[def] identifier[_general_error_handler] ( identifier[http_error] ):
literal[string]
identifier[message] = identifier[str] ( identifier[http_error] )
keyword[if] identifier[http_error] . identifier[respbody] keyword[is] keyword[not] keyword[None] :
identifier[message] += literal[st... | def _general_error_handler(http_error):
""" Simple error handler for azure."""
message = str(http_error)
if http_error.respbody is not None:
message += '\n' + http_error.respbody.decode('utf-8-sig') # depends on [control=['if'], data=[]]
raise AzureHttpError(message, http_error.status) |
def interp_na(self, dim=None, use_coordinate=True, method='linear', limit=None,
**kwargs):
'''Interpolate values according to different methods.'''
if dim is None:
raise NotImplementedError('dim is a required argument')
if limit is not None:
valids = _get_valid_fill_mask(self... | def function[interp_na, parameter[self, dim, use_coordinate, method, limit]]:
constant[Interpolate values according to different methods.]
if compare[name[dim] is constant[None]] begin[:]
<ast.Raise object at 0x7da207f01b40>
if compare[name[limit] is_not constant[None]] begin[:]
... | keyword[def] identifier[interp_na] ( identifier[self] , identifier[dim] = keyword[None] , identifier[use_coordinate] = keyword[True] , identifier[method] = literal[string] , identifier[limit] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
keyword[if] identifier[dim] keyword[is] keyword[None... | def interp_na(self, dim=None, use_coordinate=True, method='linear', limit=None, **kwargs):
"""Interpolate values according to different methods."""
if dim is None:
raise NotImplementedError('dim is a required argument') # depends on [control=['if'], data=[]]
if limit is not None:
valids = _... |
def assoc(inst, **changes):
"""
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name*... | def function[assoc, parameter[inst]]:
constant[
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundE... | keyword[def] identifier[assoc] ( identifier[inst] ,** identifier[changes] ):
literal[string]
keyword[import] identifier[warnings]
identifier[warnings] . identifier[warn] (
literal[string] ,
identifier[DeprecationWarning] ,
identifier[stacklevel] = literal[int] ,
)
identifier... | def assoc(inst, **changes):
"""
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name*... |
def inner_fork_insanity_checks(pipeline_string):
"""
This function performs two sanity checks in the pipeline string. The first
check, assures that each fork contains a lane token '|', while the second
check looks for duplicated processes within the same fork.
Parameters
----------
pipeline... | def function[inner_fork_insanity_checks, parameter[pipeline_string]]:
constant[
This function performs two sanity checks in the pipeline string. The first
check, assures that each fork contains a lane token '|', while the second
check looks for duplicated processes within the same fork.
Paramet... | keyword[def] identifier[inner_fork_insanity_checks] ( identifier[pipeline_string] ):
literal[string]
identifier[list_of_forks] =[]
identifier[left_indexes] =[]
keyword[for] identifier[pos] , identifier[char] keyword[in] identifier[enumerate] ( identifier[pipeline_string] ):
... | def inner_fork_insanity_checks(pipeline_string):
"""
This function performs two sanity checks in the pipeline string. The first
check, assures that each fork contains a lane token '|', while the second
check looks for duplicated processes within the same fork.
Parameters
----------
pipeline... |
def parse_bool(cls, value, default=None):
"""Convert ``string`` or ``bool`` to ``bool``."""
if value is None:
return default
elif isinstance(value, bool):
return value
elif isinstance(value, str):
if value == 'True':
return True
... | def function[parse_bool, parameter[cls, value, default]]:
constant[Convert ``string`` or ``bool`` to ``bool``.]
if compare[name[value] is constant[None]] begin[:]
return[name[default]]
<ast.Raise object at 0x7da18f00e290> | keyword[def] identifier[parse_bool] ( identifier[cls] , identifier[value] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return] identifier[default]
keyword[elif] identifier[isinstance] ( identi... | def parse_bool(cls, value, default=None):
"""Convert ``string`` or ``bool`` to ``bool``."""
if value is None:
return default # depends on [control=['if'], data=[]]
elif isinstance(value, bool):
return value # depends on [control=['if'], data=[]]
elif isinstance(value, str):
if ... |
def press(self, key_code):
""" Sends a 'down' event for the specified scan code """
if key_code >= 128:
# Media key
ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
14, # type
(0, 0), # loc... | def function[press, parameter[self, key_code]]:
constant[ Sends a 'down' event for the specified scan code ]
if compare[name[key_code] greater_or_equal[>=] constant[128]] begin[:]
variable[ev] assign[=] call[name[NSEvent].otherEventWithType_location_modifierFlags_timestamp_windowNumber_c... | keyword[def] identifier[press] ( identifier[self] , identifier[key_code] ):
literal[string]
keyword[if] identifier[key_code] >= literal[int] :
identifier[ev] = identifier[NSEvent] . identifier[otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_da... | def press(self, key_code):
""" Sends a 'down' event for the specified scan code """
if key_code >= 128:
# Media key
# type
# location
# flags
# timestamp
# window
# ctx
# subtype
# data1
# data2
ev = NSEvent.otherEventWithTy... |
def read_tsplib(filename):
"basic function for reading a symmetric problem in the TSPLIB format"
"data is stored in an upper triangular matrix"
"NOTE: some distance types are not handled yet"
if filename[-3:] == ".gz":
f = gzip.open(filename, "rt")
else:
f = open(filename)
line ... | def function[read_tsplib, parameter[filename]]:
constant[basic function for reading a symmetric problem in the TSPLIB format]
constant[data is stored in an upper triangular matrix]
constant[NOTE: some distance types are not handled yet]
if compare[call[name[filename]][<ast.Slice object a... | keyword[def] identifier[read_tsplib] ( identifier[filename] ):
literal[string]
literal[string]
literal[string]
keyword[if] identifier[filename] [- literal[int] :]== literal[string] :
identifier[f] = identifier[gzip] . identifier[open] ( identifier[filename] , literal[string] )
ke... | def read_tsplib(filename):
"""basic function for reading a symmetric problem in the TSPLIB format"""
'data is stored in an upper triangular matrix'
'NOTE: some distance types are not handled yet'
if filename[-3:] == '.gz':
f = gzip.open(filename, 'rt') # depends on [control=['if'], data=[]]
... |
def text(self, tag, textdata, step=None):
"""Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
"""
if step is None:
step = self._step... | def function[text, parameter[self, tag, textdata, step]]:
constant[Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
]
if compare[n... | keyword[def] identifier[text] ( identifier[self] , identifier[tag] , identifier[textdata] , identifier[step] = keyword[None] ):
literal[string]
keyword[if] identifier[step] keyword[is] keyword[None] :
identifier[step] = identifier[self] . identifier[_step]
keyword[else] :
identifier[... | def text(self, tag, textdata, step=None):
"""Saves a text summary.
Args:
tag: str: label for this data
textdata: string, or 1D/2D list/numpy array of strings
step: int: training step
Note: markdown formatting is rendered by tensorboard.
"""
if step is None:
step = self._st... |
def client_key_loader(self, f):
"""Registers a function to be called to find a client key.
Function you set has to take a client id and return a client key::
@hawk.client_key_loader
def get_client_key(client_id):
if client_id == 'Alice':
retu... | def function[client_key_loader, parameter[self, f]]:
constant[Registers a function to be called to find a client key.
Function you set has to take a client id and return a client key::
@hawk.client_key_loader
def get_client_key(client_id):
if client_id == 'Alice... | keyword[def] identifier[client_key_loader] ( identifier[self] , identifier[f] ):
literal[string]
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[wrapped_f] ( identifier[client_id] ):
identifier[client_key] = identifier[f] ( identifier[client_id] )
ke... | def client_key_loader(self, f):
"""Registers a function to be called to find a client key.
Function you set has to take a client id and return a client key::
@hawk.client_key_loader
def get_client_key(client_id):
if client_id == 'Alice':
return '... |
def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
# b_flag == 1 indicates the infinity point
b_flag1 = (z1 % POW_2_383) // POW_2_382
if b_flag1 == 1:
return Z2
x1 = z1 % POW_2_381
x2 = z... | def function[decompress_G2, parameter[p]]:
constant[
Recovers x and y coordinates from the compressed point (z1, z2).
]
<ast.Tuple object at 0x7da2041da080> assign[=] name[p]
variable[b_flag1] assign[=] binary_operation[binary_operation[name[z1] <ast.Mod object at 0x7da2590d6920> name[PO... | keyword[def] identifier[decompress_G2] ( identifier[p] : identifier[G2Compressed] )-> identifier[G2Uncompressed] :
literal[string]
identifier[z1] , identifier[z2] = identifier[p]
identifier[b_flag1] =( identifier[z1] % identifier[POW_2_383] )// identifier[POW_2_382]
keyword[if] identifie... | def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
(z1, z2) = p
# b_flag == 1 indicates the infinity point
b_flag1 = z1 % POW_2_383 // POW_2_382
if b_flag1 == 1:
return Z2 # depends on [control=['if'], data=... |
def replace_with_text_stream(stream_name):
"""Given a stream name, replace the target stream with a text-converted equivalent
:param str stream_name: The name of a target stream, such as **stdout** or **stderr**
:return: None
"""
new_stream = TEXT_STREAMS.get(stream_name)
if new_stream is not N... | def function[replace_with_text_stream, parameter[stream_name]]:
constant[Given a stream name, replace the target stream with a text-converted equivalent
:param str stream_name: The name of a target stream, such as **stdout** or **stderr**
:return: None
]
variable[new_stream] assign[=] call[... | keyword[def] identifier[replace_with_text_stream] ( identifier[stream_name] ):
literal[string]
identifier[new_stream] = identifier[TEXT_STREAMS] . identifier[get] ( identifier[stream_name] )
keyword[if] identifier[new_stream] keyword[is] keyword[not] keyword[None] :
identifier[new_stream]... | def replace_with_text_stream(stream_name):
"""Given a stream name, replace the target stream with a text-converted equivalent
:param str stream_name: The name of a target stream, such as **stdout** or **stderr**
:return: None
"""
new_stream = TEXT_STREAMS.get(stream_name)
if new_stream is not N... |
def _init_deferred_buffers(self):
"""
Initialize or reinitalize all the deferred transfer buffers
Calling this method will drop all pending transactions
so use with care.
"""
# List of transfers that have been started, but
# not completed (started by write_reg, r... | def function[_init_deferred_buffers, parameter[self]]:
constant[
Initialize or reinitalize all the deferred transfer buffers
Calling this method will drop all pending transactions
so use with care.
]
name[self]._transfer_list assign[=] call[name[collections].deque, param... | keyword[def] identifier[_init_deferred_buffers] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_transfer_list] = identifier[collections] . identifier[deque] ()
identifier[self] . identifier[_crnt_cmd] = identifier[_Command] ... | def _init_deferred_buffers(self):
"""
Initialize or reinitalize all the deferred transfer buffers
Calling this method will drop all pending transactions
so use with care.
"""
# List of transfers that have been started, but
# not completed (started by write_reg, read_reg,
... |
def visitLanguageRange(self, ctx: ShExDocParser.LanguageRangeContext):
""" ShExC: languageRange : LANGTAG (STEM_MARK languagExclusion*)?
ShExJ: valueSetValue = objectValue | LanguageStem | LanguageStemRange """
baselang = ctx.LANGTAG().getText()
if not ctx.STEM_MARK(): ... | def function[visitLanguageRange, parameter[self, ctx]]:
constant[ ShExC: languageRange : LANGTAG (STEM_MARK languagExclusion*)?
ShExJ: valueSetValue = objectValue | LanguageStem | LanguageStemRange ]
variable[baselang] assign[=] call[call[name[ctx].LANGTAG, parameter[]].getText, parameter[]... | keyword[def] identifier[visitLanguageRange] ( identifier[self] , identifier[ctx] : identifier[ShExDocParser] . identifier[LanguageRangeContext] ):
literal[string]
identifier[baselang] = identifier[ctx] . identifier[LANGTAG] (). identifier[getText] ()
keyword[if] keyword[not] identifier[c... | def visitLanguageRange(self, ctx: ShExDocParser.LanguageRangeContext):
""" ShExC: languageRange : LANGTAG (STEM_MARK languagExclusion*)?
ShExJ: valueSetValue = objectValue | LanguageStem | LanguageStemRange """
baselang = ctx.LANGTAG().getText()
if not ctx.STEM_MARK(): # valueSetValue = object... |
def set_min_requests_per_connection(self, host_distance, min_requests):
"""
Sets a threshold for concurrent requests per connection, below which
connections will be considered for disposal (down to core connections;
see :meth:`~Cluster.set_core_connections_per_host`).
Pertains t... | def function[set_min_requests_per_connection, parameter[self, host_distance, min_requests]]:
constant[
Sets a threshold for concurrent requests per connection, below which
connections will be considered for disposal (down to core connections;
see :meth:`~Cluster.set_core_connections_per_... | keyword[def] identifier[set_min_requests_per_connection] ( identifier[self] , identifier[host_distance] , identifier[min_requests] ):
literal[string]
keyword[if] identifier[self] . identifier[protocol_version] >= literal[int] :
keyword[raise] identifier[UnsupportedOperation] (
... | def set_min_requests_per_connection(self, host_distance, min_requests):
"""
Sets a threshold for concurrent requests per connection, below which
connections will be considered for disposal (down to core connections;
see :meth:`~Cluster.set_core_connections_per_host`).
Pertains to co... |
def XMPP_display(self,*arg):
""" For XMPP Demo
輸出到 XMPP 之樣式。
"""
MA = ''
for i in arg:
MAs = '- MA%02s: %.2f %s(%s)\n' % (
unicode(i),
self.MA(i),
self.MAC(i),
unicode(self.MA_serial(i)[0])
)
MA = MA + MAs
vol = '- Volume: %s %s(%s)' % (
... | def function[XMPP_display, parameter[self]]:
constant[ For XMPP Demo
輸出到 XMPP 之樣式。
]
variable[MA] assign[=] constant[]
for taget[name[i]] in starred[name[arg]] begin[:]
variable[MAs] assign[=] binary_operation[constant[- MA%02s: %.2f %s(%s)
] <ast.Mod object at 0x7da2... | keyword[def] identifier[XMPP_display] ( identifier[self] ,* identifier[arg] ):
literal[string]
identifier[MA] = literal[string]
keyword[for] identifier[i] keyword[in] identifier[arg] :
identifier[MAs] = literal[string] %(
identifier[unicode] ( identifier[i] ),
identifier[self... | def XMPP_display(self, *arg):
""" For XMPP Demo
輸出到 XMPP 之樣式。
"""
MA = ''
for i in arg:
MAs = '- MA%02s: %.2f %s(%s)\n' % (unicode(i), self.MA(i), self.MAC(i), unicode(self.MA_serial(i)[0]))
MA = MA + MAs # depends on [control=['for'], data=['i']]
vol = '- Volume: %s %s(%s)'... |
def _handle_magic_exception(self, mod, exc):
"""
Beginning with Ansible >2.6, some modules (file.py) install a
sys.excepthook which is a closure over AnsibleModule, redirecting the
magical exception to AnsibleModule.fail_json().
For extra special needs bonus points, the class is... | def function[_handle_magic_exception, parameter[self, mod, exc]]:
constant[
Beginning with Ansible >2.6, some modules (file.py) install a
sys.excepthook which is a closure over AnsibleModule, redirecting the
magical exception to AnsibleModule.fail_json().
For extra special needs... | keyword[def] identifier[_handle_magic_exception] ( identifier[self] , identifier[mod] , identifier[exc] ):
literal[string]
identifier[klass] = identifier[getattr] ( identifier[mod] , literal[string] , keyword[None] )
keyword[if] identifier[klass] keyword[and] identifier[isinstance] ( id... | def _handle_magic_exception(self, mod, exc):
"""
Beginning with Ansible >2.6, some modules (file.py) install a
sys.excepthook which is a closure over AnsibleModule, redirecting the
magical exception to AnsibleModule.fail_json().
For extra special needs bonus points, the class is not... |
def search_template_present(name, definition):
'''
Ensure that the named search template is present.
name
Name of the search template to add
definition
Required dict for creation parameters as per http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html
*... | def function[search_template_present, parameter[name, definition]]:
constant[
Ensure that the named search template is present.
name
Name of the search template to add
definition
Required dict for creation parameters as per http://www.elastic.co/guide/en/elasticsearch/reference/curr... | keyword[def] identifier[search_template_present] ( identifier[name] , identifier[definition] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] :{}, literal[string] : keyword[True] , literal[string] : literal[string] }
keyword[try] :
identifier[templa... | def search_template_present(name, definition):
"""
Ensure that the named search template is present.
name
Name of the search template to add
definition
Required dict for creation parameters as per http://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html
*... |
def format_list(extracted_list):
"""Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
same index in the argument... | def function[format_list, parameter[extracted_list]]:
constant[Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the... | keyword[def] identifier[format_list] ( identifier[extracted_list] ):
literal[string]
identifier[list] =[]
keyword[for] identifier[filename] , identifier[lineno] , identifier[name] , identifier[line] keyword[in] identifier[extracted_list] :
identifier[item] = literal[string] %( identifier[f... | def format_list(extracted_list):
"""Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
same index in the argument... |
def CreateProductPartition(client, adgroup_id):
"""Creates a ProductPartition tree for the given AdGroup ID.
Args:
client: an AdWordsClient instance.
adgroup_id: a str AdGroup ID.
Returns:
The ProductPartition tree as a sudsobject.
"""
ad_group_criterion_service = client.GetService('AdGroupCrite... | def function[CreateProductPartition, parameter[client, adgroup_id]]:
constant[Creates a ProductPartition tree for the given AdGroup ID.
Args:
client: an AdWordsClient instance.
adgroup_id: a str AdGroup ID.
Returns:
The ProductPartition tree as a sudsobject.
]
variable[ad_group_crite... | keyword[def] identifier[CreateProductPartition] ( identifier[client] , identifier[adgroup_id] ):
literal[string]
identifier[ad_group_criterion_service] = identifier[client] . identifier[GetService] ( literal[string] ,
literal[string] )
identifier[helper] = identifier[ProductPartitionHelper] ( identifier[... | def CreateProductPartition(client, adgroup_id):
"""Creates a ProductPartition tree for the given AdGroup ID.
Args:
client: an AdWordsClient instance.
adgroup_id: a str AdGroup ID.
Returns:
The ProductPartition tree as a sudsobject.
"""
ad_group_criterion_service = client.GetService('AdGroupC... |
def set_value(self, value):
"""Set value of the checkbox.
Parameters
----------
value : bool
value for the checkbox
"""
if value:
self.setCheckState(Qt.Checked)
else:
self.setCheckState(Qt.Unchecked) | def function[set_value, parameter[self, value]]:
constant[Set value of the checkbox.
Parameters
----------
value : bool
value for the checkbox
]
if name[value] begin[:]
call[name[self].setCheckState, parameter[name[Qt].Checked]] | keyword[def] identifier[set_value] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] :
identifier[self] . identifier[setCheckState] ( identifier[Qt] . identifier[Checked] )
keyword[else] :
identifier[self] . identifier[setChe... | def set_value(self, value):
"""Set value of the checkbox.
Parameters
----------
value : bool
value for the checkbox
"""
if value:
self.setCheckState(Qt.Checked) # depends on [control=['if'], data=[]]
else:
self.setCheckState(Qt.Unchecked) |
def getElementsByClassName(self, className, root='root', useIndex=True):
'''
getElementsByClassName - Searches and returns all elements containing a given class name.
@param className <str> - A one-word class name
@param root <AdvancedTag/'root'> - Sea... | def function[getElementsByClassName, parameter[self, className, root, useIndex]]:
constant[
getElementsByClassName - Searches and returns all elements containing a given class name.
@param className <str> - A one-word class name
@param root <AdvancedTa... | keyword[def] identifier[getElementsByClassName] ( identifier[self] , identifier[className] , identifier[root] = literal[string] , identifier[useIndex] = keyword[True] ):
literal[string]
( identifier[root] , identifier[isFromRoot] )= identifier[self] . identifier[_handleRootArg] ( identifier[root] )
... | def getElementsByClassName(self, className, root='root', useIndex=True):
"""
getElementsByClassName - Searches and returns all elements containing a given class name.
@param className <str> - A one-word class name
@param root <AdvancedTag/'root'> - Search ... |
def set_IC(self, values):
r"""
A method to set simulation initial conditions
Parameters
----------
values : ND-array or scalar
Set the initial conditions using an 'Np' long array. 'Np' being
the number of pores. If a scalar is given, the same value is
... | def function[set_IC, parameter[self, values]]:
constant[
A method to set simulation initial conditions
Parameters
----------
values : ND-array or scalar
Set the initial conditions using an 'Np' long array. 'Np' being
the number of pores. If a scalar is gi... | keyword[def] identifier[set_IC] ( identifier[self] , identifier[values] ):
literal[string]
identifier[self] [ identifier[self] . identifier[settings] [ literal[string] ]]= identifier[values]
identifier[converted_array] = identifier[self] [ identifier[self] . identifier[settings] [ literal... | def set_IC(self, values):
"""
A method to set simulation initial conditions
Parameters
----------
values : ND-array or scalar
Set the initial conditions using an 'Np' long array. 'Np' being
the number of pores. If a scalar is given, the same value is
... |
def df2chucks(din,chunksize,outd,fn,return_fmt='\t',force=False):
"""
:param return_fmt: '\t': tab-sep file, lly, '.', 'list': returns a list
"""
from os.path import exists#,splitext,dirname,splitext,basename,realpath
from os import makedirs
din.index=range(0,len(din),1)
chunkrange=list(np.... | def function[df2chucks, parameter[din, chunksize, outd, fn, return_fmt, force]]:
constant[
:param return_fmt: ' ': tab-sep file, lly, '.', 'list': returns a list
]
from relative_module[os.path] import module[exists]
from relative_module[os] import module[makedirs]
name[din].index assign[... | keyword[def] identifier[df2chucks] ( identifier[din] , identifier[chunksize] , identifier[outd] , identifier[fn] , identifier[return_fmt] = literal[string] , identifier[force] = keyword[False] ):
literal[string]
keyword[from] identifier[os] . identifier[path] keyword[import] identifier[exists]
key... | def df2chucks(din, chunksize, outd, fn, return_fmt='\t', force=False):
"""
:param return_fmt: ' ': tab-sep file, lly, '.', 'list': returns a list
"""
from os.path import exists #,splitext,dirname,splitext,basename,realpath
from os import makedirs
din.index = range(0, len(din), 1)
chunkrange... |
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs)... | def function[requires_submit, parameter[func]]:
constant[
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
]
def function[_wrapper, parame... | keyword[def] identifier[requires_submit] ( identifier[func] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[func] )
keyword[def] identifier[_wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[self] . identifier[_future... | def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs... |
def set_logging_settings(profile, setting, value, store='local'):
r'''
Configure logging settings for the Windows firewall.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.0
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
... | def function[set_logging_settings, parameter[profile, setting, value, store]]:
constant[
Configure logging settings for the Windows firewall.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.0
Args:
profile (str):
The firewall profile to configure. Valid options are:
... | keyword[def] identifier[set_logging_settings] ( identifier[profile] , identifier[setting] , identifier[value] , identifier[store] = literal[string] ):
literal[string]
keyword[return] identifier[salt] . identifier[utils] . identifier[win_lgpo_netsh] . identifier[set_logging_settings] ( identifier[profile] ... | def set_logging_settings(profile, setting, value, store='local'):
"""
Configure logging settings for the Windows firewall.
.. versionadded:: 2018.3.4
.. versionadded:: 2019.2.0
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
... |
def get_search_fields(self):
"""Return list of lookup names."""
if self.search_fields:
return self.search_fields
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__) | def function[get_search_fields, parameter[self]]:
constant[Return list of lookup names.]
if name[self].search_fields begin[:]
return[name[self].search_fields]
<ast.Raise object at 0x7da18fe92d10> | keyword[def] identifier[get_search_fields] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[search_fields] :
keyword[return] identifier[self] . identifier[search_fields]
keyword[raise] identifier[NotImplementedError] ( literal[string] % ident... | def get_search_fields(self):
"""Return list of lookup names."""
if self.search_fields:
return self.search_fields # depends on [control=['if'], data=[]]
raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__) |
def add_jars_for_targets(self, targets, conf, resolved_jars):
"""Adds jar classpath elements to the products of the provided targets.
The resolved jars are added in a way that works with excludes.
:param targets: The targets to add the jars for.
:param conf: The configuration.
:param resolved_jars:... | def function[add_jars_for_targets, parameter[self, targets, conf, resolved_jars]]:
constant[Adds jar classpath elements to the products of the provided targets.
The resolved jars are added in a way that works with excludes.
:param targets: The targets to add the jars for.
:param conf: The configura... | keyword[def] identifier[add_jars_for_targets] ( identifier[self] , identifier[targets] , identifier[conf] , identifier[resolved_jars] ):
literal[string]
identifier[classpath_entries] =[]
keyword[for] identifier[jar] keyword[in] identifier[resolved_jars] :
keyword[if] keyword[not] identifie... | def add_jars_for_targets(self, targets, conf, resolved_jars):
"""Adds jar classpath elements to the products of the provided targets.
The resolved jars are added in a way that works with excludes.
:param targets: The targets to add the jars for.
:param conf: The configuration.
:param resolved_jars:... |
def create_proxy_model(self, model):
"""Create a sort filter proxy model for the given model
:param model: the model to wrap in a proxy
:type model: :class:`QtGui.QAbstractItemModel`
:returns: a new proxy model that can be used for sorting and filtering
:rtype: :class:`QtGui.QAb... | def function[create_proxy_model, parameter[self, model]]:
constant[Create a sort filter proxy model for the given model
:param model: the model to wrap in a proxy
:type model: :class:`QtGui.QAbstractItemModel`
:returns: a new proxy model that can be used for sorting and filtering
... | keyword[def] identifier[create_proxy_model] ( identifier[self] , identifier[model] ):
literal[string]
identifier[proxy] = identifier[ReftrackSortFilterModel] ( identifier[self] )
identifier[proxy] . identifier[setSourceModel] ( identifier[model] )
identifier[model] . identifier[ro... | def create_proxy_model(self, model):
"""Create a sort filter proxy model for the given model
:param model: the model to wrap in a proxy
:type model: :class:`QtGui.QAbstractItemModel`
:returns: a new proxy model that can be used for sorting and filtering
:rtype: :class:`QtGui.QAbstra... |
def map(self, func, *iterables, **kwargs):
"""Apply *func* to the elements of the sequences in *iterables*.
All invocations of *func* are run in the pool. If multiple iterables
are provided, then *func* must take this many arguments, and is applied
with one element from each iterable. A... | def function[map, parameter[self, func]]:
constant[Apply *func* to the elements of the sequences in *iterables*.
All invocations of *func* are run in the pool. If multiple iterables
are provided, then *func* must take this many arguments, and is applied
with one element from each iterab... | keyword[def] identifier[map] ( identifier[self] , identifier[func] ,* identifier[iterables] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
keyword[if] identifier[self] . identifier[_closing] :
keyword[raise] identifier... | def map(self, func, *iterables, **kwargs):
"""Apply *func* to the elements of the sequences in *iterables*.
All invocations of *func* are run in the pool. If multiple iterables
are provided, then *func* must take this many arguments, and is applied
with one element from each iterable. All i... |
def mac_app_exists(app):
'''Check if 'app' is installed (OS X).
Check if the given applications is installed on this OS X system.
Args:
app (str): The application name.
Returns:
bool: Is the app installed or not?
'''
APP_CHECK_APPLESCRIPT = '''try
tell application "Finder"
set appname to name of appl... | def function[mac_app_exists, parameter[app]]:
constant[Check if 'app' is installed (OS X).
Check if the given applications is installed on this OS X system.
Args:
app (str): The application name.
Returns:
bool: Is the app installed or not?
]
variable[APP_CHECK_APPLESCRIPT] assign[=] constan... | keyword[def] identifier[mac_app_exists] ( identifier[app] ):
literal[string]
identifier[APP_CHECK_APPLESCRIPT] = literal[string]
keyword[with] identifier[open] ( literal[string] , literal[string] ) keyword[as] identifier[f] :
identifier[f] . identifier[write] ( identifier[APP_CHECK_APPLESCRIPT] % ident... | def mac_app_exists(app):
"""Check if 'app' is installed (OS X).
Check if the given applications is installed on this OS X system.
Args:
app (str): The application name.
Returns:
bool: Is the app installed or not?
"""
APP_CHECK_APPLESCRIPT = 'try\n\ttell application "Finder"\n\t\tset appname to name... |
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list h... | def function[file_dict, parameter[]]:
constant[
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg... | keyword[def] identifier[file_dict] (* identifier[packages] ,** identifier[kwargs] ):
literal[string]
identifier[errors] =[]
identifier[ret] ={}
identifier[cmd_files] =[ literal[string] , literal[string] , literal[string] ]
keyword[if] keyword[not] identifier[packages] :
keyword[r... | def file_dict(*packages, **kwargs):
"""
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list h... |
def set_evernote_filter(self, date_triggered, trigger):
"""
build the filter that will be used by evernote
:param date_triggered:
:param trigger:
:return: filter
"""
new_date_triggered = arrow.get(str(date_triggered)[:-6],
... | def function[set_evernote_filter, parameter[self, date_triggered, trigger]]:
constant[
build the filter that will be used by evernote
:param date_triggered:
:param trigger:
:return: filter
]
variable[new_date_triggered] assign[=] call[name[arrow].g... | keyword[def] identifier[set_evernote_filter] ( identifier[self] , identifier[date_triggered] , identifier[trigger] ):
literal[string]
identifier[new_date_triggered] = identifier[arrow] . identifier[get] ( identifier[str] ( identifier[date_triggered] )[:- literal[int] ],
literal[string] )
... | def set_evernote_filter(self, date_triggered, trigger):
"""
build the filter that will be used by evernote
:param date_triggered:
:param trigger:
:return: filter
"""
new_date_triggered = arrow.get(str(date_triggered)[:-6], 'YYYY-MM-DD HH:mm:ss')
new_da... |
def process_request(self, request):
"""
Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
... | def function[process_request, parameter[self, request]]:
constant[
Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_c... | keyword[def] identifier[process_request] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[request] . identifier[META] :
keyword[return]
keyword[try] :
identifier[method] , identifier[... | def process_request(self, request):
"""
Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
... |
def print_async_event(self, suffix, event):
'''
Print all of the events with the prefix 'tag'
'''
if not isinstance(event, dict):
return
# if we are "quiet", don't print
if self.opts.get('quiet', False):
return
# some suffixes we don't wa... | def function[print_async_event, parameter[self, suffix, event]]:
constant[
Print all of the events with the prefix 'tag'
]
if <ast.UnaryOp object at 0x7da20c794070> begin[:]
return[None]
if call[name[self].opts.get, parameter[constant[quiet], constant[False]]] begin[:]
... | keyword[def] identifier[print_async_event] ( identifier[self] , identifier[suffix] , identifier[event] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[event] , identifier[dict] ):
keyword[return]
keyword[if] identifier[self] . ... | def print_async_event(self, suffix, event):
"""
Print all of the events with the prefix 'tag'
"""
if not isinstance(event, dict):
return # depends on [control=['if'], data=[]]
# if we are "quiet", don't print
if self.opts.get('quiet', False):
return # depends on [contro... |
def _load_pretrained_tok2vec(nlp, loc):
"""Load pre-trained weights for the 'token-to-vector' part of the component
models, which is typically a CNN. See 'spacy pretrain'. Experimental.
"""
with loc.open("rb") as file_:
weights_data = file_.read()
loaded = []
for name, component in nlp.p... | def function[_load_pretrained_tok2vec, parameter[nlp, loc]]:
constant[Load pre-trained weights for the 'token-to-vector' part of the component
models, which is typically a CNN. See 'spacy pretrain'. Experimental.
]
with call[name[loc].open, parameter[constant[rb]]] begin[:]
varia... | keyword[def] identifier[_load_pretrained_tok2vec] ( identifier[nlp] , identifier[loc] ):
literal[string]
keyword[with] identifier[loc] . identifier[open] ( literal[string] ) keyword[as] identifier[file_] :
identifier[weights_data] = identifier[file_] . identifier[read] ()
identifier[loaded]... | def _load_pretrained_tok2vec(nlp, loc):
"""Load pre-trained weights for the 'token-to-vector' part of the component
models, which is typically a CNN. See 'spacy pretrain'. Experimental.
"""
with loc.open('rb') as file_:
weights_data = file_.read() # depends on [control=['with'], data=['file_']]... |
def get():
"""Return list of Scheduling Blocks Instances known to SDP ."""
LOG.debug('GET list of SBIs.')
# Construct response object.
_url = get_root_url()
response = dict(scheduling_blocks=[],
links=dict(home='{}'.format(_url)))
# Get ordered list of SBI ID's.
block_i... | def function[get, parameter[]]:
constant[Return list of Scheduling Blocks Instances known to SDP .]
call[name[LOG].debug, parameter[constant[GET list of SBIs.]]]
variable[_url] assign[=] call[name[get_root_url], parameter[]]
variable[response] assign[=] call[name[dict], parameter[]]
... | keyword[def] identifier[get] ():
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] )
identifier[_url] = identifier[get_root_url] ()
identifier[response] = identifier[dict] ( identifier[scheduling_blocks] =[],
identifier[links] = identifier[dict] ( identifier[home] =... | def get():
"""Return list of Scheduling Blocks Instances known to SDP ."""
LOG.debug('GET list of SBIs.')
# Construct response object.
_url = get_root_url()
response = dict(scheduling_blocks=[], links=dict(home='{}'.format(_url)))
# Get ordered list of SBI ID's.
block_ids = DB.get_sched_bloc... |
def redeem(ctx, htlc_id, secret, account):
""" Redeem an HTLC contract
"""
print_tx(ctx.blockchain.htlc_redeem(htlc_id, secret, account=account)) | def function[redeem, parameter[ctx, htlc_id, secret, account]]:
constant[ Redeem an HTLC contract
]
call[name[print_tx], parameter[call[name[ctx].blockchain.htlc_redeem, parameter[name[htlc_id], name[secret]]]]] | keyword[def] identifier[redeem] ( identifier[ctx] , identifier[htlc_id] , identifier[secret] , identifier[account] ):
literal[string]
identifier[print_tx] ( identifier[ctx] . identifier[blockchain] . identifier[htlc_redeem] ( identifier[htlc_id] , identifier[secret] , identifier[account] = identifier[accou... | def redeem(ctx, htlc_id, secret, account):
""" Redeem an HTLC contract
"""
print_tx(ctx.blockchain.htlc_redeem(htlc_id, secret, account=account)) |
def enqueue_sync(self, func, *func_args):
'''
Enqueue an arbitrary synchronous function.
Deprecated: Use async version instead
'''
worker = self.pick_sticky(0) # just pick first always
args = (func,) + func_args
coro = worker.enqueue(enums.Task.FUNC, args)
... | def function[enqueue_sync, parameter[self, func]]:
constant[
Enqueue an arbitrary synchronous function.
Deprecated: Use async version instead
]
variable[worker] assign[=] call[name[self].pick_sticky, parameter[constant[0]]]
variable[args] assign[=] binary_operation[tuple... | keyword[def] identifier[enqueue_sync] ( identifier[self] , identifier[func] ,* identifier[func_args] ):
literal[string]
identifier[worker] = identifier[self] . identifier[pick_sticky] ( literal[int] )
identifier[args] =( identifier[func] ,)+ identifier[func_args]
identifier[coro]... | def enqueue_sync(self, func, *func_args):
"""
Enqueue an arbitrary synchronous function.
Deprecated: Use async version instead
"""
worker = self.pick_sticky(0) # just pick first always
args = (func,) + func_args
coro = worker.enqueue(enums.Task.FUNC, args)
asyncio.ensure_fu... |
def data_to_imagesurface (data, **kwargs):
"""Turn arbitrary data values into a Cairo ImageSurface.
The method and arguments are the same as data_to_argb32, except that the
data array will be treated as 2D, and higher dimensionalities are not
allowed. The return value is a Cairo ImageSurface object.
... | def function[data_to_imagesurface, parameter[data]]:
constant[Turn arbitrary data values into a Cairo ImageSurface.
The method and arguments are the same as data_to_argb32, except that the
data array will be treated as 2D, and higher dimensionalities are not
allowed. The return value is a Cairo Ima... | keyword[def] identifier[data_to_imagesurface] ( identifier[data] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[cairo]
identifier[data] = identifier[np] . identifier[atleast_2d] ( identifier[data] )
keyword[if] identifier[data] . identifier[ndim] != literal[int] :
... | def data_to_imagesurface(data, **kwargs):
"""Turn arbitrary data values into a Cairo ImageSurface.
The method and arguments are the same as data_to_argb32, except that the
data array will be treated as 2D, and higher dimensionalities are not
allowed. The return value is a Cairo ImageSurface object.
... |
def _sensoryComputeLearningMode(self, anchorInput):
"""
Associate this location with a sensory input. Subsequently, anchorInput will
activate the current location during anchor().
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-location pair layer.
"""
... | def function[_sensoryComputeLearningMode, parameter[self, anchorInput]]:
constant[
Associate this location with a sensory input. Subsequently, anchorInput will
activate the current location during anchor().
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-lo... | keyword[def] identifier[_sensoryComputeLearningMode] ( identifier[self] , identifier[anchorInput] ):
literal[string]
identifier[overlaps] = identifier[self] . identifier[connections] . identifier[computeActivity] ( identifier[anchorInput] ,
identifier[self] . identifier[connectedPermanence] )
ide... | def _sensoryComputeLearningMode(self, anchorInput):
"""
Associate this location with a sensory input. Subsequently, anchorInput will
activate the current location during anchor().
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-location pair layer.
"""
... |
def _build_matches(matches, uuids, no_filtered, fastmode=False):
"""Build a list with matching subsets"""
result = []
for m in matches:
mk = m[0].uuid if not fastmode else m[0]
subset = [uuids[mk]]
for id_ in m[1:]:
uk = id_.uuid if not fastmode else id_
u ... | def function[_build_matches, parameter[matches, uuids, no_filtered, fastmode]]:
constant[Build a list with matching subsets]
variable[result] assign[=] list[[]]
for taget[name[m]] in starred[name[matches]] begin[:]
variable[mk] assign[=] <ast.IfExp object at 0x7da1b0e9fbb0>
... | keyword[def] identifier[_build_matches] ( identifier[matches] , identifier[uuids] , identifier[no_filtered] , identifier[fastmode] = keyword[False] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[m] keyword[in] identifier[matches] :
identifier[mk] = identifier[m] [ lite... | def _build_matches(matches, uuids, no_filtered, fastmode=False):
"""Build a list with matching subsets"""
result = []
for m in matches:
mk = m[0].uuid if not fastmode else m[0]
subset = [uuids[mk]]
for id_ in m[1:]:
uk = id_.uuid if not fastmode else id_
u = u... |
def add(name,
uid=None,
gid=None,
groups=None,
home=None,
shell=None,
fullname=None,
createhome=True,
**kwargs):
'''
Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <s... | def function[add, parameter[name, uid, gid, groups, home, shell, fullname, createhome]]:
constant[
Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <shell>
]
if call[name[info], parameter[name[name]]] begin[:]
... | keyword[def] identifier[add] ( identifier[name] ,
identifier[uid] = keyword[None] ,
identifier[gid] = keyword[None] ,
identifier[groups] = keyword[None] ,
identifier[home] = keyword[None] ,
identifier[shell] = keyword[None] ,
identifier[fullname] = keyword[None] ,
identifier[createhome] = keyword[True] ,
** id... | def add(name, uid=None, gid=None, groups=None, home=None, shell=None, fullname=None, createhome=True, **kwargs):
"""
Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <shell>
"""
if info(name):
raise CommandExecutionE... |
def badge_form(model):
'''A form factory for a given model badges'''
class BadgeForm(ModelForm):
model_class = Badge
kind = fields.RadioField(
_('Kind'), [validators.DataRequired()],
choices=model.__badges__.items(),
description=_('Kind of badge (certified, e... | def function[badge_form, parameter[model]]:
constant[A form factory for a given model badges]
class class[BadgeForm, parameter[]] begin[:]
variable[model_class] assign[=] name[Badge]
variable[kind] assign[=] call[name[fields].RadioField, parameter[call[name[_], parameter[... | keyword[def] identifier[badge_form] ( identifier[model] ):
literal[string]
keyword[class] identifier[BadgeForm] ( identifier[ModelForm] ):
identifier[model_class] = identifier[Badge]
identifier[kind] = identifier[fields] . identifier[RadioField] (
identifier[_] ( literal[strin... | def badge_form(model):
"""A form factory for a given model badges"""
class BadgeForm(ModelForm):
model_class = Badge
kind = fields.RadioField(_('Kind'), [validators.DataRequired()], choices=model.__badges__.items(), description=_('Kind of badge (certified, etc)'))
return BadgeForm |
def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates."""
page = d["page"]
if not "revision" in page:
return None
... | def function[geo_filter, parameter[d]]:
constant[Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates.]
variable[page] assign[=] call[name[d... | keyword[def] identifier[geo_filter] ( identifier[d] ):
literal[string]
identifier[page] = identifier[d] [ literal[string] ]
keyword[if] keyword[not] literal[string] keyword[in] identifier[page] :
keyword[return] keyword[None]
identifier[title] = identifier[page] [ literal[string] ]... | def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates.
If no coordinates are found, returns None. Otherwise, returns a new dict
with the title and URL of the original article, along with coordinates."""
page = d['page']
if not 'revision' in page:
return None ... |
def deregister(self, pin_num=None, direction=None):
"""De-registers callback functions
:param pin_num: The pin number. If None then all functions are de-registered
:type pin_num: int
:param direction: The event direction. If None then all functions for the
give... | def function[deregister, parameter[self, pin_num, direction]]:
constant[De-registers callback functions
:param pin_num: The pin number. If None then all functions are de-registered
:type pin_num: int
:param direction: The event direction. If None then all functions for the
... | keyword[def] identifier[deregister] ( identifier[self] , identifier[pin_num] = keyword[None] , identifier[direction] = keyword[None] ):
literal[string]
identifier[to_delete] =[]
keyword[for] identifier[i] , identifier[function_map] keyword[in] identifier[enumerate] ( identifier[self] . ... | def deregister(self, pin_num=None, direction=None):
"""De-registers callback functions
:param pin_num: The pin number. If None then all functions are de-registered
:type pin_num: int
:param direction: The event direction. If None then all functions for the
given pi... |
def _wrap_run_cmd(jsonfile, mode='replay'):
"""Wrapper around :func:`run_cmd` for the testing using a record-replay
model
"""
logger = logging.getLogger(__name__)
records = []
counter = 0
json_opts = {'indent': 2, 'separators':(',',': '), 'sort_keys': True}
def run_cmd_record(*args, **kw... | def function[_wrap_run_cmd, parameter[jsonfile, mode]]:
constant[Wrapper around :func:`run_cmd` for the testing using a record-replay
model
]
variable[logger] assign[=] call[name[logging].getLogger, parameter[name[__name__]]]
variable[records] assign[=] list[[]]
variable[counter]... | keyword[def] identifier[_wrap_run_cmd] ( identifier[jsonfile] , identifier[mode] = literal[string] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
identifier[records] =[]
identifier[counter] = literal[int]
identifier[json_opts] ={... | def _wrap_run_cmd(jsonfile, mode='replay'):
"""Wrapper around :func:`run_cmd` for the testing using a record-replay
model
"""
logger = logging.getLogger(__name__)
records = []
counter = 0
json_opts = {'indent': 2, 'separators': (',', ': '), 'sort_keys': True}
def run_cmd_record(*args, *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.