code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False):
"""
Combine send and receive measurement into single function.
This offers a retry mechanism: Overall timeout time is divided by
number of retries. Additional ICMPecho packets are sent to those
addresses from which we have no... | Combine send and receive measurement into single function.
This offers a retry mechanism: Overall timeout time is divided by
number of retries. Additional ICMPecho packets are sent to those
addresses from which we have not received answers, yet.
The retry mechanism is useful, because individual ICMP p... |
def status(self):
"""Get the status of the responding member."""
status_request = etcdrpc.StatusRequest()
status_response = self.maintenancestub.Status(
status_request,
self.timeout,
credentials=self.call_credentials,
metadata=self.metadata
... | Get the status of the responding member. |
def dprint(s):
'''Prints `s` with additional debugging informations'''
import inspect
frameinfo = inspect.stack()[1]
callerframe = frameinfo.frame
d = callerframe.f_locals
if (isinstance(s,str)):
val = eval(s, d)
else:
val = s
cc = frameinfo.code_context[0]
... | Prints `s` with additional debugging informations |
def default_targets(self):
"""Default targets for `dvc repro` and `dvc pipeline`."""
from dvc.stage import Stage
msg = "assuming default target '{}'.".format(Stage.STAGE_FILE)
logger.warning(msg)
return [Stage.STAGE_FILE] | Default targets for `dvc repro` and `dvc pipeline`. |
def song(self):
"""the song associated with the project"""
if self._song is None:
self._song = Song(self._song_data)
return self._song | the song associated with the project |
def iter_chain(cur):
"""Iterate over all of the chains in the database.
Args:
cur (:class:`sqlite3.Cursor`):
An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.
Yields:
list: The chain.
"""
select = "SELECT nodes FROM chain"
for node... | Iterate over all of the chains in the database.
Args:
cur (:class:`sqlite3.Cursor`):
An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.
Yields:
list: The chain. |
def parseinput(inputlist,outputname=None, atfile=None):
"""
Recursively parse user input based upon the irafglob
program and construct a list of files that need to be processed.
This program addresses the following deficiencies of the irafglob program::
parseinput can extract filenames from asso... | Recursively parse user input based upon the irafglob
program and construct a list of files that need to be processed.
This program addresses the following deficiencies of the irafglob program::
parseinput can extract filenames from association tables
Returns
-------
This program will return... |
def highlight_nodes(graph: BELGraph, nodes: Optional[Iterable[BaseEntity]] = None, color: Optional[str]=None):
"""Adds a highlight tag to the given nodes.
:param graph: A BEL graph
:param nodes: The nodes to add a highlight tag on
:param color: The color to highlight (use something that works with CSS)... | Adds a highlight tag to the given nodes.
:param graph: A BEL graph
:param nodes: The nodes to add a highlight tag on
:param color: The color to highlight (use something that works with CSS) |
def get_paged(self, res, **kwargs):
"""
This call is equivalent to ``res(**kwargs)``, only it retrieves all pages
and returns the results joined into a single iterable. The advantage over
retrieving everything at once is that the result can be consumed immediately.
:param res: ... | This call is equivalent to ``res(**kwargs)``, only it retrieves all pages
and returns the results joined into a single iterable. The advantage over
retrieving everything at once is that the result can be consumed immediately.
:param res: what resource to connect to
:param kwargs: f... |
def child_context(self, *args, **kwargs):
"""
Context setup first in child process, before returning from start() call in parent.
Result is passed in as argument of update
:return:
"""
# Now we can extract config values
expected_args = {
'services': [... | Context setup first in child process, before returning from start() call in parent.
Result is passed in as argument of update
:return: |
def generate_dumper(self, mapfile, names):
"""
Build dumpdata commands
"""
return self.build_template(mapfile, names, self._dumpdata_template) | Build dumpdata commands |
def locations_for(self, city_name, country=None, matching='nocase'):
"""
Returns a list of Location objects corresponding to
the int IDs and relative toponyms and 2-chars country of the cities
matching the provided city name.
The rule for identifying matchings is according to the... | Returns a list of Location objects corresponding to
the int IDs and relative toponyms and 2-chars country of the cities
matching the provided city name.
The rule for identifying matchings is according to the provided
`matching` parameter value.
If `country` is provided, the searc... |
def to_dict(self):
"""Return state as a dictionary.
Result can be used to serialize the instance and reconstitute
it later using :meth:`from_dict`.
:rtype: dict
"""
session = self._get_session()
snapshot = self._get_snapshot()
return {
"sessi... | Return state as a dictionary.
Result can be used to serialize the instance and reconstitute
it later using :meth:`from_dict`.
:rtype: dict |
def postprocess_authors_init(self, entry):
"""
If only a single author was found, ensure that ``authors_init`` is
nonetheless a list.
"""
if type(entry.authors_init) is not list:
entry.authors_init = [entry.authors_init] | If only a single author was found, ensure that ``authors_init`` is
nonetheless a list. |
def generate_func_call(name, args=None, kwargs=None):
"""
Generates code to call a function.
Args:
name (str): The function name.
args (list[str]): Each positional argument.
kwargs (list[tuple]): Each tuple is (arg: str, value: str). If
value is None, then the keyword ar... | Generates code to call a function.
Args:
name (str): The function name.
args (list[str]): Each positional argument.
kwargs (list[tuple]): Each tuple is (arg: str, value: str). If
value is None, then the keyword argument is omitted. Otherwise,
if the value is not a st... |
def select(self, choice_scores):
"""
Groups the frozen sets by algorithm and first chooses an algorithm based
on the traditional UCB1 criteria.
Next, from that algorithm's frozen sets, makes the final set choice.
"""
# choose algorithm using a bandit
alg_scores =... | Groups the frozen sets by algorithm and first chooses an algorithm based
on the traditional UCB1 criteria.
Next, from that algorithm's frozen sets, makes the final set choice. |
def _compute_weights(self):
""" Computes the weights for the scaled unscented Kalman filter. """
n = self.n
c = 1. / (n + 1)
self.Wm = np.full(n + 1, c)
self.Wc = self.Wm | Computes the weights for the scaled unscented Kalman filter. |
def get_signing_keys(eid, keydef, key_file):
"""
If the *key_file* file exists then read the keys from there, otherwise
create the keys and store them a file with the name *key_file*.
:param eid: The ID of the entity that the keys belongs to
:param keydef: What keys to create
:param key_file: A... | If the *key_file* file exists then read the keys from there, otherwise
create the keys and store them a file with the name *key_file*.
:param eid: The ID of the entity that the keys belongs to
:param keydef: What keys to create
:param key_file: A file name
:return: A :py:class:`oidcmsg.key_jar.KeyJ... |
def set_input(self, p_name, value):
"""Set a Step's input variable to a certain value.
The value comes either from a workflow input or output of a previous
step.
Args:
name (str): the name of the Step input
value (str): the name of the output variable that p... | Set a Step's input variable to a certain value.
The value comes either from a workflow input or output of a previous
step.
Args:
name (str): the name of the Step input
value (str): the name of the output variable that provides the
value for this inpu... |
def _find_feature_type(self, feature_name, eopatch):
""" Iterates over allowed feature types of given EOPatch and tries to find a feature type for which there
exists a feature with given name
:return: A feature type or `None` if such feature type does not exist
:rtype: FeatureType ... | Iterates over allowed feature types of given EOPatch and tries to find a feature type for which there
exists a feature with given name
:return: A feature type or `None` if such feature type does not exist
:rtype: FeatureType or None |
def _processArgs(self, entry, *_args, **_kwargs):
""" Given an entry, positional and keyword arguments, figure out what
the query-string options, payload and api arguments are.
"""
# We need the args to be a list so we can mutate them
args = list(_args)
kwargs = copy.dee... | Given an entry, positional and keyword arguments, figure out what
the query-string options, payload and api arguments are. |
def write(self, text, fg='black', bg='white'):
'''write to the console'''
if isinstance(text, str):
sys.stdout.write(text)
else:
sys.stdout.write(str(text))
sys.stdout.flush() | write to the console |
def parse_kal_scan(kal_out):
"""Parse kal band scan output."""
kal_data = []
scan_band = determine_scan_band(kal_out)
scan_gain = determine_scan_gain(kal_out)
scan_device = determine_device(kal_out)
sample_rate = determine_sample_rate(kal_out)
chan_detect_threshold = determine_chan_detect_th... | Parse kal band scan output. |
def advection(scalar, wind, deltas):
r"""Calculate the advection of a scalar field by the wind.
The order of the dimensions of the arrays must match the order in which
the wind components are given. For example, if the winds are given [u, v],
then the scalar and wind arrays must be indexed as x,y (whi... | r"""Calculate the advection of a scalar field by the wind.
The order of the dimensions of the arrays must match the order in which
the wind components are given. For example, if the winds are given [u, v],
then the scalar and wind arrays must be indexed as x,y (which puts x as the
rows, not columns).
... |
def list_files(self, dataset_id, glob=".", is_dir=False):
"""
List matched filenames in a dataset on Citrination.
:param dataset_id: The ID of the dataset to search for files.
:type dataset_id: int
:param glob: A pattern which will be matched against files in the dataset.
... | List matched filenames in a dataset on Citrination.
:param dataset_id: The ID of the dataset to search for files.
:type dataset_id: int
:param glob: A pattern which will be matched against files in the dataset.
:type glob: str
:param is_dir: A boolean indicating whether or not t... |
def _peg_pose_in_hole_frame(self):
"""
A helper function that takes in a named data field and returns the pose of that
object in the base frame.
"""
# World frame
peg_pos_in_world = self.sim.data.get_body_xpos("cylinder")
peg_rot_in_world = self.sim.data.get_body_... | A helper function that takes in a named data field and returns the pose of that
object in the base frame. |
def reversals(self, transfer_id, data={}, **kwargs):
""""
Get all Reversal Transfer from given id
Args:
transfer_id :
Id for which reversal transfer object has to be fetched
Returns:
Transfer Dict
"""
url = "{}/{}/reversals".forma... | Get all Reversal Transfer from given id
Args:
transfer_id :
Id for which reversal transfer object has to be fetched
Returns:
Transfer Dict |
def list(self, *args, **kwargs):
"""
List swarm nodes.
Args:
filters (dict): Filters to process on the nodes list. Valid
filters: ``id``, ``name``, ``membership`` and ``role``.
Default: ``None``
Returns:
A list of :py:class:`Node`... | List swarm nodes.
Args:
filters (dict): Filters to process on the nodes list. Valid
filters: ``id``, ``name``, ``membership`` and ``role``.
Default: ``None``
Returns:
A list of :py:class:`Node` objects.
Raises:
:py:class:`doc... |
def perform(self, command, params=None, **kwargs):
"""Execute a command.
Arguments can be supplied either as a dictionary or as keyword
arguments. Examples:
stc.perform('LoadFromXml', {'filename':'config.xml'})
stc.perform('LoadFromXml', filename='config.xml')
... | Execute a command.
Arguments can be supplied either as a dictionary or as keyword
arguments. Examples:
stc.perform('LoadFromXml', {'filename':'config.xml'})
stc.perform('LoadFromXml', filename='config.xml')
Arguments:
command -- Command to execute.
para... |
def unpublish(self):
"""
Unpublishes the resource.
"""
self._client._delete(
"{0}/published".format(
self.__class__.base_url(
self.sys['space'].id,
self.sys['id'],
environment_id=self._environment_id... | Unpublishes the resource. |
def is_uncertainty_edition_allowed(self, analysis_brain):
"""Checks if the edition of the uncertainty field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False
"""
# Only allow to edit the unce... | Checks if the edition of the uncertainty field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False |
def byte_bounds_offset(self):
"""Return start and end offsets of this segment's data into the
base array's data.
This ignores the byte order index. Arrays using the byte order index
will have the entire base array's raw data.
"""
if self.data.base is None:
if... | Return start and end offsets of this segment's data into the
base array's data.
This ignores the byte order index. Arrays using the byte order index
will have the entire base array's raw data. |
def imagetransformer_sep_channels_12l_16h_imagenet_large():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_8l_8h()
hparams.num_hidden_layers = 12
hparams.batch_size = 1
hparams.filter_size = 2048
hparams.num_heads = 16
hparams.learning_rate_warmup_steps = 16000
hparams.sampling_m... | separate rgb embeddings. |
def set_many(self, mapping, timeout=None):
"""Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
:returns: Whether all... | Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
:returns: Whether all given keys have been set.
:rtype: boolean |
def artUrl(self):
""" Return the first first art url starting on the most specific for that item."""
art = self.firstAttr('art', 'grandparentArt')
return self._server.url(art, includeToken=True) if art else None | Return the first first art url starting on the most specific for that item. |
def refresh_fqdn_cache(force=False):
'''
Force refreshes all FQDNs used in rules.
force
Forces all fqdn refresh
CLI Example:
.. code-block:: bash
salt '*' panos.refresh_fqdn_cache
salt '*' panos.refresh_fqdn_cache force=True
'''
if not isinstance(force, bool):
... | Force refreshes all FQDNs used in rules.
force
Forces all fqdn refresh
CLI Example:
.. code-block:: bash
salt '*' panos.refresh_fqdn_cache
salt '*' panos.refresh_fqdn_cache force=True |
def is_switched_on(self, refresh=False):
"""Get armed state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh()
val = self.get_value('Armed')
r... | Get armed state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions. |
def until(self, condition, is_true=None, message=""):
"""Repeatedly runs condition until its return value evalutes to true,
or its timeout expires or the predicate evaluates to true.
This will poll at the given interval until the given timeout
is reached, or the predicate or conditions ... | Repeatedly runs condition until its return value evalutes to true,
or its timeout expires or the predicate evaluates to true.
This will poll at the given interval until the given timeout
is reached, or the predicate or conditions returns true. A
condition that returns null or does not ... |
def syncView(self):
"""
Syncs all the items to the view.
"""
if not self.updatesEnabled():
return
for item in self.topLevelItems():
try:
item.syncView(recursive=True)
except AttributeError:
co... | Syncs all the items to the view. |
def write_branch_data(self, file):
""" Writes branch data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(BRANCH_ATTRS)
for branch in self.case.branches:
writer.writerow([getattr(branch, a) for a in BRANCH_ATTRS]) | Writes branch data as CSV. |
def _authenticate(self, params, headers):
"""
Method that simply adjusts authentication credentials for the
request.
`params` is the querystring of the request.
`headers` is the header of the request.
If auth instance is not provided to this class, this method simply
... | Method that simply adjusts authentication credentials for the
request.
`params` is the querystring of the request.
`headers` is the header of the request.
If auth instance is not provided to this class, this method simply
returns without doing anything. |
def to_pb(self):
"""Converts the union into a single GC rule as a protobuf.
:rtype: :class:`.table_v2_pb2.GcRule`
:returns: The converted current object.
"""
union = table_v2_pb2.GcRule.Union(rules=[rule.to_pb() for rule in self.rules])
return table_v2_pb2.GcRule(union=u... | Converts the union into a single GC rule as a protobuf.
:rtype: :class:`.table_v2_pb2.GcRule`
:returns: The converted current object. |
def keyword_hookup(self, noteId, keywords):
'''
Unhook existing cross-linking entries.
'''
try:
self.cur.execute("DELETE FROM notekeyword WHERE noteid=?", [noteId])
except:
self.error("ERROR: cannot unhook previous keywords")
# Now, hook up new the... | Unhook existing cross-linking entries. |
def from_offset(self, value):
'''
The starting from index of the hits to return. Defaults to 0.
'''
if not self.params:
self.params = dict({'from':value})
return self
self.params['from'] = value
return self | The starting from index of the hits to return. Defaults to 0. |
def adjustHeight(self, column):
"""
Adjusts the height for this item based on the columna and its text.
:param column | <int>
"""
tree = self.treeWidget()
if not tree:
return
w = tree.width()
if tree.verticalSc... | Adjusts the height for this item based on the columna and its text.
:param column | <int> |
def interpret(self, msg):
""" Load input """
slides = msg.get('slides', [])
self.cache = msg.get('folder', '.')
self.gallery = msg.get('gallery', ['..'])
self.finder.interpret(dict(galleries=self.gallery))
# in case slides is a generator, turn it into a list
# si... | Load input |
def dns_resource_reference(self):
"""Instance depends on the API version:
* 2018-05-01: :class:`DnsResourceReferenceOperations<azure.mgmt.dns.v2018_05_01.operations.DnsResourceReferenceOperations>`
"""
api_version = self._get_api_version('dns_resource_reference')
if api_versi... | Instance depends on the API version:
* 2018-05-01: :class:`DnsResourceReferenceOperations<azure.mgmt.dns.v2018_05_01.operations.DnsResourceReferenceOperations>` |
def set(self, key, value, **kw):
"""Place a value in the cache.
:param key: the value's key.
:param value: the value.
:param \**kw: cache configuration arguments.
"""
self.impl.set(key, value, **self._get_cache_kw(kw, None)) | Place a value in the cache.
:param key: the value's key.
:param value: the value.
:param \**kw: cache configuration arguments. |
def in_use(self):
"""Returns True if there is a :class:`State` object that uses this
``Flow``"""
state = State.objects.filter(flow=self).first()
return bool(state) | Returns True if there is a :class:`State` object that uses this
``Flow`` |
def choice_voters_changed_update_cache(
sender, instance, action, reverse, model, pk_set, **kwargs):
"""Update cache when choice.voters changes."""
if action not in ('post_add', 'post_remove', 'post_clear'):
# post_clear is not handled, because clear is called in
# django.db.models.field... | Update cache when choice.voters changes. |
def add(self, layer, verbosity = 0, position = None):
"""
Adds a layer. Layer verbosity is optional (default 0).
"""
layer._verbosity = verbosity
layer._maxRandom = self._maxRandom
layer.minTarget = 0.0
layer.maxTarget = 1.0
layer.minActivation = 0.0
... | Adds a layer. Layer verbosity is optional (default 0). |
def generate_enums(basename, xml):
'''generate main header per XML file'''
directory = os.path.join(basename, '''enums''')
mavparse.mkdir_p(directory)
for en in xml.enum:
f = open(os.path.join(directory, en.name+".java"), mode='w')
t.write(f, '''
/* AUTO-GENERATED FILE. DO NOT MODIFY.
... | generate main header per XML file |
def check_output(self, cmd):
"""Calls a command through SSH and returns its output.
"""
ret, output = self._call(cmd, True)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret)
logger.debug("Output: %r", output)
return output | Calls a command through SSH and returns its output. |
def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | Get items from this collection that are added in the current tower. |
def sign_ssh_challenge(self, blob, identity):
"""Sign given blob using a private key on the device."""
msg = _parse_ssh_blob(blob)
log.debug('%s: user %r via %r (%r)',
msg['conn'], msg['user'], msg['auth'], msg['key_type'])
log.debug('nonce: %r', msg['nonce'])
f... | Sign given blob using a private key on the device. |
def get_kernel_id(self):
"""
Get the kernel id of the client.
Return a str with the kernel id or None.
"""
sessions_url = self.get_session_url()
sessions_req = requests.get(sessions_url).content.decode()
sessions = json.loads(sessions_req)
if os.name == ... | Get the kernel id of the client.
Return a str with the kernel id or None. |
def _find_link_target(self, tarinfo):
"""Find the target member of a symlink or hardlink member in the
archive.
"""
if tarinfo.issym():
# Always search the entire archive.
linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname
limit = Non... | Find the target member of a symlink or hardlink member in the
archive. |
def set(self, name: str, value: Any) -> None:
"""
Stores a knowledge item in the agent knowledge base.
Args:
name (str): name of the item
value (Any): value of the item
"""
self.agent.set(name, value) | Stores a knowledge item in the agent knowledge base.
Args:
name (str): name of the item
value (Any): value of the item |
def table(self) -> Table:
"""
Returns a SQLAlchemy :class:`Table` object. This is either the
:class:`Table` object that was used for initialization, or one that
was constructed from the ``tablename`` plus the ``metadata``.
"""
if self._table is not None:
retur... | Returns a SQLAlchemy :class:`Table` object. This is either the
:class:`Table` object that was used for initialization, or one that
was constructed from the ``tablename`` plus the ``metadata``. |
def vcsNodeState_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs")
originator_switch_info = ET.SubElement(vcsNodeState, ... | Auto Generated Code |
def _encode_params(data):
"""Encode parameters in a piece of data.
If the data supplied is a dictionary, encodes each parameter in it, and
returns a list of tuples containing the encoded parameters, and a urlencoded
version of that.
Otherwise, assumes the data is already encode... | Encode parameters in a piece of data.
If the data supplied is a dictionary, encodes each parameter in it, and
returns a list of tuples containing the encoded parameters, and a urlencoded
version of that.
Otherwise, assumes the data is already encoded appropriately, and
returns ... |
def friedmanchisquare(*args):
"""
Friedman Chi-Square is a non-parametric, one-way within-subjects
ANOVA. This function calculates the Friedman Chi-square test for repeated
measures and returns the result, along with the associated probability
value. It assumes 3 or more repeated measures. Only 3 levels requires... | Friedman Chi-Square is a non-parametric, one-way within-subjects
ANOVA. This function calculates the Friedman Chi-square test for repeated
measures and returns the result, along with the associated probability
value. It assumes 3 or more repeated measures. Only 3 levels requires a
minimum of 10 subjects in the study... |
def delete(self):
"""Deletes the object from the datastore."""
pipeline = self.db.pipeline()
self._delete_from_indices(pipeline)
self._delete_membership(pipeline)
pipeline.delete(self.key())
pipeline.execute() | Deletes the object from the datastore. |
def state(name):
'''
Returns the state of the container
name
Container name or ID
**RETURN DATA**
A string representing the current state of the container (either
``running``, ``paused``, or ``stopped``)
CLI Example:
.. code-block:: bash
salt myminion docker.state... | Returns the state of the container
name
Container name or ID
**RETURN DATA**
A string representing the current state of the container (either
``running``, ``paused``, or ``stopped``)
CLI Example:
.. code-block:: bash
salt myminion docker.state mycontainer |
def _pfp__parse(self, stream, save_offset=False):
"""Parse the IO stream for this enum
:stream: An IO stream that can be read from
:returns: The number of bytes parsed
"""
res = super(Enum, self)._pfp__parse(stream, save_offset)
if self._pfp__value in self.enum_vals:
... | Parse the IO stream for this enum
:stream: An IO stream that can be read from
:returns: The number of bytes parsed |
def stop(self):
"""Stop streaming samples from device and delete samples buffer"""
if not self.device.is_streaming:
return
self.device.stop_stream()
self._writer.close()
self._bins = None
self._repeats = None
self._base_buffer_size = None
sel... | Stop streaming samples from device and delete samples buffer |
def reconstitute_path(drive, folders):
"""Reverts a tuple from `get_path_components` into a path.
:param drive: A drive (eg 'c:'). Only applicable for NT systems
:param folders: A list of folder names
:return: A path comprising the drive and list of folder names. The path terminate
with a ... | Reverts a tuple from `get_path_components` into a path.
:param drive: A drive (eg 'c:'). Only applicable for NT systems
:param folders: A list of folder names
:return: A path comprising the drive and list of folder names. The path terminate
with a `os.path.sep` *only* if it is a root directory |
def map_transaction(txn):
"""
Maps a single transaction row to a dictionary.
Parameters
----------
txn : pd.DataFrame
A single transaction object to convert to a dictionary.
Returns
-------
dict
Mapped transaction.
"""
if isinstance(txn['sid'], dict):
s... | Maps a single transaction row to a dictionary.
Parameters
----------
txn : pd.DataFrame
A single transaction object to convert to a dictionary.
Returns
-------
dict
Mapped transaction. |
def download_file(cls, url, local_file_name=None, force=False, chunk_size=1024):
"""
Download file from a given url
"""
local_file_name = local_file_name if local_file_name else url.split('/')[-1]
filepath = os.path.join(cls.data_path, local_file_name)
if not os.path.ex... | Download file from a given url |
def mget(self, body, doc_type=None, index=None, params=None):
"""
Get multiple documents based on an index, type (optional) and ids.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>`_
:arg body: Document identifiers; can be either `docs` (containing ... | Get multiple documents based on an index, type (optional) and ids.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-multi-get.html>`_
:arg body: Document identifiers; can be either `docs` (containing full
document information) or `ids` (when index and type is provided i... |
def init_app(self, app):
"""Initialize an application.
:param app: A :class:`~flask.Flask` app.
"""
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['nav'] = self
app.add_template_global(self.elems, 'nav')
# register some render... | Initialize an application.
:param app: A :class:`~flask.Flask` app. |
def idle_print_status(self):
'''print out statistics every 10 seconds from idle loop'''
now = time.time()
if (now - self.last_idle_status_printed_time) >= 10:
print(self.status())
self.last_idle_status_printed_time = now | print out statistics every 10 seconds from idle loop |
def pairwise_kernel(self, X, Y):
"""Function to use with :func:`sklearn.metrics.pairwise.pairwise_kernels`
Parameters
----------
X : array, shape = (n_features,)
Y : array, shape = (n_features,)
Returns
-------
similarity : float
Similaritie... | Function to use with :func:`sklearn.metrics.pairwise.pairwise_kernels`
Parameters
----------
X : array, shape = (n_features,)
Y : array, shape = (n_features,)
Returns
-------
similarity : float
Similarities are normalized to be within [0, 1] |
def wait_until_page_ready(page_object, timeout=WTF_TIMEOUT_MANAGER.NORMAL):
"""Waits until document.readyState == Complete (e.g. ready to execute javascript commands)
Args:
page_object (PageObject) : PageObject class
Kwargs:
timeout (number) : timeout period
"""... | Waits until document.readyState == Complete (e.g. ready to execute javascript commands)
Args:
page_object (PageObject) : PageObject class
Kwargs:
timeout (number) : timeout period |
def newgroups_gen(self, timestamp):
"""Generator for the NEWGROUPS command.
Generates a list of newsgroups created on the server since the specified
timestamp.
See <http://tools.ietf.org/html/rfc3977#section-7.3>
Args:
timestamp: Datetime object giving 'created sin... | Generator for the NEWGROUPS command.
Generates a list of newsgroups created on the server since the specified
timestamp.
See <http://tools.ietf.org/html/rfc3977#section-7.3>
Args:
timestamp: Datetime object giving 'created since' datetime.
Yields:
A tu... |
def autocomplete(query, country=None, hurricanes=False, cities=True, timeout=5):
"""Make an autocomplete API request
This can be used to find cities and/or hurricanes by name
:param string query: city
:param string country: restrict search to a specific country. Must be a two letter country code
:... | Make an autocomplete API request
This can be used to find cities and/or hurricanes by name
:param string query: city
:param string country: restrict search to a specific country. Must be a two letter country code
:param boolean hurricanes: whether to search for hurricanes or not
:param boolean cit... |
def update(self):
"""Update the status of the range setting."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data and (time.time() - self.__manual_update_time > 60):
self.__maxrange_state = data['charge_to_ma... | Update the status of the range setting. |
def cluster_centers_(self):
"""
Searches for or creates cluster centers for the specified clustering
algorithm. This algorithm ensures that that the centers are
appropriately drawn and scaled so that distance between clusters are
maintained.
"""
# TODO: Handle agg... | Searches for or creates cluster centers for the specified clustering
algorithm. This algorithm ensures that that the centers are
appropriately drawn and scaled so that distance between clusters are
maintained. |
def writeSentence(self, cmd, *words):
"""
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
"""
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded) | Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words. |
def example_value(self):
"""
If we're an instance of a Serializable, fall back to its
`example_instance()` method.
"""
from .serializable import Serializable
inst = self._static_example_value()
if inst is tr.Undefined and issubclass(self.klass, Serializable):
... | If we're an instance of a Serializable, fall back to its
`example_instance()` method. |
def log_call(call_name):
"""Log the API call to the logger."""
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
instance.logger.info(call_name, {"content": request.get_json()})
return f(*args, **kw)
return wrapper
return dec... | Log the API call to the logger. |
def plot_grid(step):
"""Plot cell position and thickness.
The figure is call grid_N.pdf where N is replace by the step index.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
"""
rad = get_rprof(step, 'r')[0]
drad = get_rprof(step, 'dr')[0]
... | Plot cell position and thickness.
The figure is call grid_N.pdf where N is replace by the step index.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance. |
def convert_column(self, values):
"""Normalize values."""
assert all(values >= 0), 'Cannot normalize a column with negatives'
total = sum(values)
if total > 0:
return values / total
else:
return values | Normalize values. |
def positionToIntensityUncertaintyForPxGroup(image, std, y0, y1, x0, x1):
'''
like positionToIntensityUncertainty
but calculated average uncertainty for an area [y0:y1,x0:x1]
'''
fy, fx = y1 - y0, x1 - x0
if fy != fx:
raise Exception('averaged area need to be square ATM')
ima... | like positionToIntensityUncertainty
but calculated average uncertainty for an area [y0:y1,x0:x1] |
def jwt_optional(fn):
"""
A decorator to optionally protect a Flask endpoint
If an access token in present in the request, this will call the endpoint
with :func:`~flask_jwt_extended.get_jwt_identity` having the identity
of the access token. If no access token is present in the request,
this en... | A decorator to optionally protect a Flask endpoint
If an access token in present in the request, this will call the endpoint
with :func:`~flask_jwt_extended.get_jwt_identity` having the identity
of the access token. If no access token is present in the request,
this endpoint will still be called, but
... |
def get_percentile(self, percentile):
"""Get a value representing a the input percentile of the Data Collection.
Args:
percentile: A float value from 0 to 100 representing the
requested percentile.
Return:
The Data Collection value at the input percentil... | Get a value representing a the input percentile of the Data Collection.
Args:
percentile: A float value from 0 to 100 representing the
requested percentile.
Return:
The Data Collection value at the input percentile |
def generate(basename, xml):
'''generate complete python implemenation'''
if basename.endswith('.lua'):
filename = basename
else:
filename = basename + '.lua'
msgs = []
enums = []
filelist = []
for x in xml:
msgs.extend(x.message)
enums.extend(x.enum)
... | generate complete python implemenation |
def CheckBreakpointsExpiration(self):
"""Completes all breakpoints that have been active for too long."""
with self._lock:
current_time = BreakpointsManager.GetCurrentTime()
if self._next_expiration > current_time:
return
expired_breakpoints = []
self._next_expiration = datetime... | Completes all breakpoints that have been active for too long. |
def set_link(self, link,y=0,page=-1):
"Set destination of internal link"
if(y==-1):
y=self.y
if(page==-1):
page=self.page
self.links[link]=[page,y] | Set destination of internal link |
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`AllowTrust`.
"""
trustor = account_xdr_object(self.trustor)
length = len(self.asset_code)
assert length <= 12
pad_length = 4 - length if length <= 4 else 12 - length
... | Creates an XDR Operation object that represents this
:class:`AllowTrust`. |
def serialize_to_flat(self, name, datas):
"""
Serialize given datas to a flat structure ``KEY:VALUE`` where ``KEY``
comes from ``keys`` variable and ``VALUE`` comes from ``values``
variable.
This means both ``keys`` and ``values`` are required variable to be
correctly fi... | Serialize given datas to a flat structure ``KEY:VALUE`` where ``KEY``
comes from ``keys`` variable and ``VALUE`` comes from ``values``
variable.
This means both ``keys`` and ``values`` are required variable to be
correctly filled (each one is a string of item separated with an empty
... |
def macshim():
"""Shim to run 32-bit on 64-bit mac as a sub-process"""
import subprocess, sys
subprocess.call([
sys.argv[0] + '32'
]+sys.argv[1:],
env={"VERSIONER_PYTHON_PREFER_32_BIT":"yes"}
) | Shim to run 32-bit on 64-bit mac as a sub-process |
def title(self):
"""
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used.
"""
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
retur... | get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used. |
def _set_member_entry(self, v, load=False):
"""
Setter method for member_entry, mapped from YANG variable /rbridge_id/secpolicy/defined_policy/policies/member_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_entry is considered as a private
method.... | Setter method for member_entry, mapped from YANG variable /rbridge_id/secpolicy/defined_policy/policies/member_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_entry is considered as a private
method. Backends looking to populate this variable should
d... |
def readlist(self):
"""Sort the reads, and create lists to be used in creating sorted .fastq files"""
printtime('Sorting reads', self.start)
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
threads = ... | Sort the reads, and create lists to be used in creating sorted .fastq files |
def length(
cls, request,
vector: (Ptypes.body,
Vector('The vector to analyse.'))) -> [
(200, 'Ok', Float),
(400, 'Wrong vector format')]:
'''Return the modulo of a vector.'''
log.info('Computing the length of vector {}'.format(vector)... | Return the modulo of a vector. |
def auto2unicode(text):
"""
This function tries to identify encode in available encodings.
If it finds, then it will convert text into unicode string.
Author : Arulalan.T
04.08.2014
"""
_all_unique_encodes_, _all_common_encodes_ = _get_unique_common_encodes()
# get unique... | This function tries to identify encode in available encodings.
If it finds, then it will convert text into unicode string.
Author : Arulalan.T
04.08.2014 |
async def download_file(
self, input_location, file=None, *, part_size_kb=None,
file_size=None, progress_callback=None, dc_id=None):
"""
Downloads the given input location to a file.
Args:
input_location (:tl:`InputFileLocation`):
The file loc... | Downloads the given input location to a file.
Args:
input_location (:tl:`InputFileLocation`):
The file location from which the file will be downloaded.
See `telethon.utils.get_input_location` source for a complete
list of supported types.
... |
def read_job(self, job_id, checkout=False):
"""
Reads head and reads the tree into index,
and checkout the work-tree when checkout=True.
This does not fetch the job from the actual server. It needs to be in the local git already.
"""
self.job_id = job_id
commit ... | Reads head and reads the tree into index,
and checkout the work-tree when checkout=True.
This does not fetch the job from the actual server. It needs to be in the local git already. |
def on_post(self, req, resp):
""" Validate the access token request for spec compliance
The spec also dictates the JSON based error response
on failure & is handled in this responder.
"""
grant_type = req.get_param('grant_type')
password = req.get_param('password')
... | Validate the access token request for spec compliance
The spec also dictates the JSON based error response
on failure & is handled in this responder. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.