code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _parse_chemical_equation(value):
"""
Parse the chemical equation mini-language.
See the docstring of `ChemicalEquation` for more.
Parameters
----------
value : `str`
A string in chemical equation mini-language.
Returns
-------
mapping
A mapping in the format sp... | Parse the chemical equation mini-language.
See the docstring of `ChemicalEquation` for more.
Parameters
----------
value : `str`
A string in chemical equation mini-language.
Returns
-------
mapping
A mapping in the format specified by the mini-language (see notes on
... |
def create(cls, name, input_speed=None, learn_dns_automatically=True,
output_speed=None, provider_name=None, probe_address=None,
standby_mode_period=3600, standby_mode_timeout=30,
active_mode_period=5, active_mode_timeout=1, comment=None):
"""
Create a Dynami... | Create a Dynamic Netlink.
:param str name: name of netlink Element
:param int input_speed: input speed in Kbps, used for ratio-based
load-balancing
:param int output_speed: output speed in Kbps, used for ratio-based
load-balancing
:param bool learn_dns_automatic... |
def getpath(element):
"""Get full path of a given element such as the opposite of the
resolve_path behaviour.
:param element: must be directly defined into a module or a package and has
the attribute '__name__'.
:return: element absolute path.
:rtype: str
:raises AttributeError: if el... | Get full path of a given element such as the opposite of the
resolve_path behaviour.
:param element: must be directly defined into a module or a package and has
the attribute '__name__'.
:return: element absolute path.
:rtype: str
:raises AttributeError: if element has not the attribute _... |
def _parse_repo_file(filename):
'''
Turn a single repo file into a dict
'''
parsed = configparser.ConfigParser()
config = {}
try:
parsed.read(filename)
except configparser.MissingSectionHeaderError as err:
log.error(
'Failed to parse file %s, error: %s',
... | Turn a single repo file into a dict |
def process_save(X, y, tokenizer, proc_data_path, max_len=400, train=False, ngrams=None, limit_top_tokens=None):
"""Process text and save as Dataset
"""
if train and limit_top_tokens is not None:
tokenizer.apply_encoding_options(limit_top_tokens=limit_top_tokens)
X_encoded = tokenizer.encode_te... | Process text and save as Dataset |
def get_mesh_hcurves(oqparam):
"""
Read CSV data in the format `lon lat, v1-vN, w1-wN, ...`.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
the mesh of points and the data as a dictionary
imt -> array of curves for each site
"""
i... | Read CSV data in the format `lon lat, v1-vN, w1-wN, ...`.
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:returns:
the mesh of points and the data as a dictionary
imt -> array of curves for each site |
def _formatVals(self, val_list):
"""Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text.
"""
vals = []
for (name, val) i... | Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text. |
def _create_optObject(self, **kwargs):
""" Make MINUIT or NewMinuit type optimizer object """
optimizer = kwargs.get('optimizer',
self.config['optimizer']['optimizer'])
if optimizer.upper() == 'MINUIT':
optObject = pyLike.Minuit(self.like.logLike)
... | Make MINUIT or NewMinuit type optimizer object |
def restore(source, offset):
"""
Restore a smudged file from .bytes_backup
"""
backup_location = os.path.join(
os.path.dirname(os.path.abspath(source)), source + '.bytes_backup')
click.echo('Reading backup from: {location}'.format(location=backup_location))
if not os.path.isfile(bac... | Restore a smudged file from .bytes_backup |
def commit_operation( self, input_op_data, accepted_nameop, current_block_number ):
"""
Commit an operation, thereby carrying out a state transition.
Returns a dict with the new db record fields
"""
# have to have read-write disposition
if self.disposition != DISPOS... | Commit an operation, thereby carrying out a state transition.
Returns a dict with the new db record fields |
def put(self, session):
"""Return a session to the pool.
Never blocks: if the pool is full, raises.
:type session: :class:`~google.cloud.spanner_v1.session.Session`
:param session: the session being returned.
:raises: :exc:`six.moves.queue.Full` if the queue is full.
... | Return a session to the pool.
Never blocks: if the pool is full, raises.
:type session: :class:`~google.cloud.spanner_v1.session.Session`
:param session: the session being returned.
:raises: :exc:`six.moves.queue.Full` if the queue is full. |
def _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top):
"""
Checks if numeric parameter is within given range
"""
err_msg = "%s must be between %i and %i"
if variable_value < range_bottom or variable_value > range_top:
raise ToolkitError(err_msg % (variable_n... | Checks if numeric parameter is within given range |
def env_problem(env_problem_name, **kwargs):
"""Get and initialize the `EnvProblem` with the given name and batch size.
Args:
env_problem_name: string name of the registered env problem.
**kwargs: forwarded to env problem's initialize method.
Returns:
an initialized EnvProblem with the given batch s... | Get and initialize the `EnvProblem` with the given name and batch size.
Args:
env_problem_name: string name of the registered env problem.
**kwargs: forwarded to env problem's initialize method.
Returns:
an initialized EnvProblem with the given batch size. |
def BT(cpu, dest, src):
"""
Bit Test.
Selects the bit in a bit string (specified with the first operand, called the bit base) at the
bit-position designated by the bit offset (specified by the second operand) and stores the value
of the bit in the CF flag. The bit base operand c... | Bit Test.
Selects the bit in a bit string (specified with the first operand, called the bit base) at the
bit-position designated by the bit offset (specified by the second operand) and stores the value
of the bit in the CF flag. The bit base operand can be a register or a memory location; the b... |
def transplant(exif_src, image, new_file=None):
"""
py:function:: piexif.transplant(filename1, filename2)
Transplant exif from filename1 to filename2.
:param str filename1: JPEG
:param str filename2: JPEG
"""
if exif_src[0:2] == b"\xff\xd8":
src_data = exif_src
else:
wi... | py:function:: piexif.transplant(filename1, filename2)
Transplant exif from filename1 to filename2.
:param str filename1: JPEG
:param str filename2: JPEG |
def add_property(attribute, type):
"""Add a property to a class
"""
def decorator(cls):
"""Decorator
"""
private = "_" + attribute
def getAttr(self):
"""Property getter
"""
if getattr(self, private) is None:
setattr(self, p... | Add a property to a class |
def status(self, job_ids):
"""Get the status of a list of jobs identified by their ids.
Parameters
----------
job_ids : list of str
Identifiers for the jobs.
Returns
-------
list of int
The status codes of the requsted jobs.
"""
... | Get the status of a list of jobs identified by their ids.
Parameters
----------
job_ids : list of str
Identifiers for the jobs.
Returns
-------
list of int
The status codes of the requsted jobs. |
def sample(self, batch_size):
"""Sample a batch of experiences.
Parameters
----------
batch_size: int
How many transitions to sample.
Returns
-------
obs_batch: np.array
batch of observations
act_batch: np.array
batch ... | Sample a batch of experiences.
Parameters
----------
batch_size: int
How many transitions to sample.
Returns
-------
obs_batch: np.array
batch of observations
act_batch: np.array
batch of actions executed given obs_batch
... |
def min_distance_single(self,
mesh,
transform=None,
return_name=False,
return_data=False):
"""
Get the minimum distance between a single object and any
object in the manager.
... | Get the minimum distance between a single object and any
object in the manager.
Parameters
---------------
mesh : Trimesh object
The geometry of the collision object
transform : (4,4) float
Homogenous transform matrix for the object
return_names : boo... |
def clustering_coef_wd(W):
'''
The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted directed connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector
... | The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted directed connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector
Notes
-----
Methodological n... |
def inverse(self):
"""Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform.
"""
inv_rot = np.linalg.inv(self.rotation)
inv_scale = 1.0 / self.scale
inv_trans = -inv_sc... | Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform. |
def plotChIds(self, maptype=None, modout=False):
"""Print the channel numbers on the plotting display
Note:
---------
This method will behave poorly if you are plotting in
mixed projections. Because the channel vertex polygons
are already projected using self.defaultMap,... | Print the channel numbers on the plotting display
Note:
---------
This method will behave poorly if you are plotting in
mixed projections. Because the channel vertex polygons
are already projected using self.defaultMap, applying
this function when plotting in a different... |
def edit(self, changelist=0):
"""Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
command = 'reopen' if self.action in ('add', 'edit') else 'edit'
if int(changelist):
self._connect... | Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist` |
async def send_text_message_to_all_interfaces(self, *args, **kwargs):
"""
TODO:
we should know from where user has come and use right interface
as well right interface can be chosen
:param args:
:param kwargs:
:return:
"""
logger.debug('async_send... | TODO:
we should know from where user has come and use right interface
as well right interface can be chosen
:param args:
:param kwargs:
:return: |
def merge_settings(settings, new_metadata_settings):
"""
Will update the settings with the provided new settings data extracted from the IdP metadata
:param settings: Current settings dict data
:type settings: string
:param new_metadata_settings: Settings to be merged (extracted ... | Will update the settings with the provided new settings data extracted from the IdP metadata
:param settings: Current settings dict data
:type settings: string
:param new_metadata_settings: Settings to be merged (extracted from IdP metadata after parsing)
:type new_metadata_settings: str... |
def service_restarted_since(self, sentry_unit, mtime, service,
pgrep_full=None, sleep_time=20,
retry_count=30, retry_sleep_time=10):
"""Check if service was been started after a given time.
Args:
sentry_unit (sentry): The sentry ... | Check if service was been started after a given time.
Args:
sentry_unit (sentry): The sentry unit to check for the service on
mtime (float): The epoch time to check against
service (string): service name to look for in process table
pgrep_full: [Deprecated] Use full comm... |
def getent(refresh=False, root=None):
'''
Return the list of all info for all users
refresh
Force a refresh of user information
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' user.getent
'''
if 'user.getent' in __context__ and not re... | Return the list of all info for all users
refresh
Force a refresh of user information
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' user.getent |
def mapTrace(trace, net, delta, verbose=False):
"""
matching a list of 2D positions to consecutive edges in a network
"""
result = []
paths = {}
if verbose:
print("mapping trace with %s points" % len(trace))
for pos in trace:
newPaths = {}
candidates = net.getNeighbor... | matching a list of 2D positions to consecutive edges in a network |
def process_for_rdns(self):
"""Look through my input stream for the fields in ip_field_list and
try to do a reverse dns lookup on those fields.
"""
# For each packet process the contents
for item in self.input_stream:
# Do for both the src and dst
for... | Look through my input stream for the fields in ip_field_list and
try to do a reverse dns lookup on those fields. |
def _get_json(self,
path,
params=None,
base=JIRA_BASE_URL,
):
"""Get the json for a given path and params.
:param path: The subpath required
:type path: str
:param params: Parameters to filter the json query.
... | Get the json for a given path and params.
:param path: The subpath required
:type path: str
:param params: Parameters to filter the json query.
:type params: Optional[Dict[str, Any]]
:param base: The Base JIRA URL, defaults to the instance base.
:type base: Optional[str]... |
def embed_ising(source_linear, source_quadratic, embedding, target_adjacency, chain_strength=1.0):
"""Embeds a logical Ising model onto another graph via an embedding.
Args:
source_linear (dict): The linear biases to be embedded. Should be a dict of
the form {v: bias, ...} where v is a vari... | Embeds a logical Ising model onto another graph via an embedding.
Args:
source_linear (dict): The linear biases to be embedded. Should be a dict of
the form {v: bias, ...} where v is a variable in the source model
and bias is the linear bias associated with v.
source_quadrat... |
def clear_lock(clear_func, role, remote=None, lock_type='update'):
'''
Function to allow non-fileserver functions to clear update locks
clear_func
A function reference. This function will be run (with the ``remote``
param as an argument) to clear the lock, and must return a 2-tuple of
... | Function to allow non-fileserver functions to clear update locks
clear_func
A function reference. This function will be run (with the ``remote``
param as an argument) to clear the lock, and must return a 2-tuple of
lists, one containing messages describing successfully cleared locks,
... |
def previous_track(self):
"""Send previous track command to receiver command via HTTP post."""
# Use previous track button only for sources which support NETAUDIO
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurUp",
"cmd1": ... | Send previous track command to receiver command via HTTP post. |
def _parse_account_information(self, rows):
"""
Parses the character's account information
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`, optional
A list of all rows contained in the table.
"""
acc_info = {}
if not rows:
... | Parses the character's account information
Parameters
----------
rows: :class:`list` of :class:`bs4.Tag`, optional
A list of all rows contained in the table. |
def _toComparableValue(self, value):
"""
Trivial wrapper which takes into account the possibility that our sort
column might not have defined the C{toComparableValue} method.
This can probably serve as a good generic template for some
infrastructure to deal with arbitrarily-pote... | Trivial wrapper which takes into account the possibility that our sort
column might not have defined the C{toComparableValue} method.
This can probably serve as a good generic template for some
infrastructure to deal with arbitrarily-potentially-missing methods
from certain versions of ... |
def tracebacks_from_file(fileobj, reverse=False):
"""Generator that yields tracebacks found in a file object
With reverse=True, searches backwards from the end of the file.
"""
if reverse:
lines = deque()
for line in BackwardsReader(fileobj):
lines.appendleft(line)
... | Generator that yields tracebacks found in a file object
With reverse=True, searches backwards from the end of the file. |
def change_vlan_id(self, vlan_id):
"""
Change a VLAN id for an inline interface.
:param str vlan_id: New VLAN id. Can be in format '1-2' or
a single numerical value. If in '1-2' format, this specifies
the vlan ID for the first inline interface and the rightmost
... | Change a VLAN id for an inline interface.
:param str vlan_id: New VLAN id. Can be in format '1-2' or
a single numerical value. If in '1-2' format, this specifies
the vlan ID for the first inline interface and the rightmost
for the second.
:return: None |
def parse_tibia_date(date_str) -> Optional[datetime.date]:
"""Parses a date from the format used in Tibia.com
Accepted format:
- ``MMM DD YYYY``, e.g. ``Jul 23 2015``
Parameters
-----------
date_str: :class:`str`
The date as represented in Tibia.com
Returns
-----------
:c... | Parses a date from the format used in Tibia.com
Accepted format:
- ``MMM DD YYYY``, e.g. ``Jul 23 2015``
Parameters
-----------
date_str: :class:`str`
The date as represented in Tibia.com
Returns
-----------
:class:`datetime.date`, optional
The represented date. |
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangu... | Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of ... |
def run_and_measure(self, quil_program: Program, qubits: List[int] = None, trials: int = 1,
memory_map: Any = None) -> np.ndarray:
"""
Run a Quil program once to determine the final wavefunction, and measure multiple times.
Alternatively, consider using ``wavefunction`` ... | Run a Quil program once to determine the final wavefunction, and measure multiple times.
Alternatively, consider using ``wavefunction`` and calling ``sample_bitstrings`` on the
resulting object.
For a large wavefunction and a low-medium number of trials, use this function.
On the other... |
def a_neg(self):
'''
Negative antipodal point on the major axis, Point class.
'''
na = Point(self.center)
if self.xAxisIsMajor:
na.x -= self.majorRadius
else:
na.y -= self.majorRadius
return na | Negative antipodal point on the major axis, Point class. |
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
region=None, key=None, keyid=None, profile=None):
'''
Encrypt plaintext into cipher text using specified key.
CLI example::
salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}'
... | Encrypt plaintext into cipher text using specified key.
CLI example::
salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}' |
def sync_camera_gyro_manual(image_sequence, image_timestamps, gyro_data, gyro_timestamps, full_output=False):
"""Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image d... | Get time offset that aligns image timestamps with gyro timestamps.
Given an image sequence, and gyroscope data, with their respective timestamps,
calculate the offset that aligns the image data with the gyro data.
The timestamps must only differ by an offset, not a scale factor.
This function find... |
def is_kibana_cache_incomplete(self, es_cache, k_cache):
"""Test if k_cache is incomplete
Assume k_cache is always correct, but could be missing new
fields that es_cache has
"""
# convert list into dict, with each item's ['name'] as key
k_dict = {}
for field in k... | Test if k_cache is incomplete
Assume k_cache is always correct, but could be missing new
fields that es_cache has |
def clean_markup(self, orig_str):
''' clean markup from string '''
for val in self.get_markup_vars():
orig_str = orig_str.replace(val, '')
return orig_str | clean markup from string |
def clean(self):
"""
Make sure the lookup makes sense
"""
if self.lookup == '?': # Randomly sort
return
else:
lookups = self.lookup.split(LOOKUP_SEP)
opts = self.model_def.model_class()._meta
valid = True
while len(look... | Make sure the lookup makes sense |
def up_to_date(self):
"""Check if Team Password Manager is up to date."""
VersionInfo = self.get_latest_version()
CurrentVersion = VersionInfo.get('version')
LatestVersion = VersionInfo.get('latest_version')
if CurrentVersion == LatestVersion:
log.info('TeamPasswordM... | Check if Team Password Manager is up to date. |
def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,
params=None, success=False, error=True):
"""Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the L... | Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
... |
def rows_above_layout(self):
"""
Return the number of rows visible in the terminal above the layout.
"""
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = s... | Return the number of rows visible in the terminal above the layout. |
def players(timeout=timeout):
"""Return all players in dict {id: c, f, l, n, r}.
id, rank, nationality(?), first name, last name.
"""
rc = requests.get('{0}{1}.json'.format(card_info_url, 'players'), timeout=timeout).json()
players = {}
for i in rc['Players'] + rc['LegendsPlayers']:
play... | Return all players in dict {id: c, f, l, n, r}.
id, rank, nationality(?), first name, last name. |
def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None):
"""Run DistilledSGLD on mnist dataset"""
X, Y, X_test, Y_test = load_mnist(num_training)
minibatch_size = 100
if num_training >= 10000:
num_hidden = 800
total_iter_num = 1000000
teacher_learning_rate = 1E-6
stu... | Run DistilledSGLD on mnist dataset |
def dumpRule(serviceCls, rule, prefix):
"""
Create an in-between representation of the rule, so we can eventually convert it to OpenAPIPathItem with OpenAPIOperation(s)
"""
rulePath = prefix + rule.rule
rulePath = re.sub('/{2,}', '/', rulePath)
cor = ConvertedRule(
rulePath=rulePath... | Create an in-between representation of the rule, so we can eventually convert it to OpenAPIPathItem with OpenAPIOperation(s) |
def _parse_linear_expression(expression, expanded=False, **kwargs):
"""
Parse the coefficients of a linear expression (linearity is assumed).
Returns a dictionary of variable: coefficient pairs.
"""
offset = 0
constant = None
if expression.is_Add:
coefficients = expression.as_coeff... | Parse the coefficients of a linear expression (linearity is assumed).
Returns a dictionary of variable: coefficient pairs. |
def output_ip(gandi, ip, datacenters, vms, ifaces, output_keys, justify=11):
""" Helper to output an ip information."""
output_generic(gandi, ip, output_keys, justify)
if 'type' in output_keys:
iface = ifaces.get(ip['iface_id'])
type_ = 'private' if iface.get('vlan') else 'public'
o... | Helper to output an ip information. |
def velocity_confidence_transition(data, vkey='velocity', scale=10, copy=False):
"""Computes confidences of velocity transitions.
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name of velocity estimates to be used.
... | Computes confidences of velocity transitions.
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name of velocity estimates to be used.
scale: `float` (default: 10)
Scale parameter of gaussian kernel.
copy: `boo... |
def iter_coords(obj):
"""
Returns all the coordinate tuples from a geometry or feature.
"""
if isinstance(obj, (tuple, list)):
coords = obj
elif 'features' in obj:
coords = [geom['geometry']['coordinates'] for geom in obj['features']]
elif 'geometry' in obj:
coords = obj... | Returns all the coordinate tuples from a geometry or feature. |
def get_all_slots(class_):
"""
Return a list of slot names for slots defined in class_ and its
superclasses.
"""
# A subclass's __slots__ attribute does not contain slots defined
# in its superclass (the superclass' __slots__ end up as
# attributes of the subclass).
all_slots = []
pa... | Return a list of slot names for slots defined in class_ and its
superclasses. |
def declare_set(self, name, sep=os.pathsep):
"""
Declare an environment variable as a set-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
be considered set... | Declare an environment variable as a set-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
be considered set-like.
:param sep: The separator to be used. Defaults to... |
def string_repr(s):
"""Return a string as hex dump."""
if compat.is_bytes(s):
res = "{!r}: ".format(s)
for b in s:
if type(b) is str: # Py2
b = ord(b)
res += "%02x " % b
return res
return "{}".format(s) | Return a string as hex dump. |
def find_output_without_tag(self, tag):
"""
Find all files who do not have tag in self.tags
"""
# Enforce upper case
tag = tag.upper()
return FileList([i for i in self if tag not in i.tags]) | Find all files who do not have tag in self.tags |
def save_species_fitness(self, delimiter=' ', null_value='NA', filename='species_fitness.csv'):
""" Log species' average fitness throughout evolution. """
with open(filename, 'w') as f:
w = csv.writer(f, delimiter=delimiter)
for s in self.get_species_fitness(null_value):
... | Log species' average fitness throughout evolution. |
def setInstitutionLogo(self, pathList: tuple):
"""
takes one or more [logo].svg paths
if logo should be clickable, set
pathList = (
(my_path1.svg,www.something1.html),
(my_path2.svg,www.something2.html),
...)
"""... | takes one or more [logo].svg paths
if logo should be clickable, set
pathList = (
(my_path1.svg,www.something1.html),
(my_path2.svg,www.something2.html),
...) |
def lrange(self, name, start, end):
"""
Return a slice of the list ``name`` between
position ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return self.execute_command('LRANGE', name, start, end) | Return a slice of the list ``name`` between
position ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation |
def delete_record(self, identifier=None, rtype=None, name=None, content=None, **kwargs):
"""
Delete an existing record.
If record does not exist, do nothing.
If an identifier is specified, use it, otherwise do a lookup using type, name and content.
"""
if not rtype and kw... | Delete an existing record.
If record does not exist, do nothing.
If an identifier is specified, use it, otherwise do a lookup using type, name and content. |
def write_content(self, content, destination):
"""
Write given content to destination path.
It will create needed directory structure first if it contain some
directories that does not allready exists.
Args:
content (str): Content to write to target file.
... | Write given content to destination path.
It will create needed directory structure first if it contain some
directories that does not allready exists.
Args:
content (str): Content to write to target file.
destination (str): Destination path for target file.
Ret... |
def draw(self, startpoint=(0, 0), mode='plain', showfig=False):
""" lattice visualization
:param startpoint: start drawing point coords, default: (0, 0)
:param showfig: show figure or not, default: False
:param mode: artist mode, 'plain' or 'fancy', 'plain' by de... | lattice visualization
:param startpoint: start drawing point coords, default: (0, 0)
:param showfig: show figure or not, default: False
:param mode: artist mode, 'plain' or 'fancy', 'plain' by default
:return: patchlist, anotelist, (xmin0, xmax0), (ymin0, yma... |
def get_or_add_dPt_for_point(self, idx):
"""
Return the `c:dPt` child representing the visual properties of the
data point at index *idx*.
"""
matches = self.xpath('c:dPt[c:idx[@val="%d"]]' % idx)
if matches:
return matches[0]
dPt = self._add_dPt()
... | Return the `c:dPt` child representing the visual properties of the
data point at index *idx*. |
def get_module_item_sequence(self, course_id, asset_id=None, asset_type=None):
"""
Get module item sequence.
Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items
in the course sequence.
"""
path = {}
d... | Get module item sequence.
Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items
in the course sequence. |
def get_widget(self, index=None, path=None, tabs=None):
"""Get widget by index.
If no tabs and index specified the current active widget is returned.
"""
if (index and tabs) or (path and tabs):
return tabs.widget(index)
elif self.plugin:
return self.get_p... | Get widget by index.
If no tabs and index specified the current active widget is returned. |
def get(self, spike_ids, channels=None):
"""Load the waveforms of the specified spikes."""
if isinstance(spike_ids, slice):
spike_ids = _range_from_slice(spike_ids,
start=0,
stop=self.n_spikes,
... | Load the waveforms of the specified spikes. |
def batchcancel_openOrders(self, acc_id, symbol=None, side=None, size=None, _async=False):
"""
批量撤销未成交订单
:param acc_id: 帐号ID
:param symbol: 交易对
:param side: 方向
:param size:
:param _async:
:return:
"""
params = {}
path = '/v1/order/... | 批量撤销未成交订单
:param acc_id: 帐号ID
:param symbol: 交易对
:param side: 方向
:param size:
:param _async:
:return: |
def libvlc_video_set_spu_delay(p_mi, i_delay):
'''Set the subtitle delay. This affects the timing of when the subtitle will
be displayed. Positive values result in subtitles being displayed later,
while negative values will result in subtitles being displayed earlier.
The subtitle delay will be reset to... | Set the subtitle delay. This affects the timing of when the subtitle will
be displayed. Positive values result in subtitles being displayed later,
while negative values will result in subtitles being displayed earlier.
The subtitle delay will be reset to zero each time the media changes.
@param p_mi: me... |
def _local(self, args):
'''
Process local commands
'''
args.pop(0)
command = args[0]
if command == 'install':
self._local_install(args)
elif command == 'files':
self._local_list_files(args)
elif command == 'info':
self._... | Process local commands |
def parse_default_arguments(self, default_args_sample):
"""
:type default_args_sample list
:rtype dict
"""
parsed_arguments_dict = {}
default_arguments = list(self._arguments.default_arguments.values())
expected_length = len(default_arguments)
real_length = len(default_args_sample)
... | :type default_args_sample list
:rtype dict |
def detect_compiler(libpath):
"""Determines the compiler used to compile the specified shared library by
using the system utilities.
:arg libpath: the full path to the shared library *.so file.
"""
from os import waitpid, path
from subprocess import Popen, PIPE
command = "nm {0}".format(pat... | Determines the compiler used to compile the specified shared library by
using the system utilities.
:arg libpath: the full path to the shared library *.so file. |
def eventize(self, granularity):
""" This splits the JSON information found at self.events into the
several events. For this there are three different levels of time
consuming actions: 1-soft, 2-medium and 3-hard.
Level 1 provides events about emails
Level 2 not implemented
... | This splits the JSON information found at self.events into the
several events. For this there are three different levels of time
consuming actions: 1-soft, 2-medium and 3-hard.
Level 1 provides events about emails
Level 2 not implemented
Level 3 not implemented
:param g... |
def proc_exit(self, details):
"""
Handle the event when one of the task processes exits.
"""
log = self._params.get('log', self._discard)
pid = self._key
exit_code = details
why = statusfmt(exit_code)
proc = None
for p in self._parent._proc_state:
... | Handle the event when one of the task processes exits. |
def sort_objs_by_attr(objs, key, reverse=False):
"""
对原生不支持比较操作的对象根据属性排序
:param:
* objs: (list) 需要排序的对象列表
* key: (string) 需要进行排序的对象属性
* reverse: (bool) 排序结果是否进行反转,默认为 False,不进行反转
:return:
* result: (list) 排序后的对象列表
举例如下::
print('--- sorted_objs_by_attr demo... | 对原生不支持比较操作的对象根据属性排序
:param:
* objs: (list) 需要排序的对象列表
* key: (string) 需要进行排序的对象属性
* reverse: (bool) 排序结果是否进行反转,默认为 False,不进行反转
:return:
* result: (list) 排序后的对象列表
举例如下::
print('--- sorted_objs_by_attr demo---')
class User(object):
def __init__(... |
def parse_terminal_token(cls, parser, text):
"""Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g.... | Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g. And, Or, Not, defined above) should
not be ... |
def build_library(tile, libname, chip):
"""Build a static ARM cortex library"""
dirs = chip.build_dirs()
output_name = '%s_%s.a' % (libname, chip.arch_name())
# Support both firmware/src and just src locations for source code
if os.path.exists('firmware'):
VariantDir(dirs['build'], os.pat... | Build a static ARM cortex library |
def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32):
"""Reclassify raster by given classifier dict.
Args:
srcfile: source raster file.
v_dict: classifier dict.
dstfile: destination file path.
gdaltype (:obj:`pygeoc.raster.GDALDataType`):... | Reclassify raster by given classifier dict.
Args:
srcfile: source raster file.
v_dict: classifier dict.
dstfile: destination file path.
gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default. |
def unregister_node_path(self, node):
"""
Unregisters given Node path from the **file_system_events_manager**.
:param node: Node.
:type node: FileNode or DirectoryNode or ProjectNode
:return: Method success.
:rtype: bool
"""
path = node.file if hasattr(n... | Unregisters given Node path from the **file_system_events_manager**.
:param node: Node.
:type node: FileNode or DirectoryNode or ProjectNode
:return: Method success.
:rtype: bool |
def delete(filething):
""" delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
"""
t = OggOpus(filething)
filething.fileobj.seek(0)
t.delete(filething) | delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file. |
def ScreenGenerator(nfft, r0, nx, ny):
"""Generate an infinite series of rectangular phase screens
Uses an FFT screen generator to make a large screen and then
returns non-overlapping subsections of it"""
while 1:
layers = GenerateTwoScreens(nfft, r0)
for iLayer in range(2):
... | Generate an infinite series of rectangular phase screens
Uses an FFT screen generator to make a large screen and then
returns non-overlapping subsections of it |
def hacking_has_only_comments(physical_line, filename, lines, line_number):
"""Check for empty files with only comments
H104 empty file with only comments
"""
if line_number == 1 and all(map(EMPTY_LINE_RE.match, lines)):
return (0, "H104: File contains nothing but comments") | Check for empty files with only comments
H104 empty file with only comments |
def is_entry_safe(self, entry):
"""
Return ``True`` if ``entry`` can be safely extracted,
that is, if it does start with ``/`` or ``../``
after path normalization, ``False`` otherwise.
:rtype: bool
"""
normalized = os.path.normpath(entry)
if normalized.st... | Return ``True`` if ``entry`` can be safely extracted,
that is, if it does start with ``/`` or ``../``
after path normalization, ``False`` otherwise.
:rtype: bool |
def setupFog(self):
"""
Sets the fog system up.
The specific options available are documented under :confval:`graphics.fogSettings`\ .
"""
fogcfg = self.cfg["graphics.fogSettings"]
if not fogcfg["enable"]:
return
glEnable(GL_FOG)
... | Sets the fog system up.
The specific options available are documented under :confval:`graphics.fogSettings`\ . |
def _send_container_healthcheck_sc(self, containers_by_id):
"""Send health service checks for containers."""
for container in containers_by_id.itervalues():
healthcheck_tags = self._get_tags(container, HEALTHCHECK)
match = False
for tag in healthcheck_tags:
... | Send health service checks for containers. |
def t_HEXCONSTANT(self, t):
r'0x[0-9A-Fa-f]+'
t.value = int(t.value, 16)
t.type = 'INTCONSTANT'
return t | r'0x[0-9A-Fa-f]+ |
def processing_blocks(self):
"""Return list of PBs associated with the subarray.
<http://www.esrf.eu/computing/cs/tango/pytango/v920/server_api/server.html#PyTango.server.pipe>
"""
sbi_ids = Subarray(self.get_name()).sbi_ids
pbs = []
for sbi_id in sbi_ids:
sb... | Return list of PBs associated with the subarray.
<http://www.esrf.eu/computing/cs/tango/pytango/v920/server_api/server.html#PyTango.server.pipe> |
def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift *= 2
return max(4, n + 1) | Return next power of 2 greater than or equal to n |
def _get_app_path(url):
''' Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str
'''
app_path = urlparse(url).path.rstrip("/")
if not app_path.startswith("/"):
app_path = "/" + app_path
return app_path | Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str |
def _ioctl_cast(n):
"""
Linux ioctl() request parameter is unsigned, whereas on BSD/Darwin it is
signed. Until 2.5 Python exclusively implemented the BSD behaviour,
preventing use of large unsigned int requests like the TTY layer uses
below. So on 2.4, we cast our unsigned to look like signed for Py... | Linux ioctl() request parameter is unsigned, whereas on BSD/Darwin it is
signed. Until 2.5 Python exclusively implemented the BSD behaviour,
preventing use of large unsigned int requests like the TTY layer uses
below. So on 2.4, we cast our unsigned to look like signed for Python. |
def import_cvxpy():
"""
Try importing the qutip module, log an error if unsuccessful.
:return: The cvxpy module if successful or None
:rtype: Optional[module]
"""
global _CVXPY_ERROR_LOGGED
try:
import cvxpy
except ImportError: # pragma no coverage
cvxpy = None
... | Try importing the qutip module, log an error if unsuccessful.
:return: The cvxpy module if successful or None
:rtype: Optional[module] |
def ppo_opt_step(i,
opt_state,
ppo_opt_update,
policy_net_apply,
old_policy_params,
value_net_apply,
value_net_params,
padded_observations,
padded_actions,
padded_rewa... | PPO optimizer step. |
def main():
"""Entry point for remove_template."""
# Wrap sys stdout for python 2, so print can understand unicode.
if sys.version_info[0] < 3:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
options = docopt.docopt(__doc__,
help=True,
... | Entry point for remove_template. |
def loadkml(self, filename):
'''Load a kml from file and put it on the map'''
#Open the zip file
nodes = self.readkmz(filename)
self.snap_points = []
#go through each object in the kml...
for n in nodes:
point = self.readObject(n)
#and plac... | Load a kml from file and put it on the map |
def refresh(self):
"""Refresh the devices json object data."""
# Update core device data
new_device_json = self._device_request()
_LOGGER.debug("Device Refresh Response: %s", new_device_json)
# Update avatar url
new_avatar_json = self._avatar_request()
_LOGGER.de... | Refresh the devices json object data. |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EventContext for this EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContex... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EventContext for this EventInstance
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext |
def hook(name=None, *args, **kwargs):
"""Decorator to register the function as a hook
"""
def decorator(f):
if not hasattr(f, "hooks"):
f.hooks = []
f.hooks.append((name or f.__name__, args, kwargs))
return f
return decorator | Decorator to register the function as a hook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.