code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _astore32(ins):
''' Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
'''
output = _addr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
try:
value = int(in... | Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x |
def update_file(filename, result, content, indent):
"""Updates a Jekyll file to contain the counts form an object
This just converts the results to YAML and adds to the Jekyll frontmatter.
Args:
filename: the Jekyll file to update
result: the results object from `wc`
content: the c... | Updates a Jekyll file to contain the counts form an object
This just converts the results to YAML and adds to the Jekyll frontmatter.
Args:
filename: the Jekyll file to update
result: the results object from `wc`
content: the contents of the original file
indent: the indentatio... |
def assertType(var, *allowedTypes):
"""
Asserts that a variable @var is of an @expectedType. Raises a TypeError
if the assertion fails.
"""
if not isinstance(var, *allowedTypes):
raise NotImplementedError("This operation is only supported for {}. "\
"Instead found {}".format(str(... | Asserts that a variable @var is of an @expectedType. Raises a TypeError
if the assertion fails. |
def extract_captions(tex_file, sdir, image_list, primary=True):
"""Extract captions.
Take the TeX file and the list of images in the tarball (which all,
presumably, are used in the TeX file) and figure out which captions
in the text are associated with which images
:param: lines (list): list of lin... | Extract captions.
Take the TeX file and the list of images in the tarball (which all,
presumably, are used in the TeX file) and figure out which captions
in the text are associated with which images
:param: lines (list): list of lines of the TeX file
:param: tex_file (string): the name of the TeX ... |
def match(self, path):
u"""
:type path: text_type
:param path: The path to match against this list of path specs.
:return:
"""
for spec in reversed(self.pathspecs): # type: Pathspec
if spec.pattern.match(path):
return not spec.negated
... | u"""
:type path: text_type
:param path: The path to match against this list of path specs.
:return: |
def inspect_signature_parameters(callable_, excluded=None):
"""Get the parameters of a callable.
Returns a list with the signature parameters of `callable_`.
Parameters contained in `excluded` tuple will not be included
in the result.
:param callable_: callable object
:param excluded: tuple wi... | Get the parameters of a callable.
Returns a list with the signature parameters of `callable_`.
Parameters contained in `excluded` tuple will not be included
in the result.
:param callable_: callable object
:param excluded: tuple with default parameters to exclude
:result: list of parameters |
def save(self, *args, **kwargs):
"""
**uid**: :code:`division_cycle_ballotmeasure:{number}`
"""
self.uid = '{}_{}_ballotmeasure:{}'.format(
self.division.uid,
self.election_day.uid,
self.number
)
super(BallotMeasure, self).save(*args, *... | **uid**: :code:`division_cycle_ballotmeasure:{number}` |
def can_use_c_for(self, node):
"""
Check if a for loop can use classic C syntax.
To use C syntax:
- target should not be assign in the loop
- xrange should be use as iterator
- order have to be known at compile time
"""
assert isinstance(node.... | Check if a for loop can use classic C syntax.
To use C syntax:
- target should not be assign in the loop
- xrange should be use as iterator
- order have to be known at compile time |
def run_key(self, key):
'''
Return a function that executes the arguments passed via the local
client
'''
def func(*args, **kwargs):
'''
Run a remote call
'''
args = list(args)
for _key, _val in kwargs:
a... | Return a function that executes the arguments passed via the local
client |
def match_https_hostname(cls, hostname):
"""
:param hostname: a string
:returns: an :py:class:`~httpretty.core.URLMatcher` or ``None``
"""
items = sorted(
cls._entries.items(),
key=lambda matcher_entries: matcher_entries[0].priority,
reverse=Tr... | :param hostname: a string
:returns: an :py:class:`~httpretty.core.URLMatcher` or ``None`` |
def add_group(id, description=None):
""" Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str
"""
if not description:
de... | Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str |
def validate(self, str_in):
# type: (Text) -> None
""" Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff (1) the string does not represent a
date in the correct format; or (2) the date it represents
... | Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff (1) the string does not represent a
date in the correct format; or (2) the date it represents
is invalid (such as 30 February).
:param str str_in: ... |
def _args2_fpath(dpath, fname, cfgstr, ext):
r"""
Ensures that the filename is not too long
Internal util_cache helper function
Windows MAX_PATH=260 characters
Absolute length is limited to 32,000 characters
Each filename component is limited to 255 characters
Args:
dpath (str):
... | r"""
Ensures that the filename is not too long
Internal util_cache helper function
Windows MAX_PATH=260 characters
Absolute length is limited to 32,000 characters
Each filename component is limited to 255 characters
Args:
dpath (str):
fname (str):
cfgstr (str):
... |
def load(self, source):
"""
Opens the source file.
"""
self.source = open(self.source, 'rb')
self.loaded = True | Opens the source file. |
def _colorize(val, color):
"""Colorize a string using termcolor or colorama.
If any of them are available.
"""
if termcolor is not None:
val = termcolor.colored(val, color)
elif colorama is not None:
val = TERMCOLOR2COLORAMA[color] + val + colorama.Style.RESET_ALL
return val | Colorize a string using termcolor or colorama.
If any of them are available. |
def Operation(self, x, y):
"""Whether x is fully contained in y."""
if x in y:
return True
# x might be an iterable
# first we need to skip strings or we'll do silly things
# pylint: disable=consider-merging-isinstance
if isinstance(x, py2to3.STRING_TYPES) or isinstance(x, bytes):
r... | Whether x is fully contained in y. |
def _set_fill_word(self, v, load=False):
"""
Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fill_word is considered as a private
method. Backends looking to po... | Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fill_word is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... |
def _build_url(*args, **kwargs) -> str:
"""
Return a valid url.
"""
resource_url = API_RESOURCES_URLS
for key in args:
resource_url = resource_url[key]
if kwargs:
resource_url = resource_url.format(**kwargs)
return urljoin(URL, resource_url) | Return a valid url. |
def get_pointgroup(self, tolerance=0.3):
"""Returns a PointGroup object for the molecule.
Args:
tolerance (float): Tolerance to generate the full set of symmetry
operations.
Returns:
:class:`~PointGroupOperations`
"""
PA = self._get_poin... | Returns a PointGroup object for the molecule.
Args:
tolerance (float): Tolerance to generate the full set of symmetry
operations.
Returns:
:class:`~PointGroupOperations` |
def set_configs(self, key, d):
"""Set the whole configuration for a key"""
if '_config' in self.proxy:
self.proxy['_config'][key] = d
else:
self.proxy['_config'] = {key: d} | Set the whole configuration for a key |
def pref_update(self, key, new_val):
""" Changes a preference value and saves it to disk """
print('Update and save pref from: %s=%r, to: %s=%r' %
(key, six.text_type(self[key]), key, six.text_type(new_val)))
self.__setattr__(key, new_val)
return self.save() | Changes a preference value and saves it to disk |
def tupletree(table, start='start', stop='stop', value=None):
"""
Construct an interval tree for the given table, where each node in the tree
is a row of the table.
"""
import intervaltree
tree = intervaltree.IntervalTree()
it = iter(table)
hdr = next(it)
flds = list(map(text_type,... | Construct an interval tree for the given table, where each node in the tree
is a row of the table. |
def show_cluster_role(cl_args, cluster, role):
''' print topologies information to stdout '''
try:
result = tracker_access.get_cluster_role_topologies(cluster, role)
if not result:
Log.error('Unknown cluster/role \'%s\'' % '/'.join([cluster, role]))
return False
result = result[cluster]
ex... | print topologies information to stdout |
def update_compliance_task(self, id, name=None, module_name=None, schedule=None, scope=None, enabled=None):
'''**Description**
Update an existing compliance task.
**Arguments**
- id: the id of the compliance task to be updated.
- name: The name of the task e.g. 'Chec... | **Description**
Update an existing compliance task.
**Arguments**
- id: the id of the compliance task to be updated.
- name: The name of the task e.g. 'Check Docker Compliance'.
- module_name: The name of the module that implements this task. Separate from task n... |
def add_proof(self, text, publisher_account, keeper):
"""Add a proof to the DDO, based on the public_key id/index and signed with the private key
add a static proof to the DDO, based on one of the public keys."""
# just incase clear out the current static proof property
self._proof = No... | Add a proof to the DDO, based on the public_key id/index and signed with the private key
add a static proof to the DDO, based on one of the public keys. |
def rot_matrix(angle):
r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.mat... | r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.matrix import rot_matrix
>... |
def track_enrollment(pathway, user_id, course_run_id, url_path=None):
"""
Emit a track event for enterprise course enrollment.
"""
track_event(user_id, 'edx.bi.user.enterprise.onboarding', {
'pathway': pathway,
'url_path': url_path,
'course_run_id': course_run_id,
}) | Emit a track event for enterprise course enrollment. |
def close(self, figs=True, data=False, ds=False, remove_only=False):
"""
Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, clos... | Close this project instance
Parameters
----------
figs: bool
Close the figures
data: bool
delete the arrays from the (main) project
ds: bool
If True, close the dataset as well
remove_only: bool
If True and `figs` is True, t... |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_interface_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubEleme... | Auto Generated Code |
def check(self, instance):
"""
Returns a dictionary that looks a lot like what's sent back by
db.serverStatus()
"""
def total_seconds(td):
"""
Returns total seconds of a timedelta in a way that's safe for
Python < 2.7
"""
... | Returns a dictionary that looks a lot like what's sent back by
db.serverStatus() |
def _validate_header(self, hed):
"""
Validate the list that represents the table header.
:param hed: The list that represents the table header.
:type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return: True if the table header is valid or False if the tabl... | Validate the list that represents the table header.
:param hed: The list that represents the table header.
:type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return: True if the table header is valid or False if the table header
is not valid.
:rtyp... |
def _minimal_common_integer_splitted(si_0, si_1):
"""
Calculates the minimal integer that appears in both StridedIntervals.
It's equivalent to finding an integral solution for equation `ax + b = cy + d` that makes `ax + b` minimal
si_0.stride, si_1.stride being a and c, and si_0.lower_bo... | Calculates the minimal integer that appears in both StridedIntervals.
It's equivalent to finding an integral solution for equation `ax + b = cy + d` that makes `ax + b` minimal
si_0.stride, si_1.stride being a and c, and si_0.lower_bound, si_1.lower_bound being b and d, respectively.
Upper bound... |
def aggregate(self):
"""Create a new SampleSet with repeated samples aggregated.
Returns:
:obj:`.SampleSet`
Note:
:attr:`.SampleSet.record.num_occurrences` are accumulated but no
other fields are.
"""
_, indices, inverse = np.unique(self.rec... | Create a new SampleSet with repeated samples aggregated.
Returns:
:obj:`.SampleSet`
Note:
:attr:`.SampleSet.record.num_occurrences` are accumulated but no
other fields are. |
def _config_sortable(self, sortable):
"""Configure a new sortable state"""
for col in self["columns"]:
command = (lambda c=col: self._sort_column(c, True)) if sortable else ""
self.heading(col, command=command)
self._sortable = sortable | Configure a new sortable state |
def from_config(config, **options):
"""Instantiate an `RotatedEventStore` from config.
Parameters:
_config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store... | Instantiate an `RotatedEventStore` from config.
Parameters:
_config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Warning will be logged
f... |
def format_log_context(msg, connection=None, keyspace=None):
"""Format log message to add keyspace and connection context"""
connection_info = connection or 'DEFAULT_CONNECTION'
if keyspace:
msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg)
else:
msg = ... | Format log message to add keyspace and connection context |
def make_datalab_help_action(self):
"""Custom action for --datalab-help.
The action output the package specific parameters and will be part of "%%ml train"
help string.
"""
datalab_help = self.datalab_help
epilog = self.datalab_epilog
class _CustomAction(argparse.Action):
def __init... | Custom action for --datalab-help.
The action output the package specific parameters and will be part of "%%ml train"
help string. |
def do_checkout(self, repo):
'''
Common code for git_pillar/winrepo to handle locking and checking out
of a repo.
'''
time_start = time.time()
while time.time() - time_start <= 5:
try:
return repo.checkout()
except GitLockError as e... | Common code for git_pillar/winrepo to handle locking and checking out
of a repo. |
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: EnvironmentContext for this EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environ... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: EnvironmentContext for this EnvironmentInstance
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext |
def dodirot(D, I, Dbar, Ibar):
"""
Rotate a direction (declination, inclination) by the difference between
dec=0 and inc = 90 and the provided desired mean direction
Parameters
----------
D : declination to be rotated
I : inclination to be rotated
Dbar : declination of desired mean
... | Rotate a direction (declination, inclination) by the difference between
dec=0 and inc = 90 and the provided desired mean direction
Parameters
----------
D : declination to be rotated
I : inclination to be rotated
Dbar : declination of desired mean
Ibar : inclination of desired mean
Ret... |
def get_bond_symmetry(site_symmetry,
lattice,
positions,
atom_center,
atom_disp,
symprec=1e-5):
"""
Bond symmetry is the symmetry operations that keep the symmetry
of the cell containing two fixed a... | Bond symmetry is the symmetry operations that keep the symmetry
of the cell containing two fixed atoms. |
def in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8):
"""
Tests if a particular fractional coord is within a fractional coord_list.
Args:
fcoord_list: List of fractional coords to test
fcoord: A specific fractional coord to test.
atol: Absolute tolerance. Defaults to 1e-8.
Ret... | Tests if a particular fractional coord is within a fractional coord_list.
Args:
fcoord_list: List of fractional coords to test
fcoord: A specific fractional coord to test.
atol: Absolute tolerance. Defaults to 1e-8.
Returns:
True if coord is in the coord list. |
def serialize_relations(pid):
"""Serialize the relations for given PID."""
data = {}
relations = PIDRelation.get_child_relations(pid).all()
for relation in relations:
rel_cfg = resolve_relation_type_config(relation.relation_type)
dump_relation(rel_cfg.api(relation.parent),
... | Serialize the relations for given PID. |
def show_feature_destibution(self, data = None):
"""!
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displa... | !
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displayed only. |
def to_json(self):
"""
Serialises a HucitWork to a JSON formatted string.
"""
titles = self.get_titles()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "titles" : [{"language":lang, "label":label} for lang,... | Serialises a HucitWork to a JSON formatted string. |
def set_info_page(self):
"""Set current info_page."""
if self.info_page is not None:
self.infowidget.setHtml(
self.info_page,
QUrl.fromLocalFile(self.css_path)
) | Set current info_page. |
def _expand_user(filepath_or_buffer):
"""Return the argument with an initial component of ~ or ~user
replaced by that user's home directory.
Parameters
----------
filepath_or_buffer : object to be converted if possible
Returns
-------
expanded_filepath_or_buffer : an expanded filepa... | Return the argument with an initial component of ~ or ~user
replaced by that user's home directory.
Parameters
----------
filepath_or_buffer : object to be converted if possible
Returns
-------
expanded_filepath_or_buffer : an expanded filepath or the
i... |
def add(args):
"""
Add a new feed
"""
session = c.Session(args)
if args["name"] in session.feeds.sections():
sys.exit("You already have a feed with that name.")
if args["name"] in ["all", "DEFAULT"]:
sys.exit(
("greg uses ""{}"" for a special purpose."
"P... | Add a new feed |
def get_branch(self):
"""
:return:
"""
if self.repo.head.is_detached:
if os.getenv('GIT_BRANCH'):
branch = os.getenv('GIT_BRANCH')
elif os.getenv('BRANCH_NAME'):
branch = os.getenv('BRANCH_NAME')
elif os.getenv('TRAVIS_B... | :return: |
def cmd_alt(self, args):
'''show altitude'''
print("Altitude: %.1f" % self.status.altitude)
qnh_pressure = self.get_mav_param('AFS_QNH_PRESSURE', None)
if qnh_pressure is not None and qnh_pressure > 0:
ground_temp = self.get_mav_param('GND_TEMP', 21)
pressure = s... | show altitude |
def get_list(self, key, fallback=None, split=","):
"""
Retrieve a value in list form.
The interpolated value will be split on some key (by default, ',') and
the resulting list will be returned.
Arguments:
key - the key to return
fallback - The result to return i... | Retrieve a value in list form.
The interpolated value will be split on some key (by default, ',') and
the resulting list will be returned.
Arguments:
key - the key to return
fallback - The result to return if key isn't in the component. By
default, this will... |
def get_kbd_values_json(kbname, searchwith=""):
"""Return values from searching a dynamic kb as a json-formatted string.
This IS probably the method you want.
:param kbname: name of the knowledge base
:param searchwith: a term to search with
"""
res = get_kbd_values(kbname, searchwith)
... | Return values from searching a dynamic kb as a json-formatted string.
This IS probably the method you want.
:param kbname: name of the knowledge base
:param searchwith: a term to search with |
def extract_rar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a RAR archive."""
cmdlist = [cmd, 'x']
if not interactive:
cmdlist.extend(['-p-', '-y'])
cmdlist.extend(['--', os.path.abspath(archive)])
return (cmdlist, {'cwd': outdir}) | Extract a RAR archive. |
async def _seed2did(self) -> str:
"""
Derive DID, as per indy-sdk, from seed.
:return: DID
"""
rv = None
dids_with_meta = json.loads(await did.list_my_dids_with_meta(self.handle)) # list
if dids_with_meta:
for did_with_meta in dids_with_meta: # di... | Derive DID, as per indy-sdk, from seed.
:return: DID |
def draw_mask(self, image_shape, size_lines=1, size_points=0,
raise_if_out_of_image=False):
"""
Draw this line segment as a binary image mask.
Parameters
----------
image_shape : tuple of int
The shape of the image onto which to draw the line mask.
... | Draw this line segment as a binary image mask.
Parameters
----------
image_shape : tuple of int
The shape of the image onto which to draw the line mask.
size_lines : int, optional
Thickness of the line segments.
size_points : int, optional
S... |
async def collect_wallets(self, uid):
"""
Asynchronous generator
"""
logging.debug(self.types)
logging.debug(uid)
for coinid in self.types:
logging.debug(coinid)
await asyncio.sleep(0.5)
# Connect to appropriate database
database = self.client[self.collection]
logging.debug(database)
colle... | Asynchronous generator |
def get_version_status(
package_descriptors, targets, repos_data,
strip_version=False, strip_os_code_name=False):
"""
For each package and target check if it is affected by a sync.
This is the case when the package version in the testing repo is different
from the version in the main re... | For each package and target check if it is affected by a sync.
This is the case when the package version in the testing repo is different
from the version in the main repo.
:return: a dict indexed by package names containing
dicts indexed by targets containing
a list of status strings (one for... |
def kmcop(args):
"""
%prog kmcop *.kmc_suf
Intersect or union kmc indices.
"""
p = OptionParser(kmcop.__doc__)
p.add_option("--action", choices=("union", "intersect"),
default="union", help="Action")
p.add_option("-o", default="results", help="Output name")
opts, args = ... | %prog kmcop *.kmc_suf
Intersect or union kmc indices. |
def predict(fqdn, result, *argl, **argd):
"""Analyzes the result of a generic predict operation performed by
`sklearn`.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to... | Analyzes the result of a generic predict operation performed by
`sklearn`.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to the method call.
argd (dict): keyword ar... |
def draw_rect(self, color, world_rect, thickness=0):
"""Draw a rectangle using world coordinates."""
tl = self.world_to_surf.fwd_pt(world_rect.tl).round()
br = self.world_to_surf.fwd_pt(world_rect.br).round()
rect = pygame.Rect(tl, br - tl)
pygame.draw.rect(self.surf, color, rect, thickness) | Draw a rectangle using world coordinates. |
def package_releases(request, package_name, show_hidden=False):
"""
Retrieve a list of the releases registered for the given package_name.
Returns a list with all version strings if show_hidden is True or
only the non-hidden ones otherwise."""
session = DBSession()
package = Package.by_name(sess... | Retrieve a list of the releases registered for the given package_name.
Returns a list with all version strings if show_hidden is True or
only the non-hidden ones otherwise. |
async def add_participant(self, display_name: str = None, username: str = None, email: str = None, seed: int = 0, misc: str = None, **params):
""" add a participant to the tournament
|methcoro|
Args:
display_name: The name displayed in the bracket/schedule - not required if email o... | add a participant to the tournament
|methcoro|
Args:
display_name: The name displayed in the bracket/schedule - not required if email or challonge_username is provided. Must be unique per tournament.
username: Provide this if the participant has a Challonge account. He or she w... |
def percentile(values=None, percentile=None):
"""Calculates a simplified weighted average percentile
"""
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
... | Calculates a simplified weighted average percentile |
def flowwrite(flow, filename, quantize=False, concat_axis=0, *args, **kwargs):
"""Write optical flow to file.
If the flow is not quantized, it will be saved as a .flo file losslessly,
otherwise a jpeg image which is lossy but of much smaller size. (dx and dy
will be concatenated horizontally into a sin... | Write optical flow to file.
If the flow is not quantized, it will be saved as a .flo file losslessly,
otherwise a jpeg image which is lossy but of much smaller size. (dx and dy
will be concatenated horizontally into a single image if quantize is True.)
Args:
flow (ndarray): (h, w, 2) array of ... |
def create_context(self, state_hash, base_contexts, inputs, outputs):
"""Create a ExecutionContext to run a transaction against.
Args:
state_hash: (str): Merkle root to base state on.
base_contexts (list of str): Context ids of contexts that will
have their state... | Create a ExecutionContext to run a transaction against.
Args:
state_hash: (str): Merkle root to base state on.
base_contexts (list of str): Context ids of contexts that will
have their state applied to make this context.
inputs (list of str): Addresses that c... |
def date(self):
"""Convert instant to a date.
>>> instant(2014).date
datetime.date(2014, 1, 1)
>>> instant('2014-2').date
datetime.date(2014, 2, 1)
>>> instant('2014-2-3').date
datetime.date(2014, 2, 3)
"""
instant_date = date_by_instant_cache.get... | Convert instant to a date.
>>> instant(2014).date
datetime.date(2014, 1, 1)
>>> instant('2014-2').date
datetime.date(2014, 2, 1)
>>> instant('2014-2-3').date
datetime.date(2014, 2, 3) |
def _get_wms_request(self, bbox, size_x, size_y):
"""
Returns WMS request.
"""
bbox_3857 = transform_bbox(bbox, CRS.POP_WEB)
return GeopediaWmsRequest(layer=self.layer,
theme=self.theme,
bbox=bbox_3857,
... | Returns WMS request. |
def set_zone(timezone):
'''
Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
... | Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'Ameri... |
def update_edges(self, elev_fn, dem_proc):
"""
After finishing a calculation, this will update the neighbors and the
todo for that tile
"""
interp = self.build_interpolator(dem_proc)
self.update_edge_todo(elev_fn, dem_proc)
self.set_neighbor_data(elev_fn, dem_proc... | After finishing a calculation, this will update the neighbors and the
todo for that tile |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'match') and self.match is not None:
_dict['match'] = self.match
return _dict | Return a json dictionary representing this model. |
def handle_json_GET_neareststops(self, params):
"""Return a list of the nearest 'limit' stops to 'lat', 'lon'"""
schedule = self.server.schedule
lat = float(params.get('lat'))
lon = float(params.get('lon'))
limit = int(params.get('limit'))
stops = schedule.GetNearestStops(lat=lat, lon=lon, n=lim... | Return a list of the nearest 'limit' stops to 'lat', 'lon |
def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
"""
Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, us... | Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, user may opt to utilize thumbnail_index parameter.
Please eee documentation for further ... |
def _get_domain_id(self, domain_text_element): # pylint: disable=no-self-use
"""Return the easyname id of the domain."""
try:
# Hierarchy: TR > TD > SPAN > Domain Text
tr_anchor = domain_text_element.parent.parent.parent
td_anchor = tr_anchor.find('td', {'class': 'td... | Return the easyname id of the domain. |
def download_url(self, timeout=60, name=None):
"""
Trigger a browse download
:param timeout: int - Time in seconds to expire the download
:param name: str - for LOCAL only, to rename the file being downloaded
:return: str
"""
if "local" in self.driver.name.lower()... | Trigger a browse download
:param timeout: int - Time in seconds to expire the download
:param name: str - for LOCAL only, to rename the file being downloaded
:return: str |
def validate(self, value):
"""Validate field value."""
if value is not None:
if not isinstance(value, list):
raise ValidationError("field must be a list")
for index, element in enumerate(value):
try:
self.inner.validate(element... | Validate field value. |
def tree_adj_to_prec(graph, root=0):
"""Transforms a tree given as adjacency list into predecessor table form.
if graph is not a tree: will return a DFS spanning tree
:param graph: directed graph in listlist or listdict format
:returns: tree in predecessor table representation
:complexity: linear
... | Transforms a tree given as adjacency list into predecessor table form.
if graph is not a tree: will return a DFS spanning tree
:param graph: directed graph in listlist or listdict format
:returns: tree in predecessor table representation
:complexity: linear |
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object... | List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object_versions mybucket |
def redraw(self):
"""
Redraw the Vispy canvas
"""
if self._multiscat is not None:
self._multiscat._update()
self.vispy_widget.canvas.update() | Redraw the Vispy canvas |
def connect(tenant=None, user=None, password=None, token=None, is_public=False):
"""
Authenticates user and returns new platform to user.
This is an entry point to start working with Qubell Api.
:rtype: QubellPlatform
:param str tenant: url to tenant, default taken from 'QUBELL_T... | Authenticates user and returns new platform to user.
This is an entry point to start working with Qubell Api.
:rtype: QubellPlatform
:param str tenant: url to tenant, default taken from 'QUBELL_TENANT'
:param str user: user email, default taken from 'QUBELL_USER'
:param str passw... |
def unmount(self, remove_rw=False, allow_lazy=False):
"""Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
:raises SubsystemError: when one of the underlying commands fails. Some are swallowed.
:raises CleanupError: when actual cleanup fails. Some are ... | Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
:raises SubsystemError: when one of the underlying commands fails. Some are swallowed.
:raises CleanupError: when actual cleanup fails. Some are swallowed. |
def Run(self, unused_args):
"""Estimate the install date of this system."""
# Don't use winreg.KEY_WOW64_64KEY since it breaks on Windows 2000
subkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows NT\\CurrentVersion",
0, winr... | Estimate the install date of this system. |
def walk(filesystem, top, topdown=True, onerror=None, followlinks=False):
"""Perform an os.walk operation over the fake filesystem.
Args:
filesystem: The fake filesystem used for implementation
top: The root directory from which to begin walk.
topdown: Determines whether to return the t... | Perform an os.walk operation over the fake filesystem.
Args:
filesystem: The fake filesystem used for implementation
top: The root directory from which to begin walk.
topdown: Determines whether to return the tuples with the root as
the first entry (`True`) or as the last, after... |
def handle_request(self, environ, start_response):
"""Retrieves the route handler and calls the handler returning its the response
:param dict environ: The WSGI environment dictionary for the request
:param start_response:
:return: The WbResponse for the request
:rtype: WbRespon... | Retrieves the route handler and calls the handler returning its the response
:param dict environ: The WSGI environment dictionary for the request
:param start_response:
:return: The WbResponse for the request
:rtype: WbResponse |
def vm_cputime(vm_=None):
'''
Return cputime used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name i... | Return cputime used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'cputime' <int>
'cputime_percent' <int>
},
...
]
If you pass a VM name in as an argument then it will return i... |
def select_authors_by_geo(query):
"""Pass exact name (case insensitive) of geography name, return ordered set
of author ids.
"""
for geo, ids in AUTHOR_GEO.items():
if geo.casefold() == query.casefold():
return set(ids) | Pass exact name (case insensitive) of geography name, return ordered set
of author ids. |
def get_pltdotstr(self, **kws_usr):
"""Plot one GO header group in Grouper."""
dotstrs = self.get_pltdotstrs(**kws_usr)
assert len(dotstrs) == 1
return dotstrs[0] | Plot one GO header group in Grouper. |
def to_json_file(self, json_file_path):
""" Save this instance to a json file."""
with open(json_file_path, "w", encoding='utf-8') as writer:
writer.write(self.to_json_string()) | Save this instance to a json file. |
def recv(self, maxsize=None):
'''
Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process.
'''
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
... | Receive data from the terminal as a (``stdout``, ``stderr``) tuple. If
any of those is ``None`` we can no longer communicate with the
terminal's child process. |
def calc_next_run(self):
"""Calculate next run time of this task"""
base_time = self.last_run
if self.last_run == HAS_NOT_RUN:
if self.wait_for_schedule is False:
self.next_run = timezone.now()
self.wait_for_schedule = False # reset so we don't run on ... | Calculate next run time of this task |
def make_error_block(ec_info, data_block):
"""\
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words.
"""
num_error_words = ec_info.num_total - ec_info.num_data... | \
Creates the error code words for the provided data block.
:param ec_info: ECC information (number of blocks, number of code words etc.)
:param data_block: Iterable of (integer) code words. |
def figure_out_build_file(absolute_path, local_path=None):
"""
try to figure out the build file (Dockerfile or just a container.yaml) from provided
path and optionally from relative local path this is meant to be used with
git repo: absolute_path is path to git repo, local_path is path to dockerfile
... | try to figure out the build file (Dockerfile or just a container.yaml) from provided
path and optionally from relative local path this is meant to be used with
git repo: absolute_path is path to git repo, local_path is path to dockerfile
within git repo
:param absolute_path:
:param local_path:
... |
def reraise(self, cause_cls_finder=None):
"""Re-raise captured exception (possibly trying to recreate)."""
if self._exc_info:
six.reraise(*self._exc_info)
else:
# Attempt to regenerate the full chain (and then raise
# from the root); without a traceback, oh we... | Re-raise captured exception (possibly trying to recreate). |
def get_days_since_last_modified(filename):
"""
:param filename: Absolute file path
:return: Number of days since filename's last modified time
"""
now = datetime.now()
last_modified = datetime.fromtimestamp(os.path.getmtime(filename))
return (now - last_modified)... | :param filename: Absolute file path
:return: Number of days since filename's last modified time |
def indexAt(self, point):
"""Returns the index of the component at *point* relative to view coordinates.
If there is None, and empty index is returned. :qtdoc:`Re-implemented<QAbstractItemView.indexAt>`
:param point: the point, in view coordinates, to find an index for
:type point: :qtd... | Returns the index of the component at *point* relative to view coordinates.
If there is None, and empty index is returned. :qtdoc:`Re-implemented<QAbstractItemView.indexAt>`
:param point: the point, in view coordinates, to find an index for
:type point: :qtdoc:`QPoint`
:returns: :qtdoc:... |
def add_deformation(chn_names, data):
"""From circularity, compute the deformation
This method is useful for RT-DC data sets that contain
the circularity but not the deformation.
"""
if "deformation" not in chn_names:
for ii, ch in enumerate(chn_names):
if ch == "circularity":
... | From circularity, compute the deformation
This method is useful for RT-DC data sets that contain
the circularity but not the deformation. |
def register_view(self, view):
""" register_view will create the needed structure
in order to be able to sent all data to Prometheus
"""
v_name = get_view_name(self.options.namespace, view)
if v_name not in self.registered_views:
desc = {'name': v_name,
... | register_view will create the needed structure
in order to be able to sent all data to Prometheus |
def cloudata(site):
""" Returns a dictionary with all the tag clouds related to a site.
"""
# XXX: this looks like it can be done via ORM
tagdata = getquery("""
SELECT feedjack_post.feed_id, feedjack_tag.name, COUNT(*)
FROM feedjack_post, feedjack_subscriber, feedjack_tag,
feedjack_post_tags
WHERE feedjack... | Returns a dictionary with all the tag clouds related to a site. |
def pldist(point, start, end):
"""
Calculates the distance from ``point`` to the line given
by the points ``start`` and ``end``.
:param point: a point
:type point: numpy array
:param start: a point of the line
:type start: numpy array
:param end: another point of the line
:type end:... | Calculates the distance from ``point`` to the line given
by the points ``start`` and ``end``.
:param point: a point
:type point: numpy array
:param start: a point of the line
:type start: numpy array
:param end: another point of the line
:type end: numpy array |
def should_retry_on_error(self, error):
"""rules for retry
:param error:
ProtocolException that returns from Server
"""
if self.is_streaming_request:
# not retry for streaming request
return False
retry_flag = self.headers.get('re', retry.DE... | rules for retry
:param error:
ProtocolException that returns from Server |
def main_inject(args):
"""
mapped to pout.inject on the command line, makes it easy to make pout global
without having to actually import it in your python environment
.. since:: 2018-08-13
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return c... | mapped to pout.inject on the command line, makes it easy to make pout global
without having to actually import it in your python environment
.. since:: 2018-08-13
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.