positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def expanduser(path):
"""
Args:
path (pathlike): A path to expand
Returns:
`fsnative`
Like :func:`python:os.path.expanduser` but supports unicode home
directories under Windows + Python 2 and always returns a `fsnative`.
"""
path = path2fsn(path)
if path == "~":
... | Args:
path (pathlike): A path to expand
Returns:
`fsnative`
Like :func:`python:os.path.expanduser` but supports unicode home
directories under Windows + Python 2 and always returns a `fsnative`. |
def multiply(self, p, e):
"""Multiply a point by an integer."""
e %= self.order()
if p == self._infinity or e == 0:
return self._infinity
pubkey = create_string_buffer(64)
public_pair_bytes = b'\4' + to_bytes_32(p[0]) + to_bytes_32(p[1])
r = libsecp256k1.secp2... | Multiply a point by an integer. |
def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear mainten... | Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name> |
def _designspace_locations(self, designspace):
"""Map font filenames to their locations in a designspace."""
maps = []
for elements in (designspace.sources, designspace.instances):
location_map = {}
for element in elements:
path = _normpath(element.path)
... | Map font filenames to their locations in a designspace. |
def issues(self, kind, email):
""" Filter unique issues for given activity type and email """
return list(set([unicode(activity.issue)
for activity in self.activities()
if kind == activity.kind and activity.user['email'] == email])) | Filter unique issues for given activity type and email |
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
"""Print ASCII diagram in Jupyter."""
if cycle:
# There should never be a cycle. This is just in case.
p.text('Circuit(...)')
else:
p.text(self.to_text_diagram()) | Print ASCII diagram in Jupyter. |
def get_task_var(self, key, default=None):
"""
Fetch the value of a task variable related to connection configuration,
or, if delegate_to is active, fetch the same variable via HostVars for
the delegated-to machine.
When running with delegate_to, Ansible tasks have variables ass... | Fetch the value of a task variable related to connection configuration,
or, if delegate_to is active, fetch the same variable via HostVars for
the delegated-to machine.
When running with delegate_to, Ansible tasks have variables associated
with the original machine, not the delegated-to... |
def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_... | Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. |
def _client_send(self, msg):
"""Sends an Rpc message through the connection.
Args:
msg: string, the message to send.
Raises:
Error: a socket error occurred during the send.
"""
try:
self._client.write(msg.encode("utf8") + b'\n')
s... | Sends an Rpc message through the connection.
Args:
msg: string, the message to send.
Raises:
Error: a socket error occurred during the send. |
def ensemble_res_1to1(ensemble, pst,facecolor='0.5',logger=None,filename=None,
skip_groups=[],base_ensemble=None,**kwargs):
"""helper function to plot ensemble 1-to-1 plots sbowing the simulated range
Parameters
----------
ensemble : varies
the ensemble argument can be a p... | helper function to plot ensemble 1-to-1 plots sbowing the simulated range
Parameters
----------
ensemble : varies
the ensemble argument can be a pandas.DataFrame or derived type or a str, which
is treated as a fileanme. Optionally, ensemble can be a list of these types or
a dict, i... |
def vm_state(vm_=None, **kwargs):
'''
Return list of all the vms and their state.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
:param vm_: name of the domain
:param connection: libvirt connection URI, overriding defau... | Return list of all the vms and their state.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
:param vm_: name of the domain
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:p... |
def _setup_parser(self, filename=None):
"""
Configure the ConfigParser instance the way we want it.
Args:
filename (str) or None
Returns:
SafeConfigParser
"""
assert isinstance(filename, str) or filename is None
# If we are not overridin... | Configure the ConfigParser instance the way we want it.
Args:
filename (str) or None
Returns:
SafeConfigParser |
def NEW_DEBUG_FRAME(self, requestHeader):
"""
Initialize a debug frame with requestHeader
Frame count is updated and will be attached to respond header
The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data]
Some of them may be None
"""
if ... | Initialize a debug frame with requestHeader
Frame count is updated and will be attached to respond header
The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data]
Some of them may be None |
def _execute(self,
command, # type: str
args, # type: List[str]
env_vars=None, # type: EnvVars
shim=None # type: OptStr
):
# type: (...) -> Tuple[int, bytes, bytes]
"""Execute a pip command with ... | Execute a pip command with the given arguments. |
def _attach_document(self, doc):
''' Attach a model to a Bokeh |Document|.
This private interface should only ever called by the Document
implementation to set the private ._document field properly
'''
if self._document is not None and self._document is not doc:
rai... | Attach a model to a Bokeh |Document|.
This private interface should only ever called by the Document
implementation to set the private ._document field properly |
def pairwise_ellpitical_binary(sources, eps, far=None):
"""
Do a pairwise comparison of all sources and determine if they have a normalized distance within
eps.
Form this into a matrix of shape NxN.
Parameters
----------
sources : list
A list of sources (objects with parameters: r... | Do a pairwise comparison of all sources and determine if they have a normalized distance within
eps.
Form this into a matrix of shape NxN.
Parameters
----------
sources : list
A list of sources (objects with parameters: ra,dec,a,b,pa)
eps : float
Normalised distance constrain... |
def filterflags_general_tags(tags_list, has_any=None, has_all=None,
has_none=None, min_num=None, max_num=None,
any_startswith=None, any_endswith=None,
in_any=None, any_match=None, none_match=None,
logic='... | r"""
maybe integrate into utool? Seems pretty general
Args:
tags_list (list):
has_any (None): (default = None)
has_all (None): (default = None)
min_num (None): (default = None)
max_num (None): (default = None)
Notes:
in_any should probably be ni_any
TOD... |
def solve(self, S, dimK=None):
"""Compute sparse coding and dictionary update for training
data `S`."""
# Use dimK specified in __init__ as default
if dimK is None and self.dimK is not None:
dimK = self.dimK
# Start solve timer
self.timer.start(['solve', 'so... | Compute sparse coding and dictionary update for training
data `S`. |
def set_type_by_schema(self, schema_obj, schema_type):
"""
Set property type by schema object
Schema will create, if it doesn't exists in collection
:param dict schema_obj: raw schema object
:param str schema_type:
"""
schema_id = self._get_object_schema_id(schem... | Set property type by schema object
Schema will create, if it doesn't exists in collection
:param dict schema_obj: raw schema object
:param str schema_type: |
def ray_bounds(ray_origins,
ray_directions,
bounds,
buffer_dist=1e-5):
"""
Given a set of rays and a bounding box for the volume of interest
where the rays will be passing through, find the bounding boxes
of the rays as they pass through the volume.
Para... | Given a set of rays and a bounding box for the volume of interest
where the rays will be passing through, find the bounding boxes
of the rays as they pass through the volume.
Parameters
------------
ray_origins: (m,3) float, ray origin points
ray_directions: (m,3) float, ray direction ve... |
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
in... | Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q'... |
def _batch_entry(self):
"""Entry point for the batcher thread."""
try:
while True:
self._batch_entry_run()
except:
self.exc_info = sys.exc_info()
os.kill(self.pid, signal.SIGUSR1) | Entry point for the batcher thread. |
def forward_word_extend_selection(self, e): #
u"""Move forward to the end of the next word. Words are composed of
letters and digits."""
self.l_buffer.forward_word_extend_selection(self.argument_reset)
self.finalize() | u"""Move forward to the end of the next word. Words are composed of
letters and digits. |
def _stream_raw_result(self, response, chunk_size=1, decode=True):
''' Stream result for TTY-enabled container and raw binary data'''
self._raise_for_status(response)
for out in response.iter_content(chunk_size, decode):
yield out | Stream result for TTY-enabled container and raw binary data |
def ReadAllClientGraphSeries(
self,
client_label,
report_type,
time_range = None,
):
"""See db.Database."""
series_with_timestamps = {}
for series_key, series in iteritems(self.client_graph_series):
series_label, series_type, timestamp = series_key
if series_label == cl... | See db.Database. |
def is_valid(self,
value # type: Any
):
# type: (...) -> bool
"""
Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
the validation process will be silently caught.
:param value: the val... | Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
the validation process will be silently caught.
:param value: the value to validate
:return: a boolean flag indicating success or failure |
def read(self, n):
"""
Receive *n* bytes from the socket.
Args:
n(int): The number of bytes to read.
Returns:
bytes: *n* bytes read from the socket.
Raises:
EOFError: If the socket was closed.
"""
d = b''
while n:
... | Receive *n* bytes from the socket.
Args:
n(int): The number of bytes to read.
Returns:
bytes: *n* bytes read from the socket.
Raises:
EOFError: If the socket was closed. |
def fetch_all_records(self):
r"""
Returns a generator that yields all of the DNS records for the domain
:rtype: generator of `DomainRecord`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return map(self._record, api.... | r"""
Returns a generator that yields all of the DNS records for the domain
:rtype: generator of `DomainRecord`\ s
:raises DOAPIError: if the API endpoint replies with an error |
def get_settings(self):
"""
Returns current settings.
Only accessible if authenticated as the user.
"""
url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name)
return self._imgur._send_request(url) | Returns current settings.
Only accessible if authenticated as the user. |
async def register(*address_list, cluster=None, loop=None):
"""Start Raft node (server)
Args:
address_list — 127.0.0.1:8000 [, 127.0.0.1:8001 ...]
cluster — [127.0.0.1:8001, 127.0.0.1:8002, ...]
"""
loop = loop or asyncio.get_event_loop()
for address in address_list:
host, p... | Start Raft node (server)
Args:
address_list — 127.0.0.1:8000 [, 127.0.0.1:8001 ...]
cluster — [127.0.0.1:8001, 127.0.0.1:8002, ...] |
def _get_and_start_work(self):
"return (async_result, work_unit) or (None, None)"
worker_id = nice_identifier()
work_unit = self.task_master.get_work(worker_id, available_gb=self.available_gb())
if work_unit is None:
return None, None
async_result = self.pool.apply_as... | return (async_result, work_unit) or (None, None) |
def applymap(self, func, subset=None, **kwargs):
"""
Apply a function elementwise, updating the HTML
representation with the result.
Parameters
----------
func : function
``func`` should take a scalar and return a scalar
subset : IndexSlice
... | Apply a function elementwise, updating the HTML
representation with the result.
Parameters
----------
func : function
``func`` should take a scalar and return a scalar
subset : IndexSlice
a valid indexer to limit ``data`` to *before* applying the
... |
def valueFromString(self, value, context=None):
"""
Re-implements the orb.Column.valueFromString method to
lookup a reference object based on the given value.
:param value: <str>
:param context: <orb.Context> || None
:return: <orb.Model> || None
"""
mode... | Re-implements the orb.Column.valueFromString method to
lookup a reference object based on the given value.
:param value: <str>
:param context: <orb.Context> || None
:return: <orb.Model> || None |
def __parse_drac(output):
'''
Parse Dell DRAC output
'''
drac = {}
section = ''
for i in output.splitlines():
if i.strip().endswith(':') and '=' not in i:
section = i[0:-1]
drac[section] = {}
if i.rstrip() and '=' in i:
if section in drac:
... | Parse Dell DRAC output |
def parse_hash(address):
'''
str -> bytes
There's probably a better way to do this.
'''
raw = parse(address)
# Cash addresses
try:
if address.find(riemann.network.CASHADDR_PREFIX) == 0:
if raw.find(riemann.network.CASHADDR_P2SH) == 0:
return raw[len(riem... | str -> bytes
There's probably a better way to do this. |
def delete(self):
"""Remove myself from my :class:`Character`.
For symmetry with :class:`Thing` and :class`Place`.
"""
branch, turn, tick = self.engine._nbtt()
self.engine._edges_cache.store(
self.character.name,
self.origin.name,
self.destin... | Remove myself from my :class:`Character`.
For symmetry with :class:`Thing` and :class`Place`. |
def _compute(self, arrays, dates, assets, mask):
"""
Compute our result with numexpr, then re-apply `mask`.
"""
return super(NumExprFilter, self)._compute(
arrays,
dates,
assets,
mask,
) & mask | Compute our result with numexpr, then re-apply `mask`. |
def determine_api_port(public_port, singlenode_mode=False):
'''
Determine correct API server listening port based on
existence of HTTPS reverse proxy and/or haproxy.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
... | Determine correct API server listening port based on
existence of HTTPS reverse proxy and/or haproxy.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuffle ports when only a single unit is present
returns: int: the correct listening port for the API service |
def extract_pk_blob_from_pyasn1(pyasn1_struct):
"""
Extract an ASN.1 encoded public key blob from the given :mod:`pyasn1`
structure (which must represent a certificate).
"""
pk = pyasn1_struct.getComponentByName(
"tbsCertificate"
).getComponentByName(
"subjectPublicKeyInfo"
... | Extract an ASN.1 encoded public key blob from the given :mod:`pyasn1`
structure (which must represent a certificate). |
def get_components(self, which):
"""
Get the component name dictionary for the desired object.
The returned dictionary maps component names on this class to component
names on the desired object.
Parameters
----------
which : str
Can either be ``'pos... | Get the component name dictionary for the desired object.
The returned dictionary maps component names on this class to component
names on the desired object.
Parameters
----------
which : str
Can either be ``'pos'`` or ``'vel'`` to get the components for the
... |
def _connect_database(config):
"""Create simple connection with Mongodb
config comes with settings from .ini file.
"""
settings = config.registry.settings
mongo_uri = "mongodb://localhost:27017"
mongodb_name = "test"
if settings.get("mongo_url"):
mongo_uri = settings["mongo_url"]
... | Create simple connection with Mongodb
config comes with settings from .ini file. |
def change_location(self, old_location_name, new_location_name, new_parent_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False):
"""
Find actual data object for location with old_location_name.
Then call Location class change method to update location name... | Find actual data object for location with old_location_name.
Then call Location class change method to update location name and data. |
def cdn_request(self, uri, method, *args, **kwargs):
"""
If the service supports CDN, use this method to access CDN-specific
URIs.
"""
if not self.cdn_management_url:
raise exc.NotCDNEnabled("CDN is not enabled for this service.")
cdn_uri = "%s%s" % (self.cdn_... | If the service supports CDN, use this method to access CDN-specific
URIs. |
def node_str(node):
"""
Returns the complete menu entry text for a menu node, or "" for invisible
menu nodes. Invisible menu nodes are those that lack a prompt or that do
not have a satisfied prompt condition.
Example return value: "[*] Bool symbol (BOOL)"
The symbol name is printed in parenth... | Returns the complete menu entry text for a menu node, or "" for invisible
menu nodes. Invisible menu nodes are those that lack a prompt or that do
not have a satisfied prompt condition.
Example return value: "[*] Bool symbol (BOOL)"
The symbol name is printed in parentheses to the right of the prompt.... |
def append_child(self, child):
"""
Equivalent to 'node.children.append(child)'. This method also sets the
child's parent attribute appropriately.
"""
child.parent = self
self.children.append(child)
self.changed() | Equivalent to 'node.children.append(child)'. This method also sets the
child's parent attribute appropriately. |
def determine_frame_positions(self):
"""Record the file pointer position of each frame"""
self.rewind_file()
with ignored(struct.error):
while True:
pointer_position = self.blob_file.tell()
length = struct.unpack('<i', self.blob_file.read(4))[0]
... | Record the file pointer position of each frame |
def sentiment(self):
"""
The sentiment of this sentence
:getter: Returns the sentiment value of this sentence
:type: int
"""
if self._sentiment is None:
self._sentiment = int(self._element.get('sentiment'))
return self._sentiment | The sentiment of this sentence
:getter: Returns the sentiment value of this sentence
:type: int |
def from_string(cls, string, version):
"""
Constructs an ARC record from a string and returns it.
TODO: It might be best to merge this with the _read_arc_record
function rather than reimplement the functionality here.
"""
header, payload = string.split("\n",1)
... | Constructs an ARC record from a string and returns it.
TODO: It might be best to merge this with the _read_arc_record
function rather than reimplement the functionality here. |
async def setnym(ini_path: str) -> int:
"""
Set configuration. Open pool, trustee anchor, and wallet of anchor whose nym to send.
Register exit hooks to close pool and trustee anchor.
Engage trustee anchor to send nym for VON anchor, if it differs on the ledger from configuration.
:param ini_path:... | Set configuration. Open pool, trustee anchor, and wallet of anchor whose nym to send.
Register exit hooks to close pool and trustee anchor.
Engage trustee anchor to send nym for VON anchor, if it differs on the ledger from configuration.
:param ini_path: path to configuration file
:return: 0 for OK, 1... |
def p_state_action_constraint_section(self, p):
'''state_action_constraint_section : STATE_ACTION_CONSTRAINTS LCURLY state_cons_list RCURLY SEMI
| STATE_ACTION_CONSTRAINTS LCURLY RCURLY SEMI'''
if len(p) == 6:
p[0] = ('constraints', p[3])
el... | state_action_constraint_section : STATE_ACTION_CONSTRAINTS LCURLY state_cons_list RCURLY SEMI
| STATE_ACTION_CONSTRAINTS LCURLY RCURLY SEMI |
def extract_labels(self, f, one_hot=False, num_classes=10):
"""Extract the labels into a 1D uint8 numpy array [index].
Args:
f: A file object that can be passed into a gzip reader.
one_hot: Does one hot encoding for the result.
num_classes: Number of classes for the one hot... | Extract the labels into a 1D uint8 numpy array [index].
Args:
f: A file object that can be passed into a gzip reader.
one_hot: Does one hot encoding for the result.
num_classes: Number of classes for the one hot encoding.
Returns:
labels: a 1D unit8 numpy array.
... |
def zotero_inline_tags(parser, token):
"""
Render an inline formset of tags.
Usage:
{% zotero_inline_tags formset[ option] %}
option = "all" | "media" | "formset"
"""
args = token.split_contents()
length = len(args)
if length == 2:
rendered_node = RenderedAl... | Render an inline formset of tags.
Usage:
{% zotero_inline_tags formset[ option] %}
option = "all" | "media" | "formset" |
def mpi_submit(nslave, worker_args, worker_envs):
"""
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arg... | customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arguments to launch each job
this usually includes th... |
def plot_attention(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], filename: str):
"""
Uses matplotlib for creating a visualization of the attention matrix.
:param attention_matrix: The attention matrix.
:param source_tokens: A list of source tokens.
:param target_... | Uses matplotlib for creating a visualization of the attention matrix.
:param attention_matrix: The attention matrix.
:param source_tokens: A list of source tokens.
:param target_tokens: A list of target tokens.
:param filename: The file to which the attention visualization will be written to. |
def base64_bytes(x):
"""Turn base64 into bytes"""
if six.PY2:
return base64.decodestring(x)
return base64.decodebytes(bytes_encode(x)) | Turn base64 into bytes |
def socket_handler(name, logname, host, port):
"""
A Bark logging handler logging output to a stream (TCP) socket.
The server listening at the given 'host' and 'port' will be sent a
pickled dictionary.
Similar to logging.handlers.SocketHandler.
"""
return wrap_log_handler(logging.handlers.... | A Bark logging handler logging output to a stream (TCP) socket.
The server listening at the given 'host' and 'port' will be sent a
pickled dictionary.
Similar to logging.handlers.SocketHandler. |
def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in MongoDB with specified key.
"""
mongo_key = self._format_mongo_key(hash_name, bucket_key)
val_dict = {}
val_dict['lsh'] = mongo_key
# Depending on type (spars... | Stores vector and JSON-serializable data in MongoDB with specified key. |
def flush(self):
"""Flush all pending gauges"""
writer = self.writer
if writer is None:
raise GaugedUseAfterFreeError
self.flush_writer_position()
keys = self.translate_keys()
blocks = []
current_block = self.current_block
statistics = self.sta... | Flush all pending gauges |
def wrap(self, value):
''' Expects a dictionary with the keys being instances of ``KVField.key_type``
and the values being instances of ``KVField.value_type``. After validation,
the dictionary is transformed into a list of dictionaries with ``k`` and ``v``
fields set to the ... | Expects a dictionary with the keys being instances of ``KVField.key_type``
and the values being instances of ``KVField.value_type``. After validation,
the dictionary is transformed into a list of dictionaries with ``k`` and ``v``
fields set to the keys and values from the original d... |
def remap(input, keys, values, missing='ignore', inplace=False):
"""Given an input array, remap its entries corresponding to 'keys' to 'values'
equivalent of output = [map.get(i, default=i) for i in input],
if map were a dictionary of corresponding keys and values
Parameters
----------
input : ... | Given an input array, remap its entries corresponding to 'keys' to 'values'
equivalent of output = [map.get(i, default=i) for i in input],
if map were a dictionary of corresponding keys and values
Parameters
----------
input : ndarray, [...]
values to perform replacements in
keys : ndar... |
def libvlc_video_set_teletext(p_mi, i_page):
'''Set new teletext page to retrieve.
@param p_mi: the media player.
@param i_page: teletex page number requested.
'''
f = _Cfunctions.get('libvlc_video_set_teletext', None) or \
_Cfunction('libvlc_video_set_teletext', ((1,), (1,),), None,
... | Set new teletext page to retrieve.
@param p_mi: the media player.
@param i_page: teletex page number requested. |
def duration_expired(start_time, duration_seconds):
"""
Return True if ``duration_seconds`` have expired since ``start_time``
"""
if duration_seconds is not None:
delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time)
if delta_seconds >= duration_seconds:
... | Return True if ``duration_seconds`` have expired since ``start_time`` |
def docker_to_uuid(uuid):
'''
Get the image uuid from an imported docker image
.. versionadded:: 2019.2.0
'''
if _is_uuid(uuid):
return uuid
if _is_docker_uuid(uuid):
images = list_installed(verbose=True)
for image_uuid in images:
if 'name' not in images[imag... | Get the image uuid from an imported docker image
.. versionadded:: 2019.2.0 |
def list_insert(lst, new_elements, index_or_name=None, after=True):
"""
Return a copy of the list with the new element(s) inserted.
Args:
lst (list): The original list.
new_elements ("any" or list of "any"): The element(s) to insert in the list.
index_or_name (int or str): The value... | Return a copy of the list with the new element(s) inserted.
Args:
lst (list): The original list.
new_elements ("any" or list of "any"): The element(s) to insert in the list.
index_or_name (int or str): The value of the reference element, or directly its numeric index.
... |
def config(name='ckeditor', custom_config='', **kwargs):
"""Config CKEditor.
:param name: The target input field's name. If you use Flask-WTF/WTForms, it need to set
to field's name. Default to ``'ckeditor'``.
:param custom_config: The addition config, for example ``uiColor: '#9AB8F... | Config CKEditor.
:param name: The target input field's name. If you use Flask-WTF/WTForms, it need to set
to field's name. Default to ``'ckeditor'``.
:param custom_config: The addition config, for example ``uiColor: '#9AB8F3'``.
The proper syntax for each option is ``configurati... |
def set_menu(self, ):
"""Setup the menu that the menu_tb button uses
:returns: None
:rtype: None
:raises: None
"""
self.menu = QtGui.QMenu(self)
actions = self.reftrack.get_additional_actions()
self.actions = []
for a in actions:
if a.... | Setup the menu that the menu_tb button uses
:returns: None
:rtype: None
:raises: None |
def authAddress(val):
"""
# The C1 Tag
extracts the address of the authors as given by WOS. **Warning** the mapping of author to address is not very good and is given in multiple ways.
# Parameters
_val_: `list[str]`
> The raw data from a WOS file
# Returns
`list[str]`
> A lis... | # The C1 Tag
extracts the address of the authors as given by WOS. **Warning** the mapping of author to address is not very good and is given in multiple ways.
# Parameters
_val_: `list[str]`
> The raw data from a WOS file
# Returns
`list[str]`
> A list of addresses |
def new_value(self, name, value):
"""Create new value in data"""
try:
# We need to enclose values in a list to be able to send
# them to the kernel in Python 2
svalue = [cloudpickle.dumps(value, protocol=PICKLE_PROTOCOL)]
# Needed to prevent memory... | Create new value in data |
def sequence_cross_entropy_with_logits(logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: torch.FloatTensor,
average: str = "batch",
label_smoothing: fl... | Computes the cross entropy loss of a sequence, weighted with respect to
some user provided weights. Note that the weighting here is not the same as
in the :func:`torch.nn.CrossEntropyLoss()` criterion, which is weighting
classes; here we are weighting the loss contribution from particular elements
in th... |
def taql(command, style='Python', tables=[], globals={}, locals={}):
"""Execute a TaQL command and return a table object.
A `TaQL <../../doc/199.html>`_
command is an SQL-like command to do a selection of rows and/or
columns in a table.
The default style used in a TaQL command is python, which mea... | Execute a TaQL command and return a table object.
A `TaQL <../../doc/199.html>`_
command is an SQL-like command to do a selection of rows and/or
columns in a table.
The default style used in a TaQL command is python, which means 0-based
indexing, C-ordered arrays, and non-inclusive end in ranges.
... |
def save(self):
"""Write the store dict to a file specified by store_file_path"""
with open(self.store_file_path, 'w') as fh:
fh.write(json.dumps(self.store, indent=4)) | Write the store dict to a file specified by store_file_path |
def send_external(self, http_verb, host, url, http_headers, chunk):
"""
Used with create_upload_url to send a chunk the the possibly external object store.
:param http_verb: str PUT or POST
:param host: str host we are sending the chunk to
:param url: str url to use when sending
... | Used with create_upload_url to send a chunk the the possibly external object store.
:param http_verb: str PUT or POST
:param host: str host we are sending the chunk to
:param url: str url to use when sending
:param http_headers: object headers to send with the request
:param chun... |
def watch_docs(c):
"""
Watch both doc trees & rebuild them if files change.
This includes e.g. rebuilding the API docs if the source code changes;
rebuilding the WWW docs if the README changes; etc.
Reuses the configuration values ``packaging.package`` or ``tests.package``
(the former winning ... | Watch both doc trees & rebuild them if files change.
This includes e.g. rebuilding the API docs if the source code changes;
rebuilding the WWW docs if the README changes; etc.
Reuses the configuration values ``packaging.package`` or ``tests.package``
(the former winning over the latter if both defined... |
def iiif_info_handler(prefix=None, identifier=None,
config=None, klass=None, auth=None, **args):
"""Handler for IIIF Image Information requests."""
if (not auth or degraded_request(identifier) or auth.info_authz()):
# go ahead with request as made
if (auth):
log... | Handler for IIIF Image Information requests. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'fields') and self.fields is not None:
_dict['fields'] = [x._to_dict() for x in self.fields]
return _dict | Return a json dictionary representing this model. |
def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None):
'''
Delete a pipeline, its pipeline definition, and its run history. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.delete_pipeline my_pipeline_id
'''
cli... | Delete a pipeline, its pipeline definition, and its run history. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.delete_pipeline my_pipeline_id |
def get_facts(self, date, end_date=None, search_terms="", ongoing_days=0):
"""Returns facts for the time span matching the optional filter criteria.
In search terms comma (",") translates to boolean OR and space (" ")
to boolean AND.
Filter is applied to tags, categories, activi... | Returns facts for the time span matching the optional filter criteria.
In search terms comma (",") translates to boolean OR and space (" ")
to boolean AND.
Filter is applied to tags, categories, activity names and description
ongoing_days (int): look into the last `ongoing_da... |
def system_monitor_LineCard_alert_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
LineCard = ET.SubElement(system_monitor, "LineCard")
... | Auto Generated Code |
def _registerHandler(self, handler):
"""
Registers a handler.
:param handler: A handler object.
"""
self._logger.addHandler(handler)
self._handlers.append(handler) | Registers a handler.
:param handler: A handler object. |
def from_jsonld(cls, data, __reference__=None, __source__=None):
"""Instantiate a JSON-LD class from data."""
if isinstance(data, cls):
return data
if not isinstance(data, dict):
raise ValueError(data)
if '@type' in data:
type_ = tuple(sorted(data['@... | Instantiate a JSON-LD class from data. |
def purge(self, name=None):
"""
Disconnect from the given database and remove from local cache
:param name: The name of the connection
:type name: str
:rtype: None
"""
self.disconnect(name)
if name in self._connections:
del self._connections... | Disconnect from the given database and remove from local cache
:param name: The name of the connection
:type name: str
:rtype: None |
def MakeZip(self, input_dir, output_file):
"""Creates a ZIP archive of the files in the input directory.
Args:
input_dir: the name of the input directory.
output_file: the name of the output ZIP archive without extension.
"""
logging.info("Generating zip template file at %s", output_file)
... | Creates a ZIP archive of the files in the input directory.
Args:
input_dir: the name of the input directory.
output_file: the name of the output ZIP archive without extension. |
def probe_git():
"""Return a git repository instance if it exists."""
try:
repo = git.Repo()
except git.InvalidGitRepositoryError:
LOGGER.warning(
"We highly recommend keeping your model in a git repository."
" It allows you to track changes and to easily collaborate ... | Return a git repository instance if it exists. |
def get_upstream_artifacts_full_paths_per_task_id(context):
"""List the downloaded upstream artifacts.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict, dict: lists of the paths to upstream artifacts, sorted by task_id.
First dict represents... | List the downloaded upstream artifacts.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict, dict: lists of the paths to upstream artifacts, sorted by task_id.
First dict represents the existing upstream artifacts. The second one
maps t... |
def get_annotationdefault(self):
"""
The AnnotationDefault attribute, only present upon fields in an
annotaion.
reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20
""" # noqa
buff = self.get_attribute("AnnotationDefault")
if buf... | The AnnotationDefault attribute, only present upon fields in an
annotaion.
reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20 |
def store_array_elements(self, array, start_idx, data):
"""
Stores either a single element or a range of elements in the array.
:param array: Reference to the array.
:param start_idx: Starting index for the store.
:param data: Either a single value or a list of values.
... | Stores either a single element or a range of elements in the array.
:param array: Reference to the array.
:param start_idx: Starting index for the store.
:param data: Either a single value or a list of values. |
def get_airport_weather(self, iata, page=1, limit=100):
"""Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for u... | Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher p... |
def apply_norm(x, norm_type, depth, epsilon, layer_collection=None):
"""Apply Normalization."""
if layer_collection is not None:
assert norm_type == "layer"
if norm_type == "layer":
return layer_norm(
x, filters=depth, epsilon=epsilon, layer_collection=layer_collection)
if norm_type == "group":
... | Apply Normalization. |
def getAuthenticatedRole(store):
"""
Get the base 'Authenticated' role for this store, which is the role that is
given to every user who is explicitly identified by a non-anonymous
username.
"""
def tx():
def addToEveryone(newAuthenticatedRole):
newAuthenticatedRole.becomeMem... | Get the base 'Authenticated' role for this store, which is the role that is
given to every user who is explicitly identified by a non-anonymous
username. |
def get_resource_children(raml_resource):
""" Get children of :raml_resource:.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
"""
path = raml_resource.path
return [res for res in raml_resource.root.resources
if res.parent and res.parent.path == path] | Get children of :raml_resource:.
:param raml_resource: Instance of ramlfications.raml.ResourceNode. |
def Struct_plot(lS, lax=None, proj='all', element=None, dP=None,
dI=None, dBs=None, dBv=None,
dVect=None, dIHor=None, dBsHor=None, dBvHor=None,
Lim=None, Nstep=None, dLeg=None, indices=False,
draw=True, fs=None, wintit=None, tit=None, Test=True):
""" P... | Plot the projections of a list of Struct subclass instances
D. VEZINET, Aug. 2014
Inputs :
V A Ves instance
Nstep An int (the number of points for evaluation of theta by np.linspace)
axP A plt.Axes instance (if given) on which to plot the poloidal projection, othe... |
def refresh_timer_cb(self, timer, flags):
"""Refresh timer callback.
This callback will normally only be called internally.
Parameters
----------
timer : a Ginga GUI timer
A GUI-based Ginga timer
flags : dict-like
A set of flags controlling the t... | Refresh timer callback.
This callback will normally only be called internally.
Parameters
----------
timer : a Ginga GUI timer
A GUI-based Ginga timer
flags : dict-like
A set of flags controlling the timer |
def pause(self):
"""Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`.
"""
for client in self._snippet_clients.values():
self._device.log.debug(
'Clearing host port ... | Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`. |
def get_storage(self, contract_hash, storage_key, id=None, endpoint=None):
"""
Returns a storage item of a specified contract
Args:
contract_hash: (str) hash of the contract to lookup, for example 'd7678dd97c000be3f33e9362e673101bac4ca654'
storage_key: (str) storage key t... | Returns a storage item of a specified contract
Args:
contract_hash: (str) hash of the contract to lookup, for example 'd7678dd97c000be3f33e9362e673101bac4ca654'
storage_key: (str) storage key to lookup, for example 'totalSupply'
id: (int, optional) id to use for response trac... |
def updateWritingTone(user, writingTone, maintainHistory):
"""
updateWritingTone updates the user with the writing tones interpreted based
on the specified thresholds
@param: user a json object representing user information (tone) to be used
in conversing with the Conversation Service
@param: wr... | updateWritingTone updates the user with the writing tones interpreted based
on the specified thresholds
@param: user a json object representing user information (tone) to be used
in conversing with the Conversation Service
@param: writingTone a json object containing the writing tones in the
payload... |
def getSiblings(self, textId, subreference: CtsReference):
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage CtsReference
:type subreference: str
:return: Tuple of references
... | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage CtsReference
:type subreference: str
:return: Tuple of references
:rtype: (str, str) |
def file_transfer(
ssh_conn,
source_file,
dest_file,
file_system=None,
direction="put",
disable_md5=False,
inline_transfer=False,
overwrite_file=False,
):
"""Use Secure Copy or Inline (IOS-only) to transfer files to/from network devices.
inline_transfer ONLY SUPPORTS TEXT FILES ... | Use Secure Copy or Inline (IOS-only) to transfer files to/from network devices.
inline_transfer ONLY SUPPORTS TEXT FILES and will not support binary file transfers.
return {
'file_exists': boolean,
'file_transferred': boolean,
'file_verified': boolean,
} |
def json_encode_default(obj):
'''
Convert datetime.datetime to timestamp
:param obj: value to (possibly) convert
'''
if isinstance(obj, (datetime, date)):
result = dt2ts(obj)
else:
result = json_encoder.default(obj)
return to_encoding(result) | Convert datetime.datetime to timestamp
:param obj: value to (possibly) convert |
def _create_and_update(self):
"""
Create or update request, re-read object from Artifactory
:return: None
"""
data_json = self._create_json()
data_json.update(self.additional_params)
request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._ur... | Create or update request, re-read object from Artifactory
:return: None |
def removeconfounds(self, confounds=None, clean_params=None, transpose=None, njobs=None, update_pipeline=True, overwrite=True, tag=None):
"""
Removes specified confounds using nilearn.signal.clean
Parameters
----------
confounds : list
List of confounds. Can be presp... | Removes specified confounds using nilearn.signal.clean
Parameters
----------
confounds : list
List of confounds. Can be prespecified in set_confounds
clean_params : dict
Dictionary of kawgs to pass to nilearn.signal.clean
transpose : bool (default False)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.