code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def CMOVB(cpu, dest, src):
"""
Conditional move - Below/not above or equal.
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current CP... | Conditional move - Below/not above or equal.
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current CPU.
:param dest: destination operand.
... |
def is_active(self):
"""The images plugin is active iff any run has at least one relevant tag."""
if self._db_connection_provider:
# The plugin is active if one relevant tag can be found in the database.
db = self._db_connection_provider()
cursor = db.execute(
'''
SELECT 1
... | The images plugin is active iff any run has at least one relevant tag. |
def _set_shape(self, shape):
"""Deletes all cells beyond new shape and sets dict_grid shape
Parameters
----------
shape: 3-tuple of Integer
\tTarget shape for grid
"""
# Delete each cell that is beyond new borders
old_shape = self.shape
deleted... | Deletes all cells beyond new shape and sets dict_grid shape
Parameters
----------
shape: 3-tuple of Integer
\tTarget shape for grid |
def domagicmag(file, Recs):
"""
converts a magic record back into the SIO mag format
"""
for rec in Recs:
type = ".0"
meths = []
tmp = rec["magic_method_codes"].split(':')
for meth in tmp:
meths.append(meth.strip())
if 'LT-T-I' in meths:
ty... | converts a magic record back into the SIO mag format |
def infect(cls, graph, key, default_scope=None):
"""
Forcibly convert an entry-point based factory to a ScopedFactory.
Must be invoked before resolving the entry point.
:raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding
"""
f... | Forcibly convert an entry-point based factory to a ScopedFactory.
Must be invoked before resolving the entry point.
:raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding |
def delete_account_user(self, account_id, user_id, **kwargs): # noqa: E501
"""Delete a user. # noqa: E501
An endpoint for deleting a user. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{user-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501... | Delete a user. # noqa: E501
An endpoint for deleting a user. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{user-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
as... |
def run_op(self, op, sched):
"""
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever ... | Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever the function returned.
* if StopIterat... |
def set_outlet(self, latitude, longitude, outslope):
"""
Adds outlet point to project
"""
self.project_manager.setOutlet(latitude=latitude, longitude=longitude,
outslope=outslope) | Adds outlet point to project |
def next_game(self):
'''
Advances the series to the next game, if possible. Also updates
each team's score with points from the most recently completed game.
:return: the next game, if the previous game did not end the series;
None otherwise
:raises SeriesOverEx... | Advances the series to the next game, if possible. Also updates
each team's score with points from the most recently completed game.
:return: the next game, if the previous game did not end the series;
None otherwise
:raises SeriesOverException: if the series has already ended
... |
def init_wstr(self):
"""
Compute and initialize optimization levels for BLO and
stratification. This method is invoked once, from the
constructor of an object of :class:`RC2Stratified`. Given
the weights of the soft clauses, the method divides the
MaxS... | Compute and initialize optimization levels for BLO and
stratification. This method is invoked once, from the
constructor of an object of :class:`RC2Stratified`. Given
the weights of the soft clauses, the method divides the
MaxSAT problem into several optimization levels. |
def _perform_call(self, query_url, default_response=None, timeout=10):
"""Returns the raw results from the API"""
try:
response = requests.get(query_url, timeout=timeout)
except socket.timeout:
current_plugin.logger.warning("Timeout contacting Piwik server")
r... | Returns the raw results from the API |
def lookup(self, TC: type, G: type) -> Optional[TypeClass]:
''' Find an instance of the type class `TC` for type `G`.
Iterates `G`'s parent classes, looking up instances for each,
checking whether the instance is a subclass of the target type
class `TC`.
'''
if isinstance... | Find an instance of the type class `TC` for type `G`.
Iterates `G`'s parent classes, looking up instances for each,
checking whether the instance is a subclass of the target type
class `TC`. |
def django_api(
self,
name,
introduced_at,
undocumented=False,
deprecated_at=None,
title=None,
**options):
"""Add a django API handler to the service.
:param name: This is the name of the django url to use.
The... | Add a django API handler to the service.
:param name: This is the name of the django url to use.
The 'methods' paramater can be supplied as normal, you can also user
the @api.handler decorator to link this API to its handler. |
def receives(self, *args, **kwargs):
"""Pop the next `Request` and assert it matches.
Returns None if the server is stopped.
Pass a `Request` or request pattern to specify what client request to
expect. See the tutorial for examples. Pass ``timeout`` as a keyword
argument to ov... | Pop the next `Request` and assert it matches.
Returns None if the server is stopped.
Pass a `Request` or request pattern to specify what client request to
expect. See the tutorial for examples. Pass ``timeout`` as a keyword
argument to override this server's ``request_timeout``. |
async def send_event(self, con, name, payload):
"""Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the clien... | Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the client has
connected and passed to self.prepare_conn(con... |
def _check_mode(stream):
"""Check that a stream was opened in read-binary mode.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:raises: :exc:`ValueError` if the ``stream.mode`` is a valid attribute
and is not among ``rb``, ``r+b`` or ``rb+``.
"""
mode =... | Check that a stream was opened in read-binary mode.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:raises: :exc:`ValueError` if the ``stream.mode`` is a valid attribute
and is not among ``rb``, ``r+b`` or ``rb+``. |
def get_subgraph(self, subvertices, normalize=False):
"""Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information.
"""
graph = Graph.get_subgraph(self, subvertices, normalize)
if normalize:
new_numbers = self.number... | Creates a subgraph of the current graph
See :meth:`molmod.graphs.Graph.get_subgraph` for more information. |
def savecsv(self, filename):
'''save waypoints to a file in human-readable CSV file'''
f = open(filename, mode='w')
headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"]
print(self.csv_line(headers))
f.write(self.csv_line(headers) + "\n")
for w in self.... | save waypoints to a file in human-readable CSV file |
def post_input_accelerators(self, value):
"""
Setter for **self.__post_input_accelerators** attribute.
:param value: Attribute value.
:type value: tuple or list
"""
if value is not None:
assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is no... | Setter for **self.__post_input_accelerators** attribute.
:param value: Attribute value.
:type value: tuple or list |
def remove_tracks(self, track_indices):
"""
Remove tracks specified by `track_indices`.
Parameters
----------
track_indices : list
The indices of the tracks to be removed.
"""
if isinstance(track_indices, int):
track_indices = [track_indi... | Remove tracks specified by `track_indices`.
Parameters
----------
track_indices : list
The indices of the tracks to be removed. |
def download_file(src_url, dst_path):
"""
Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none:
"""
if "MD9821... | Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none: |
def relative_abundance(biomf, sampleIDs=None):
"""
Calculate the relative abundance of each OTUID in a Sample.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: list
:param sampleIDs: A list of sample id's from BIOM format OTU table.
:rtype: dict
:return: Retu... | Calculate the relative abundance of each OTUID in a Sample.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: list
:param sampleIDs: A list of sample id's from BIOM format OTU table.
:rtype: dict
:return: Returns a keyed on SampleIDs, and the values are dictionaries k... |
def similarity(self, other):
"""Get similarity as a ratio of the stripped text."""
logging.debug("comparing %r and %r...", self.stripped, other.stripped)
ratio = SequenceMatcher(a=self.stripped, b=other.stripped).ratio()
similarity = self.Similarity(ratio)
return similarity | Get similarity as a ratio of the stripped text. |
def update_state(self):
"""
Update state with latest info from Wink API.
"""
response = self.api_interface.get_device_state(self, type_override="button")
return self._update_state_from_response(response) | Update state with latest info from Wink API. |
def get_pore_surface_parameters(surface_area):
""" Get input parameters for pore surface binary.
Get input parameters for pore_surface binary from zeo++ output,
while keeping data provenance.
"""
PoreSurfaceParameters = DataFactory('phtools.surface')
d = {
'accessible_surface_area': sur... | Get input parameters for pore surface binary.
Get input parameters for pore_surface binary from zeo++ output,
while keeping data provenance. |
def get_interfaces_counters(self):
"""Return interfaces counters."""
query = junos_views.junos_iface_counter_table(self.device)
query.get()
interface_counters = {}
for interface, counters in query.items():
interface_counters[interface] = {
k: v if v is... | Return interfaces counters. |
def pop(self, index=-1):
"""See list.pop."""
if not isinstance(index, int):
if PY2:
raise TypeError('an integer is required')
raise TypeError("'str' object cannot be interpreted as an integer")
length = len(self)
if -length <= index < length:
... | See list.pop. |
def _compute_std(self, C, mag, stddevs, idx):
"""
Compute total standard deviation, as explained in table 2, page 67.
"""
if mag > 8.0:
mag = 8.0
for stddev in stddevs:
stddev[idx] += C['C4'] + C['C5'] * mag | Compute total standard deviation, as explained in table 2, page 67. |
def apply(self, transformation, node):
'''
High-level function to call a `transformation' on a `node'.
If the transformation is an analysis, the result of the analysis
is displayed.
'''
assert issubclass(transformation, (Transformation, Analysis))
a = transformati... | High-level function to call a `transformation' on a `node'.
If the transformation is an analysis, the result of the analysis
is displayed. |
def _filters(self):
"""
Additional filters to:
- select particular todo items given with the -i flag,
- hide appropriately tagged items in the absense of the -x flag.
"""
filters = super()._filters()
if self.ids:
def get_todo(p_id):
... | Additional filters to:
- select particular todo items given with the -i flag,
- hide appropriately tagged items in the absense of the -x flag. |
def closest_to_ref(arrays, ref, cutoff=1E-12):
"""
:param arrays: a sequence of R arrays
:param ref: the reference array
:returns: a dictionary with keys rlz, value, and dist
"""
dist = numpy.zeros(len(arrays))
logref = log(ref, cutoff)
for rlz, array in enumerate(arrays):
diff =... | :param arrays: a sequence of R arrays
:param ref: the reference array
:returns: a dictionary with keys rlz, value, and dist |
def update_parent_sequence_map(child_part, delete=False):
"""Updates the child map of a simple sequence assessment assessment part"""
if child_part.has_parent_part():
object_map = child_part.get_assessment_part()._my_map
database = 'assessment_authoring'
collection_type = 'AssessmentPart... | Updates the child map of a simple sequence assessment assessment part |
def as_handler(cls, **initkwargs):
"""Converts the class into an actual handler function that can be used
when registering different types of processors in
:class:`~gears.environment.Environment` class instance.
The arguments passed to :meth:`as_handler` are forwarded to the
con... | Converts the class into an actual handler function that can be used
when registering different types of processors in
:class:`~gears.environment.Environment` class instance.
The arguments passed to :meth:`as_handler` are forwarded to the
constructor of the class. |
def _brahmic(data, scheme_map, **kw):
"""Transliterate `data` with the given `scheme_map`. This function is used
when the source scheme is a Brahmic scheme.
:param data: the data to transliterate
:param scheme_map: a dict that maps between characters in the old scheme
and characters in the... | Transliterate `data` with the given `scheme_map`. This function is used
when the source scheme is a Brahmic scheme.
:param data: the data to transliterate
:param scheme_map: a dict that maps between characters in the old scheme
and characters in the new scheme |
def flatten_dict(value, target_depth=1, depth=None):
"""
Take a hashtable with multiple nested dicts and return a
dict where the keys are a concatenation of each sub-key.
The depth of the returned array is dictated by target_depth, defaulting to 1
ex: {'a' : {'b':1, 'c': 2}} ==> {'... | Take a hashtable with multiple nested dicts and return a
dict where the keys are a concatenation of each sub-key.
The depth of the returned array is dictated by target_depth, defaulting to 1
ex: {'a' : {'b':1, 'c': 2}} ==> {'a_b': 1, 'a_c': 2}
Assumes a constant structure actoss all s... |
def filters_in_format(self, value):
"""
Setter for **self.__filters_in_format** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... | Setter for **self.__filters_in_format** attribute.
:param value: Attribute value.
:type value: unicode |
def start(self, report, run_start_time=None):
"""Start tracking this pants run using the given Report.
`RunTracker.initialize` must have been called first to create the run_info_dir and
run_info. TODO: This lifecycle represents a delicate dance with the `Reporting.initialize`
method, and portions of th... | Start tracking this pants run using the given Report.
`RunTracker.initialize` must have been called first to create the run_info_dir and
run_info. TODO: This lifecycle represents a delicate dance with the `Reporting.initialize`
method, and portions of the `RunTracker` should likely move to `Reporting` inst... |
def translate_chromosome(self, chromosome):
"""
Translate all the genes in a chromosome.
chromosome: a ``chromosomes.Chromosome`` instance to translate
return: a list of translation products for the genes in the chromosome
"""
assert isinstance(chromos... | Translate all the genes in a chromosome.
chromosome: a ``chromosomes.Chromosome`` instance to translate
return: a list of translation products for the genes in the chromosome |
def _connect_loop(self, client_factory):
"""In the current greenlet we try to establish connection with peer.
This greenlet will spin another greenlet to handle incoming data
from the peer once connection is established.
"""
# If current configuration allow, enable active sessio... | In the current greenlet we try to establish connection with peer.
This greenlet will spin another greenlet to handle incoming data
from the peer once connection is established. |
def get_specific_user():
'''
Get a user name for publishing. If you find the user is "root" attempt to be
more specific
'''
user = get_user()
if salt.utils.platform.is_windows():
if _win_current_user_is_admin():
return 'sudo_{0}'.format(user)
else:
env_vars = ('SU... | Get a user name for publishing. If you find the user is "root" attempt to be
more specific |
def expectation_sensitivity(T, a):
r"""Sensitivity of expectation value of observable A=(a_i).
Parameters
----------
T : (M, M) ndarray
Transition matrix
a : (M,) ndarray
Observable, a[i] is the value of the observable at state i.
Returns
-------
S : (M, M) ndarray
... | r"""Sensitivity of expectation value of observable A=(a_i).
Parameters
----------
T : (M, M) ndarray
Transition matrix
a : (M,) ndarray
Observable, a[i] is the value of the observable at state i.
Returns
-------
S : (M, M) ndarray
Sensitivity matrix of the expectati... |
def credits(self, **kwargs):
"""
Get the cast and crew information for a specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self.... | Get the cast and crew information for a specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. |
def dbInsert(self, def_buf, raw_a, raw_b):
""" Call overridden dbExec() with built insert statement.
Args:
def_buf (SerialBlock): Block of read buffer fields to write.
raw_a (str): Hex string of raw A read.
raw_b (str): Hex string of raw B read or empty.
"""
... | Call overridden dbExec() with built insert statement.
Args:
def_buf (SerialBlock): Block of read buffer fields to write.
raw_a (str): Hex string of raw A read.
raw_b (str): Hex string of raw B read or empty. |
def mixup(learn:Learner, alpha:float=0.4, stack_x:bool=False, stack_y:bool=True) -> Learner:
"Add mixup https://arxiv.org/abs/1710.09412 to `learn`."
learn.callback_fns.append(partial(MixUpCallback, alpha=alpha, stack_x=stack_x, stack_y=stack_y))
return learn | Add mixup https://arxiv.org/abs/1710.09412 to `learn`. |
def escape_quotes_if_needed(string):
"""
re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javasc... | re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javascript calls. |
def update_badge_users_count(self):
"""
Denormalizes ``Badge.users.count()`` into ``Bagdes.users_count`` field.
"""
logger.debug('→ Badge %s: syncing users count...', self.slug)
badge, updated = self.badge, False
if not badge:
logger.debug(
'... | Denormalizes ``Badge.users.count()`` into ``Bagdes.users_count`` field. |
def plot_layers(weights, tied_weights=False, channels=1):
'''Create a plot of weights, visualized as "bottom-level" pixel arrays.'''
if hasattr(weights[0], 'get_value'):
weights = [w.get_value() for w in weights]
k = min(len(weights), 9)
imgs = np.eye(weights[0].shape[0])
for i, weight in en... | Create a plot of weights, visualized as "bottom-level" pixel arrays. |
def answer_callback_query(token, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, Tru... | Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
Alternatively, the user can be redirected to the specified Game URL. For this option to work, you mus... |
def bfloat16_activations_var_getter(getter, *args, **kwargs):
"""A custom getter function for float32 parameters and bfloat16 activations.
Args:
getter: custom getter
*args: arguments
**kwargs: keyword arguments
Returns:
variables with the correct dtype.
Raises:
KeyError: if "dtype" is not ... | A custom getter function for float32 parameters and bfloat16 activations.
Args:
getter: custom getter
*args: arguments
**kwargs: keyword arguments
Returns:
variables with the correct dtype.
Raises:
KeyError: if "dtype" is not provided as a kwarg. |
def to_file_mode(self):
""" Write all the messages to files """
for message_no in range(len(self.messages)):
self.__to_file(message_no) | Write all the messages to files |
def guard_rollback_to_open(worksheet):
"""Return whether 'rollback_to_receive' transition can be performed or not
"""
for analysis in worksheet.getAnalyses():
if api.get_review_status(analysis) in ["assigned"]:
return True
return False | Return whether 'rollback_to_receive' transition can be performed or not |
def data(self, index, role=Qt.DisplayRole):
"""Qt Override."""
row = index.row()
if not index.isValid() or not (0 <= row < len(self.servers)):
return to_qvariant()
server = self.servers[row]
column = index.column()
if role == Qt.DisplayRole:
if c... | Qt Override. |
def intersectingPoint(self, p):
"""
given a point, get intervals in the tree that are intersected.
:param p: intersection point
:return: the list of intersected intervals
"""
# perfect match
if p == self.data.mid:
return self.data.ends
if p > self.data.mid:
# we know all in... | given a point, get intervals in the tree that are intersected.
:param p: intersection point
:return: the list of intersected intervals |
def build(self):
"""Do the query."""
result = []
for entry in self.sequence:
ignore = False
for filter_function in self.filter_functions:
if not filter_function(entry):
ignore = True
break
if not ignore:
... | Do the query. |
def grade_or_comment_on_submission_courses(self, user_id, course_id, assignment_id, comment_file_ids=None, comment_group_comment=None, comment_media_comment_id=None, comment_media_comment_type=None, comment_text_comment=None, include_visibility=None, rubric_assessment=None, submission_excuse=None, submission_posted_gra... | Grade or comment on a submission.
Comment on and/or update the grading for a student's assignment submission.
If any submission or rubric_assessment arguments are provided, the user
must have permission to manage grades in the appropriate context (course or
section). |
def refresh(self, *objects, **kwargs):
'''
This method is an alternate API for refreshing many entities (possibly
not tracked by the session). You can call::
session.refresh(obj)
session.refresh(obj1, obj2, ...)
session.refresh([obj1, obj2, ...])
And... | This method is an alternate API for refreshing many entities (possibly
not tracked by the session). You can call::
session.refresh(obj)
session.refresh(obj1, obj2, ...)
session.refresh([obj1, obj2, ...])
And all provided entities will be reloaded from Redis.
... |
def _cuda_get_gpu_spec_string(gpu_ids=None):
"""
Build a GPU id string to be used for CUDA_VISIBLE_DEVICES.
"""
if gpu_ids is None:
return ''
if isinstance(gpu_ids, list):
return ','.join(str(gpu_id) for gpu_id in gpu_ids)
if isinstance(gpu_ids, int):
return str(gpu_id... | Build a GPU id string to be used for CUDA_VISIBLE_DEVICES. |
def retrieve_commands(obj):
"""Retrieve all commands and help texts from an API object."""
commands = {} # Name and help
for func in obj.__dict__:
if not inspect.isfunction(obj.__dict__[func]) and \
not isinstance(obj.__dict__[func], property):
continue
if func.starts... | Retrieve all commands and help texts from an API object. |
def asyncPipeUniq(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously filters out non unique items according
to the specified field. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items
conf : {'fiel... | An operator that asynchronously filters out non unique items according
to the specified field. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items
conf : {'field': {'type': 'text', 'value': <field to be unique>}}
returns
----... |
def _get_magnitude_scaling_term(self, C, rup):
"""
Returns the magnitude scling term defined in equation (2)
"""
dmag = rup.mag - C["Mh"]
if rup.mag <= C["Mh"]:
mag_term = (C["e4"] * dmag) + (C["e5"] * (dmag ** 2.0))
else:
mag_term = C["e6"] * dmag... | Returns the magnitude scling term defined in equation (2) |
def _appendGlyph(self, other, offset=None):
"""
Subclasses may override this method.
"""
other = other.copy()
if offset != (0, 0):
other.moveBy(offset)
for contour in other.contours:
self.appendContour(contour)
for component in other.compon... | Subclasses may override this method. |
def platform_path(path):
r"""
Returns platform specific path for pyinstaller usage
Args:
path (str):
Returns:
str: path2
CommandLine:
python -m utool.util_path --test-platform_path
Example:
>>> # ENABLE_DOCTEST
>>> # FIXME: find examples of the wird pa... | r"""
Returns platform specific path for pyinstaller usage
Args:
path (str):
Returns:
str: path2
CommandLine:
python -m utool.util_path --test-platform_path
Example:
>>> # ENABLE_DOCTEST
>>> # FIXME: find examples of the wird paths this fixes (mostly on win... |
def status(self, status_id, raise_exception_on_failure=False):
"""Return the status of the generation job."""
query = {"output": "json", "user_credentials": self.api_key}
resp = requests.get(
"%sstatus/%s" % (self._url, status_id), params=query, timeout=self._timeout
)
... | Return the status of the generation job. |
def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row):
"""MOSEK requires a specific sparse format to define the lower-triangular
part of a symmetric matrix. This function does the conversion from the
sparse upper triangular matrix format of Ncpol2SDPA.
"""
block_index, i, j = con... | MOSEK requires a specific sparse format to define the lower-triangular
part of a symmetric matrix. This function does the conversion from the
sparse upper triangular matrix format of Ncpol2SDPA. |
def fake2db_sqlite_initiator(self, number_of_rows, name=None, custom=None):
'''Main handler for the operation
'''
rows = number_of_rows
conn = self.database_caller_creator(name)
if custom:
self.custom_db_creator(rows, conn, custom)
conn.close()
... | Main handler for the operation |
def serialize_for_transport(obj_pyxb, pretty=False, strip_prolog=False, xslt_url=None):
"""Serialize PyXB object to XML ``bytes`` with UTF-8 encoding for transport over the
network, filesystem storage and other machine usage.
Args:
obj_pyxb: PyXB object
PyXB object to serialize.
pretty... | Serialize PyXB object to XML ``bytes`` with UTF-8 encoding for transport over the
network, filesystem storage and other machine usage.
Args:
obj_pyxb: PyXB object
PyXB object to serialize.
pretty: bool
True: Use pretty print formatting for human readability.
strip_prolog:
... |
def nvmlDeviceGetHandleByIndex(index):
r"""
/**
* Acquire the handle for a particular device, based on its index.
*
* For all products.
*
* Valid indices are derived from the \a accessibleDevices count returned by
* \ref nvmlDeviceGetCount(). For example, if \a accessibleDevices ... | r"""
/**
* Acquire the handle for a particular device, based on its index.
*
* For all products.
*
* Valid indices are derived from the \a accessibleDevices count returned by
* \ref nvmlDeviceGetCount(). For example, if \a accessibleDevices is 2 the valid indices
* are 0 and 1... |
def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
procname -- string, name of procedure to execute on server
args -- Sequence of parameters to use with procedure
Returns the original args.
Compatibility warning: PEP-249 specifies t... | Execute stored procedure procname with args
procname -- string, name of procedure to execute on server
args -- Sequence of parameters to use with procedure
Returns the original args.
Compatibility warning: PEP-249 specifies that any modified
parameters must be returne... |
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
... | Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed. |
def run(self, timeout=None):
"""
Run the map/reduce operation synchronously. Returns a list of
results, or a list of links if the last phase is a link phase.
Shortcut for :meth:`riak.client.RiakClient.mapred`.
:param timeout: Timeout in milliseconds
:type timeout: intege... | Run the map/reduce operation synchronously. Returns a list of
results, or a list of links if the last phase is a link phase.
Shortcut for :meth:`riak.client.RiakClient.mapred`.
:param timeout: Timeout in milliseconds
:type timeout: integer, None
:rtype: list |
def _replace_docstring_header(paragraph):
"""Process NumPy-like function docstrings."""
# Replace Markdown headers in docstrings with light headers in bold.
paragraph = re.sub(_docstring_header_pattern,
r'*\1*',
paragraph,
)
paragrap... | Process NumPy-like function docstrings. |
def set_dimensions(self, variables, unlimited_dims=None):
"""
This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited... | This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited_dims : list-like
List of dimension names that should be treated a... |
def getCSV(self):
"""
Returns
-------
filename: str
"""
import getpass
import gspread
user = raw_input("Insert Google username:")
password = getpass.getpass(prompt="Insert password:")
name = raw_input("SpreadSheet filename on Drive:")
... | Returns
-------
filename: str |
def set_tunnel(self, host, port=None, headers=None):
""" Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request.
"""
self._tunnel_host = host
self._tunnel_port = port
... | Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request. |
def add_crs(op, element, **kwargs):
"""
Converts any elements in the input to their equivalent geotypes
if given a coordinate reference system.
"""
return element.map(lambda x: convert_to_geotype(x, kwargs.get('crs')), Element) | Converts any elements in the input to their equivalent geotypes
if given a coordinate reference system. |
def get_alignment_stream(self, plate=None, plate_value=None):
"""
Gets the alignment stream for a particular plate value
:param plate: The plate on which the alignment node lives
:param plate_value: The plate value to select the stream from the node
:return: The alignment stream... | Gets the alignment stream for a particular plate value
:param plate: The plate on which the alignment node lives
:param plate_value: The plate value to select the stream from the node
:return: The alignment stream |
def formatter(self, api_client, data, newval):
"""Parse additional url fields and map them to inputs
Attempt to create a dictionary with keys being user input, and
response being the returned URL
"""
if newval is None:
return None
user_param = data['_paramAd... | Parse additional url fields and map them to inputs
Attempt to create a dictionary with keys being user input, and
response being the returned URL |
def overlay_gateway_attach_rbridge_id_rb_add(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | Auto Generated Code |
def textForSaving(self):
"""Get text with correct EOL symbols. Use this method for saving a file to storage
"""
lines = self.text.splitlines()
if self.text.endswith('\n'): # splitlines ignores last \n
lines.append('')
return self.eol.join(lines) + self.eol | Get text with correct EOL symbols. Use this method for saving a file to storage |
def packetToDict(pkt):
"""
Given a packet, this turns it into a dictionary ... is this useful?
in: packet, array of numbers
out: dictionary (key, value)
"""
d = {
'id': pkt[4],
# 'instruction': xl320.InstrToStr[pkt[7]],
# 'length': (pkt[6] << 8) + pkt[5],
# 'params': pkt[8:-2],
'Model Number': (pkt[10... | Given a packet, this turns it into a dictionary ... is this useful?
in: packet, array of numbers
out: dictionary (key, value) |
def get_breaks_lno(self, filename):
"""List all line numbers that have a breakpoint"""
return list(
filter(
lambda x: x is not None, [
getattr(breakpoint, 'line', None)
for breakpoint in self.breakpoints
if breakpoin... | List all line numbers that have a breakpoint |
def exec_prog(args):
"""Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute.
"""
program_name = args[0]
logging.info(" ".join(args))
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
if not os.acces... | Run a subprocess, check for .OK and raise error if does not exist.
args: list of arguments, for value is the command to execute. |
def match_to_dict(match):
"""Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
"""
... | Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([]) |
def helper_parallel_lines(start0, end0, start1, end1, filename):
"""Image for :func:`.parallel_lines_parameters` docstring."""
if NO_IMAGES:
return
figure = plt.figure()
ax = figure.gca()
points = stack1d(start0, end0, start1, end1)
ax.plot(points[0, :2], points[1, :2], marker="o")
... | Image for :func:`.parallel_lines_parameters` docstring. |
def selected_impact_function_constraints(self):
"""Obtain impact function constraints selected by user.
:returns: Tuple of metadata of hazard, exposure,
hazard layer geometry and exposure layer geometry
:rtype: tuple
"""
hazard = self.step_fc_functions1.selected_val... | Obtain impact function constraints selected by user.
:returns: Tuple of metadata of hazard, exposure,
hazard layer geometry and exposure layer geometry
:rtype: tuple |
def apply(self, actual_time):
"""Check time and apply faults"""
if self.time != actual_time:
self.time = actual_time
else:
return
for i in range(self.n):
if self.tf[i] == self.time:
logger.info(
' <Fault> Applying f... | Check time and apply faults |
def create_request_token_response(self, uri, http_method='GET', body=None,
headers=None, credentials=None):
"""Create a request token response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTT... | Create a request token response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:pa... |
def clear_reply_handlers_by_message_id(self, message_id):
"""
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers
"""
self.reply_handlers[message_id] ... | Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers |
def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion."""
# Check for read-only attribute
default_warning_message = (
"Unab... | Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion. |
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
... | Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
... |
def plot_eigh(self, colorbar=True, cb_orientation='vertical',
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel='Longitude', ylabel='Latitude',
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
"""
Plo... | Plot the two eigenvalues and maximum absolute value eigenvalue of the
horizontal tensor.
Usage
-----
x.plot_eigh([tick_interval, minor_tick_interval, xlabel, ylabel,
colorbar, cb_orientation, cb_label, axes_labelsize,
tick_labelsize, show, fname... |
def ecdsa_sign(private_key, data, hash_algorithm):
"""
Generates an ECDSA signature in pure Python (thus slow)
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode str... | Generates an ECDSA signature in pure Python (thus slow)
:param private_key:
The PrivateKey to generate the signature with
:param data:
A byte string of the data the signature is for
:param hash_algorithm:
A unicode string of "sha1", "sha256", "sha384" or "sha512"
:raises:
... |
def addmem(self, data, size):
"""
Add block of memory to the end of the message, as a new frame.
Returns 0 on success, -1 on error.
"""
return lib.zmsg_addmem(self._as_parameter_, data, size) | Add block of memory to the end of the message, as a new frame.
Returns 0 on success, -1 on error. |
def _set_affiliation(self, v, load=False):
"""
Setter method for affiliation, mapped from YANG variable /universe/individual/affiliation (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_affiliation is considered as a private
method. Backends looking ... | Setter method for affiliation, mapped from YANG variable /universe/individual/affiliation (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_affiliation is considered as a private
method. Backends looking to populate this variable should
do so via calling this... |
def add_identity(session, uidentity, identity_id, source,
name=None, email=None, username=None):
"""Add an identity to the session.
This function adds a new identity to the session using
`identity_id` as its identifier. The new identity will
also be linked to the unique identity object... | Add an identity to the session.
This function adds a new identity to the session using
`identity_id` as its identifier. The new identity will
also be linked to the unique identity object of `uidentity`.
Neither the values given to `identity_id` nor to `source` can
be `None` or empty. Moreover, `na... |
def pack_req(cls, is_unlock, password_md5, conn_id):
"""Convert from user request for trading days to PLS request"""
from futuquant.common.pb.Trd_UnlockTrade_pb2 import Request
req = Request()
req.c2s.unlock = is_unlock
req.c2s.pwdMD5 = password_md5
return pack_pb_req(re... | Convert from user request for trading days to PLS request |
def unresolve_filename(self, package_dir, filename):
"""Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filen... | Retrieves the probable source path from the output filename. Pass
in a .css path to get out a .scss path.
:param package_dir: the path of the package directory
:type package_dir: :class:`str`
:param filename: the css filename
:type filename: :class:`str`
:returns: the s... |
def chi_square_calc(classes, table, TOP, P, POP):
"""
Calculate chi-squared.
:param classes: confusion matrix classes
:type classes : list
:param table: confusion matrix table
:type table : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:typ... | Calculate chi-squared.
:param classes: confusion matrix classes
:type classes : list
:param table: confusion matrix table
:type table : dict
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
... |
def reset_socat(use_sudo=False):
"""
Finds and closes all processes of `socat`.
:param use_sudo: Use `sudo` command. As Docker-Fabric does not run `socat` with `sudo`, this is by default set to
``False``. Setting it to ``True`` could unintentionally remove instances from other users.
:type use_su... | Finds and closes all processes of `socat`.
:param use_sudo: Use `sudo` command. As Docker-Fabric does not run `socat` with `sudo`, this is by default set to
``False``. Setting it to ``True`` could unintentionally remove instances from other users.
:type use_sudo: bool |
def is_client_method_whitelisted(request: AxesHttpRequest) -> bool:
"""
Check if the given request uses a whitelisted method.
"""
if settings.AXES_NEVER_LOCKOUT_GET and request.method == 'GET':
return True
return False | Check if the given request uses a whitelisted method. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.