code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def mkdir_p(dir):
'''like mkdir -p'''
if not dir:
return
if dir.endswith("/") or dir.endswith("\\"):
mkdir_p(dir[:-1])
return
if os.path.isdir(dir):
return
mkdir_p(os.path.dirname(dir))
try:
os.mkdir(dir)
except Exception:
pass | like mkdir -p |
def read_annotation_file(annotation_file, annotation_type):
"""read_annotation_file(annotation_file, annotation_type) -> annotations
Reads annotations from the given ``annotation_file``.
The way, how annotations are read depends on the given ``annotation_type``.
Depending on the type, one or several annotation... | read_annotation_file(annotation_file, annotation_type) -> annotations
Reads annotations from the given ``annotation_file``.
The way, how annotations are read depends on the given ``annotation_type``.
Depending on the type, one or several annotations might be present in the annotation file.
Currently, these var... |
def op_at_on(operation: ops.Operation,
time: Timestamp,
device: Device):
"""Creates a scheduled operation with a device-determined duration."""
return ScheduledOperation(time,
device.duration_of(operation),
... | Creates a scheduled operation with a device-determined duration. |
def addPoints(self, points, board_size=None):
'''
add corner points directly instead of extracting them from
image
points = ( (0,1), (...),... ) [x,y]
'''
self.opts['foundPattern'].append(True)
self.findCount += 1
if board_size is not None:
... | add corner points directly instead of extracting them from
image
points = ( (0,1), (...),... ) [x,y] |
def links(self, obj):
"""
Return all nodes connected by the given hyperedge or all hyperedges
connected to the given hypernode.
@type obj: hyperedge
@param obj: Object identifier.
@rtype: list
@return: List of node objects linked to the given h... | Return all nodes connected by the given hyperedge or all hyperedges
connected to the given hypernode.
@type obj: hyperedge
@param obj: Object identifier.
@rtype: list
@return: List of node objects linked to the given hyperedge. |
def raw(key=None):
'''
Return the raw pillar data that is available in the module. This will
show the pillar as it is loaded as the __pillar__ dict.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw da... | Return the raw pillar data that is available in the module. This will
show the pillar as it is loaded as the __pillar__ dict.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.... |
def build_environ(self, sock_file, conn):
""" Build the execution environment. """
# Grab the request line
request = self.read_request_line(sock_file)
# Copy the Base Environment
environ = self.base_environ.copy()
# Grab the headers
for k, v in self.read_headers... | Build the execution environment. |
def _image_width(image):
"""
Returns the width of the image found at the path supplied by `image`
relative to your project's images directory.
"""
if not Image:
raise Exception("Images manipulation require PIL")
file = StringValue(image).value
path = None
try:
width = spr... | Returns the width of the image found at the path supplied by `image`
relative to your project's images directory. |
def _needle(fa, fb, needlefile, a, b, results):
"""
Run single needle job
"""
from Bio.Emboss.Applications import NeedleCommandline
needle_cline = NeedleCommandline(asequence=fa, bsequence=fb,
gapopen=10, gapextend=0.5, outfile=needlefile)
stdout, stderr = needle_cline()... | Run single needle job |
def get_plug_mro(self, plug_type):
"""Returns a list of names identifying the plug classes in the plug's MRO.
For example:
['openhtf.plugs.user_input.UserInput']
Or:
['openhtf.plugs.user_input.UserInput',
'my_module.advanced_user_input.AdvancedUserInput']
"""
ignored_classe... | Returns a list of names identifying the plug classes in the plug's MRO.
For example:
['openhtf.plugs.user_input.UserInput']
Or:
['openhtf.plugs.user_input.UserInput',
'my_module.advanced_user_input.AdvancedUserInput'] |
def add_input(self, line):
"""
Appends {line} of input to the input instantly. (directly hits the database)
:param line: the line of text to append
:return: None
"""
Deployment.objects.filter(pk=self.id).update(input=CF('input')+line) | Appends {line} of input to the input instantly. (directly hits the database)
:param line: the line of text to append
:return: None |
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %... | Stop the daemon |
def _decompose_and_get_unitary(val: Union['cirq.Operation', 'cirq.Gate']
) -> np.ndarray:
"""Try to decompose a cirq.Operation or cirq.Gate, and return its unitary
if it exists.
Returns:
If `val` can be decomposed into unitaries, calculate the resulting
unitar... | Try to decompose a cirq.Operation or cirq.Gate, and return its unitary
if it exists.
Returns:
If `val` can be decomposed into unitaries, calculate the resulting
unitary and return it. If it doesn't exist, None is returned. |
def get_connection(self, is_read_only=False) -> redis.StrictRedis:
"""
Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration.
:type is_read_only: bool
:param is_read_only: In case of redis sentinel, it returns connection to slave
... | Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration.
:type is_read_only: bool
:param is_read_only: In case of redis sentinel, it returns connection to slave
:return: Returns a StrictRedis connection |
def _send_post_request(self, path, data, headers):
"""
Sends the POST request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: Either a dict, or bytes.
:type data: dict or bytes
:param dict headers:... | Sends the POST request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param data: Either a dict, or bytes.
:type data: dict or bytes
:param dict headers: A dict of headers to send with the request.
:rtype: str
... |
def mean_size_ISO(self, k, r):
'''
>>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6)
>>> psd.mean_size_ISO(1, 2)
4.412484512922977e-06
'''
p = k + r
q = r
return self.mean_size(p=p, q=q) | >>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6)
>>> psd.mean_size_ISO(1, 2)
4.412484512922977e-06 |
def unescape(self):
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape()
'Main » <em>About</em>'
"""
from ._constants import HTML_ENTITIES
def hand... | Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape()
'Main » <em>About</em>' |
def run(self):
"""Processing the pipeline."""
self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
self.logger.info("Running on platform %s", platform.platform())
self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())
configuration = self.l... | Processing the pipeline. |
def _on_disconnect(_loop, adapter, _adapter_id, conn_id):
"""Callback when a device disconnects unexpectedly."""
conn_string = adapter._get_property(conn_id, 'connection_string')
if conn_string is None:
adapter._logger.debug("Dropping disconnect notification with unknown conn_id=%s", conn_id)
... | Callback when a device disconnects unexpectedly. |
def _check_expr_filename(expr):
"""
Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None
"""
expr_lst = expr.split()
f = [x for x in expr_lst if x not in DATA_FRAMES and x.endswith... | Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None |
def apply_changes(self, event):
"""
applies the changes in the various attribute boxes of this object to all highlighted fit objects in the logger, these changes are reflected both in this object and in the Zeq_GUI parent object.
@param: event -> the wx.ButtonEvent that triggered this function
... | applies the changes in the various attribute boxes of this object to all highlighted fit objects in the logger, these changes are reflected both in this object and in the Zeq_GUI parent object.
@param: event -> the wx.ButtonEvent that triggered this function |
def remove(self):
"""
Deletes itself.
:return: None
"""
for e in self._entries:
e.grid_forget()
e.destroy()
self._remove_btn.grid_forget()
self._remove_btn.destroy()
self.deleted = True
if self._remove_callback:
... | Deletes itself.
:return: None |
def projection(x, A, b):
""" Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b.
:param x: vector
:param A, b: matrix and array characterizing the constraints on x (A.x = b)
:return x_hat: optimum angle vector, minimizing cost.
:return cost: least square error of xhat, x
:re... | Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b.
:param x: vector
:param A, b: matrix and array characterizing the constraints on x (A.x = b)
:return x_hat: optimum angle vector, minimizing cost.
:return cost: least square error of xhat, x
:return constraints_error: mse of co... |
def get_definition_location(project, source_code, offset,
resource=None, maxfixes=1):
"""Return the definition location of the python name at `offset`
Return a (`rope.base.resources.Resource`, lineno) tuple. If no
`resource` is given and the definition is inside the same module... | Return the definition location of the python name at `offset`
Return a (`rope.base.resources.Resource`, lineno) tuple. If no
`resource` is given and the definition is inside the same module,
the first element of the returned tuple would be `None`. If the
location cannot be determined ``(None, None)``... |
def make_predicate_object_combinator(function, p, o):
""" Combinator to hold predicate object pairs until a subject is supplied and then
call a function that accepts a subject, predicate, and object.
Create a combinator to defer production of a triple until the missing pieces are supplied.
... | Combinator to hold predicate object pairs until a subject is supplied and then
call a function that accepts a subject, predicate, and object.
Create a combinator to defer production of a triple until the missing pieces are supplied.
Note that the naming here tells you what is stored IN the comb... |
def wait_for_message_from(address, wait_for_s=config.FOREVER, autoreply=False):
"""Wait for a message
:param address: a nw0 address (eg from `nw0.advertise`)
:param wait_for_s: how many seconds to wait for a message before giving up [default: forever]
:param autoreply: whether to send an empty repl... | Wait for a message
:param address: a nw0 address (eg from `nw0.advertise`)
:param wait_for_s: how many seconds to wait for a message before giving up [default: forever]
:param autoreply: whether to send an empty reply [default: No]
:returns: the message received from another address or None if... |
def inspecting_client_factory(self, host, port, ioloop_set_to):
"""Return an instance of :class:`ReplyWrappedInspectingClientAsync` or similar
Provided to ease testing. Dynamically overriding this method after instantiation
but before start() is called allows for deep brain surgery. See
... | Return an instance of :class:`ReplyWrappedInspectingClientAsync` or similar
Provided to ease testing. Dynamically overriding this method after instantiation
but before start() is called allows for deep brain surgery. See
:class:`katcp.fake_clients.fake_inspecting_client_factory` |
def doArc8(arcs, domains, assignments):
"""
Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused.
"""
check = dict.fromkeys(domains, True)
while check:
variable, _ = check.popitem()
if variable not in arcs or variable in assignments:
... | Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused. |
def plural(formatter, value, name, option, format):
"""Chooses different textension for locale-specific pluralization rules.
Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}`
Example::
>>> smart.format(u'There {num:is an item|are {} items}.', num=1}
There is an item.
>>> smart.form... | Chooses different textension for locale-specific pluralization rules.
Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}`
Example::
>>> smart.format(u'There {num:is an item|are {} items}.', num=1}
There is an item.
>>> smart.format(u'There {num:is an item|are {} items}.', num=10}
... |
def SetColumns( self, columns, sortOrder=None ):
"""Set columns to a set of values other than the originals and recreates column controls"""
self.columns = columns
self.sortOrder = [(x.defaultOrder,x) for x in self.columns if x.sortDefault]
self.CreateColumns() | Set columns to a set of values other than the originals and recreates column controls |
def _parse_pairwise_input(indices1, indices2, MDlogger, fname=''):
r"""For input of pairwise type (distances, inverse distances, contacts) checks the
type of input the user gave and reformats it so that :py:func:`DistanceFeature`,
:py:func:`InverseDistanceFeature`, and ContactFeature can work.
... | r"""For input of pairwise type (distances, inverse distances, contacts) checks the
type of input the user gave and reformats it so that :py:func:`DistanceFeature`,
:py:func:`InverseDistanceFeature`, and ContactFeature can work.
In case the input isn't already a list of distances, this function ... |
def star(self, login, repo):
"""Star to login/repo
:param str login: (required), owner of the repo
:param str repo: (required), name of the repo
:return: bool
"""
resp = False
if login and repo:
url = self._build_url('user', 'starred', login, repo)
... | Star to login/repo
:param str login: (required), owner of the repo
:param str repo: (required), name of the repo
:return: bool |
def covariance_points(self,x0,y0,xother,yother):
""" Get the covariance between point x0,y0 and the points
contained in xother, yother.
Parameters
----------
x0 : (float)
x-coordinate
y0 : (float)
y-coordinate
xother : (iterable of floats)... | Get the covariance between point x0,y0 and the points
contained in xother, yother.
Parameters
----------
x0 : (float)
x-coordinate
y0 : (float)
y-coordinate
xother : (iterable of floats)
x-coordinate of other points
yother : (i... |
def _rank_optimize(self):
"""optimize ranking by pushing long edges toward lower layers as much as possible.
see other interersting network flow solver to minimize total edge length
(http://jgaa.info/accepted/2005/EiglspergerSiebenhallerKaufmann2005.9.3.pdf)
"""
assert self.dag
... | optimize ranking by pushing long edges toward lower layers as much as possible.
see other interersting network flow solver to minimize total edge length
(http://jgaa.info/accepted/2005/EiglspergerSiebenhallerKaufmann2005.9.3.pdf) |
def inputindexbytemplate(project, user, inputtemplate):
"""Retrieve sorted index for the specified input template"""
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'input/'
for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate.... | Retrieve sorted index for the specified input template |
def init_localization():
'''prepare l10n'''
locale.setlocale(locale.LC_ALL, '') # User's preferred locale, according to environment
# Use first two characters of country code, defaulting to 'en' in the absence of a preference
loc = locale.getlocale()
lang = loc[0][0:2] if loc[0] else 'en'
filen... | prepare l10n |
def uninstall(cert_name,
keychain="/Library/Keychains/System.keychain",
keychain_password=None):
'''
Uninstall a certificate from a keychain
cert_name
The name of the certificate to remove
keychain
The keychain to install the certificate to, this defaults to... | Uninstall a certificate from a keychain
cert_name
The name of the certificate to remove
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
keychain_password
If your keychain is likely to be locked pass the password and ... |
def _get_prop_infos(self, prop):
"""
Return the infos configured for this specific prop, merging the
different configuration level
"""
info_dict = self.get_info_field(prop)
main_infos = info_dict.get('export', {}).copy()
infos = main_infos.get(self.config_key, {})... | Return the infos configured for this specific prop, merging the
different configuration level |
def run_and_measure_payload(quil_program, qubits, trials, random_seed):
"""REST payload for :py:func:`ForestConnection._run_and_measure`"""
if not quil_program:
raise ValueError("You have attempted to run an empty program."
" Please provide gates or measure instructions to your ... | REST payload for :py:func:`ForestConnection._run_and_measure` |
def _get_validation(self, method, param):
"""Return the correct validations dictionary for this parameter.
First checks the method itself and then its class. If no validation is
defined for this parameter, None is returned.
:param method: A function to get the validation information fro... | Return the correct validations dictionary for this parameter.
First checks the method itself and then its class. If no validation is
defined for this parameter, None is returned.
:param method: A function to get the validation information from.
:type method: Python function
:par... |
def __create_vector(self, *vec) -> Vector3:
"""
Converts a variety of vector types to a flatbuffer Vector3.
Supports Flatbuffers Vector3, cTypes Vector3, list/tuple of numbers, or passing x,y,z (z optional)
"""
import numbers
if len(vec) == 1:
if hasattr(vec[... | Converts a variety of vector types to a flatbuffer Vector3.
Supports Flatbuffers Vector3, cTypes Vector3, list/tuple of numbers, or passing x,y,z (z optional) |
def find_module(self, fullname, path=None):
"""
Looks up the table based on the module path.
"""
if not fullname.startswith(self._module_name + '.'):
# Not a quilt submodule.
return None
submodule = fullname[len(self._module_name) + 1:]
parts = su... | Looks up the table based on the module path. |
def getUpperDetectionLimit(self):
"""Returns the Upper Detection Limit (UDL) that applies to this
analysis in particular. If no value set or the analysis service
doesn't allow manual input of detection limits, returns the value set
by default in the Analysis Service
"""
i... | Returns the Upper Detection Limit (UDL) that applies to this
analysis in particular. If no value set or the analysis service
doesn't allow manual input of detection limits, returns the value set
by default in the Analysis Service |
def skip(self, steps=1):
"""Skip ahead by 'steps' tokens."""
for _ in six.moves.range(steps):
self.next_token() | Skip ahead by 'steps' tokens. |
def scrypt_mcf_check(mcf, password):
"""Returns True if the password matches the given MCF hash"""
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
... | Returns True if the password matches the given MCF hash |
def glover_hrf(tr, oversampling=50, time_length=32., onset=0.):
""" Implementation of the Glover hrf model
Parameters
----------
tr : float
scan repeat time, in seconds
oversampling : int, optional
temporal oversampling factor
time_length : float, optional
hrf kernel l... | Implementation of the Glover hrf model
Parameters
----------
tr : float
scan repeat time, in seconds
oversampling : int, optional
temporal oversampling factor
time_length : float, optional
hrf kernel length, in seconds
onset : float, optional
onset of the resp... |
def parse_item(self, item):
"""
Receives an item and returns a dictionary of field values.
"""
# Create a dictionary from values for each field
parsed_data = {}
for field_name in self.fields:
# A field-name may be mapped to another identifier on the s... | Receives an item and returns a dictionary of field values. |
def plot_track(track, filename=None, beat_resolution=None, downbeats=None,
preset='default', cmap='Blues', xtick='auto', ytick='octave',
xticklabel=True, yticklabel='auto', tick_loc=None,
tick_direction='in', label='both', grid='both',
grid_linestyle=':', grid... | Plot the pianoroll or save a plot of the pianoroll.
Parameters
----------
filename :
The filename to which the plot is saved. If None, save nothing.
beat_resolution : int
The number of time steps used to represent a beat. Required and only
effective when `xtick` is 'beat'.
d... |
def stop_instance(self, instance_id):
"""
Stops the instance gracefully.
:param str instance_id: instance identifier
"""
self._init_az_api()
cluster_name, node_name = instance_id
self._init_inventory(cluster_name)
for name, api_version in [
... | Stops the instance gracefully.
:param str instance_id: instance identifier |
def Build(self):
"""Builds a client config dictionary used in the OAuth 2.0 flow."""
if all((self.client_type, self.client_id, self.client_secret,
self.auth_uri, self.token_uri)):
client_config = {
self.client_type: {
'client_id': self.client_id,
'client_s... | Builds a client config dictionary used in the OAuth 2.0 flow. |
def all_properties(self):
"""Get all properties of a given index"""
properties = {}
r = self.requests.get(self.index_url + "/_mapping", headers=HEADER_JSON, verify=False)
try:
r.raise_for_status()
r_json = r.json()
if 'items' not in r_json[self.index... | Get all properties of a given index |
def role_create(role, principal, endpoint_id):
"""
Executor for `globus endpoint role show`
"""
principal_type, principal_val = principal
client = get_client()
if principal_type == "identity":
principal_val = maybe_lookup_identity_id(principal_val)
if not principal_val:
... | Executor for `globus endpoint role show` |
def convert_attribute_tag_to_name(value):
"""
A utility function that converts an attribute tag into the corresponding
attribute name string.
For example: enums.Tags.STATE -> 'State'
Args:
value (enum): The Tags enumeration value of the attribute.
Returns:
string: The attribut... | A utility function that converts an attribute tag into the corresponding
attribute name string.
For example: enums.Tags.STATE -> 'State'
Args:
value (enum): The Tags enumeration value of the attribute.
Returns:
string: The attribute name string that corresponds to the attribute
... |
def _find_mime_parameters(tokenlist, value):
"""Do our best to find the parameters in an invalid MIME header
"""
while value and value[0] != ';':
if value[0] in PHRASE_ENDS:
tokenlist.append(ValueTerminal(value[0], 'misplaced-special'))
value = value[1:]
else:
... | Do our best to find the parameters in an invalid MIME header |
def K_globe_stop_check_valve_Crane(D1, D2, fd=None, style=0):
r'''Returns the loss coefficient for a globe stop check valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^2) ... | r'''Returns the loss coefficient for a globe stop check valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^2) + (1-\beta^2)^2\right]}{\beta^4}
Style 0 is the stand... |
def individual_weights(self):
"""Read individual weights from the load cells in grams.
Returns
-------
weight : float
The sensor weight in grams.
"""
weights = self._raw_weights()
if weights.shape[1] == 0:
return np.zeros(weights.shape[0])... | Read individual weights from the load cells in grams.
Returns
-------
weight : float
The sensor weight in grams. |
def list_licenses(page_size=200, page_index=0, sort="", q=""):
"""
List all Licenses
"""
response = utils.checked_api_call(pnc_api.licenses, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content) | List all Licenses |
def load_files(self, configs):
""" Read configs set into storage """
logger.debug("Reading configs: %s", configs)
config_filenames = [resource.resource_filename(config) for config in configs]
try:
self.config.read(config_filenames)
except Exception as e... | Read configs set into storage |
def write(self, data):
"""Provide as convenience for influxdb v0.9.0, this may change."""
self.request(
url="write",
method='POST',
params=None,
data=data,
expected_response_code=200
)
return True | Provide as convenience for influxdb v0.9.0, this may change. |
def _annotate(
cls,
item,
timestamp,
stack_depth
):
"""
:param itemt: A LogItemTHE TYPE OF MESSAGE
:param stack_depth: FOR TRACKING WHAT LINE THIS CAME FROM
:return:
"""
item.timestamp = timestamp
item.machine = machine_metadat... | :param itemt: A LogItemTHE TYPE OF MESSAGE
:param stack_depth: FOR TRACKING WHAT LINE THIS CAME FROM
:return: |
def blockreplace(marker_start,
marker_end,
content='',
append_if_not_found=False,
prepend_if_not_found=False,
show_changes=True,
append_newline=False,
source='running',
path=None,
... | .. versionadded:: 2019.2.0
Replace content of the configuration source, delimited by the line markers.
A block of content delimited by comments can help you manage several lines
without worrying about old entries removal.
marker_start
The line content identifying a line as the start of the co... |
def find_statements(self, query, language='spo', type='triples', flush=None,
limit=None):
"""
Run a query in a format supported by the Fedora Resource Index (e.g., SPO
or Sparql) and return the results.
:param query: query as a string
:param language: que... | Run a query in a format supported by the Fedora Resource Index (e.g., SPO
or Sparql) and return the results.
:param query: query as a string
:param language: query language to use; defaults to 'spo'
:param type: type of query - tuples or triples; defaults to 'triples'
:param flu... |
def implode(self, env):
"""
remove all trace of this cart: delete the file(s) on the local
filesystem and delete the entry from the database
"""
juicer.utils.Log.log_debug("imploding %s" % self.cart_name)
# rm -r self.remotes_storage()
if os.path.exists(self.remo... | remove all trace of this cart: delete the file(s) on the local
filesystem and delete the entry from the database |
def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat',... | smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window w... |
def exists_evaluator(self, index):
""" Evaluate the given exists match condition for the user attributes.
Args:
index: Index of the condition to be evaluated.
Returns:
Boolean: True if the user attributes have a non-null value for the given condition,
otherwise False.
... | Evaluate the given exists match condition for the user attributes.
Args:
index: Index of the condition to be evaluated.
Returns:
Boolean: True if the user attributes have a non-null value for the given condition,
otherwise False. |
def parse_string(self, string):
"""Parse a string into a Graph.
:param string: String that is to be passed into Grapg
:return: Graph
"""
dom = minidom.parseString(string)
return self.parse_dom(dom) | Parse a string into a Graph.
:param string: String that is to be passed into Grapg
:return: Graph |
def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False | Resumes pulse capture after an optional trigger pulse. |
def _builder_reprs(cls, options, namespace=None, ns=None):
"""
Given a list of Option objects (such as those returned from
OptsSpec.parse_options) or an %opts or %%opts magic string,
return a list of corresponding option builder reprs. The
namespace is typically given as 'hv' if ... | Given a list of Option objects (such as those returned from
OptsSpec.parse_options) or an %opts or %%opts magic string,
return a list of corresponding option builder reprs. The
namespace is typically given as 'hv' if fully qualified
namespaces are desired. |
def trim(self):
"""Return the just data defined by the PE headers, removing any overlayed data."""
overlay_data_offset = self.get_overlay_data_start_offset()
if overlay_data_offset is not None:
return self.__data__[ : overlay_data_offset ]
return self.__data__[:] | Return the just data defined by the PE headers, removing any overlayed data. |
def lte(name, value):
'''
Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: te... | Only succeed if the value in the given register location is less than
or equal the given value
USAGE:
.. code-block:: yaml
foo:
check.lte:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
... |
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle ... | Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges |
def interact_plain(header=UP_LINE, local_ns=None,
module=None, dummy=None,
stack_depth=1, global_ns=None):
"""
Create an interactive python console
"""
frame = sys._getframe(stack_depth)
variables = {}
if local_ns is not None:
variables.update(loca... | Create an interactive python console |
def combine_dicts(*dicts, copy=False, base=None):
"""
Combines multiple dicts in one.
:param dicts:
A sequence of dicts.
:type dicts: dict
:param copy:
If True, it returns a deepcopy of input values.
:type copy: bool, optional
:param base:
Base dict where combine m... | Combines multiple dicts in one.
:param dicts:
A sequence of dicts.
:type dicts: dict
:param copy:
If True, it returns a deepcopy of input values.
:type copy: bool, optional
:param base:
Base dict where combine multiple dicts in one.
:type base: dict, optional
:ret... |
def get_chain(self, index):
"""Assemble and return the chain leading from a given node to the merkle root of this tree.
"""
chain = []
this = self.leaves[index]
chain.append((this.val, 'SELF'))
while this.p:
chain.append((this.sib.val, this.sib.side))
... | Assemble and return the chain leading from a given node to the merkle root of this tree. |
def from_events(self, instance, ev_args, ctx):
"""
Like :meth:`.ChildList.from_events`, but the object is appended to the
list associated with its tag in the dict.
"""
tag = ev_args[0], ev_args[1]
cls = self._tag_map[tag]
obj = yield from cls.parse_events(ev_args... | Like :meth:`.ChildList.from_events`, but the object is appended to the
list associated with its tag in the dict. |
def search_by_attribute_set(
url: str,
profile: Tuple[str],
limit: Optional[int] = 100,
namespace_filter: Optional[str]=None) -> Dict:
"""
Given a list of phenotypes, returns a ranked list of individuals
individuals can be filtered by namespace, eg MONDO, MGI, HGNC
:retur... | Given a list of phenotypes, returns a ranked list of individuals
individuals can be filtered by namespace, eg MONDO, MGI, HGNC
:returns Dict with the structure: {
'unresolved' : [...]
'query_IRIs' : [...]
'results': {...}
}
:raises JSONDecodeError: If the response body does not c... |
def populate(self, installed_bots=None):
"""
Load bots.
Import each bot module.
It is thread-safe and idempotent, but not re-entrant.
"""
if self.ready:
return
# populate() might be called by two threads in parallel on servers
# that create th... | Load bots.
Import each bot module.
It is thread-safe and idempotent, but not re-entrant. |
def init_mbed_dut(contextlist, conf, index, args):
"""
Initializes a local hardware dut
"""
binary = None
try:
binary = conf["application"]['bin']
except KeyError:
pass
dev = conf.get('allocated', None)
if not dev:
raise ResourceInitError("Allocated device not fo... | Initializes a local hardware dut |
def create_instance(cls, values, classname="weka.core.DenseInstance", weight=1.0):
"""
Creates a new instance.
:param values: the float values (internal format) to use, numpy array or list.
:type values: ndarray or list
:param classname: the classname of the instance (eg weka.co... | Creates a new instance.
:param values: the float values (internal format) to use, numpy array or list.
:type values: ndarray or list
:param classname: the classname of the instance (eg weka.core.DenseInstance).
:type classname: str
:param weight: the weight of the instance
... |
def display(self, format="png"):
"""
Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg"
"""
from sebastian.core.transforms import lilypond
seq = HSeq(self) | lilypond()
lily_output... | Return an object that can be used to display this sequence.
This is used for IPython Notebook.
:param format: "png" or "svg" |
def serialize(self, buf, offset):
"""
Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length.
"""
fields = [ofproto.oxs_from_user(k, uv) for (k, uv)
in self.fields]
hdr_pack_str = '!HH'
fiel... | Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length. |
def get_status(*nrs):
"""Returns a list of Bugreport objects.
Given a list of bugnumbers this method returns a list of Bugreport
objects.
Parameters
----------
nrs : int or list of ints
the bugnumbers
Returns
-------
bugs : list of Bugreport objects
"""
# If we ca... | Returns a list of Bugreport objects.
Given a list of bugnumbers this method returns a list of Bugreport
objects.
Parameters
----------
nrs : int or list of ints
the bugnumbers
Returns
-------
bugs : list of Bugreport objects |
def num_instances(self):
"""
Number of spouts + bolts
"""
num = 0
# Get all the components
components = self.spouts() + self.bolts()
# Get instances for each worker
for component in components:
config = component.comp.config
for kvs in config.kvs:
if kvs.key == api_... | Number of spouts + bolts |
def _ReadSemanticDataTypeDefinition(
self, definitions_registry, definition_values, data_type_definition_class,
definition_name, supported_definition_values):
"""Reads a semantic data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
re... | Reads a semantic data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
data_type_definition_class (str): data type definition class.
definition_name (str): name of t... |
def generate_accounts(seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: {
'privatekey': encode_hex(sha3(seed)),
'address': encode_hex(privatekey_to_address(sha3(seed))),
}
for seed in seeds
} | Create private keys and addresses for all seeds. |
def plot_pressure(self, p, plot_range=None):
"""
Required input:
P: Mean Sea Level Pressure (hPa)
Optional Input:
plot_range: Data range for making figure (list of (min,max,step))
"""
# PLOT PRESSURE
if not plot_range:
plot_range = [970... | Required input:
P: Mean Sea Level Pressure (hPa)
Optional Input:
plot_range: Data range for making figure (list of (min,max,step)) |
def build_estimator(model_dir, model_type, model_column_fn, inter_op, intra_op, ctx):
"""Build an estimator appropriate for the given model type."""
wide_columns, deep_columns = model_column_fn()
hidden_units = [100, 75, 50, 25]
# Create a tf.estimator.RunConfig to ensure the model is run on CPU, which
# tra... | Build an estimator appropriate for the given model type. |
def tplot_options(option, value):
"""
This function allows the user to set several global options for the generated plots.
Parameters:
option : str
The name of the option. See section below
value : str/int/float/list
The value of the option. See section bel... | This function allows the user to set several global options for the generated plots.
Parameters:
option : str
The name of the option. See section below
value : str/int/float/list
The value of the option. See section below.
Options:
======... |
def analyze(self, time: int=None) -> typing.Tuple[float, float, int, int]:
"""
Determine noise, curvature, range, and domain of specified array.
:param: pixel to inch ratio
:param: time (column) to use.
:return: curvature
:return: noise
:return: range
:r... | Determine noise, curvature, range, and domain of specified array.
:param: pixel to inch ratio
:param: time (column) to use.
:return: curvature
:return: noise
:return: range
:return: domain |
def sign(mv):
"""Obtains a signature for a `MetricValue`
Args:
mv (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricValue`): a
MetricValue that's part of an operation
Returns:
string: a unique signature for that operation
"""
md5 = hashlib.md5()
update_h... | Obtains a signature for a `MetricValue`
Args:
mv (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricValue`): a
MetricValue that's part of an operation
Returns:
string: a unique signature for that operation |
def open(self, update=False):
"""
Opens pdf file to read from.
"""
filename = os.path.basename(self.source_path)
folder, _ext = os.path.splitext(filename)
self.path = os.path.sep.join([self.directory, folder, filename])
if not os.path.exists(os.path.dirname(self.p... | Opens pdf file to read from. |
def destroy(self, id):
"""Destroy a group.
:param str id: a group ID
:return: ``True`` if successful
:rtype: bool
"""
path = '{}/destroy'.format(id)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
return response.ok | Destroy a group.
:param str id: a group ID
:return: ``True`` if successful
:rtype: bool |
def distribution_for_instance(self, inst):
"""
Peforms a prediction, returning the cluster distribution.
:param inst: the Instance to get the cluster distribution for
:type inst: Instance
:return: the cluster distribution
:rtype: float[]
"""
pred = self._... | Peforms a prediction, returning the cluster distribution.
:param inst: the Instance to get the cluster distribution for
:type inst: Instance
:return: the cluster distribution
:rtype: float[] |
def average(x):
"""
Return a numpy array of column average.
It does not affect if the array is one dimension
Parameters
----------
x : ndarray
A numpy array instance
Returns
-------
ndarray
A 1 x n numpy array instance of column average
Examples
--------
... | Return a numpy array of column average.
It does not affect if the array is one dimension
Parameters
----------
x : ndarray
A numpy array instance
Returns
-------
ndarray
A 1 x n numpy array instance of column average
Examples
--------
>>> a = np.array([[1, 2, 3... |
def getElementByWdomId(id: str) -> Optional[WebEventTarget]:
"""Get element with ``wdom_id``."""
if not id:
return None
elif id == 'document':
return get_document()
elif id == 'window':
return get_document().defaultView
elm = WdomElement._elements_with_wdom_id.get(id)
ret... | Get element with ``wdom_id``. |
def _do_resumable_upload(self, stream, metadata, num_retries):
"""Perform a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: in... | Perform a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: int
:param num_retries: Number of upload retries. (Deprecated: This
... |
def proximal_l2_squared(space, lam=1, g=None):
r"""Proximal operator factory of the squared l2-norm/distance.
Function for the proximal operator of the convex conjugate of the
functional F where F is the l2-norm (or distance to g, if given)::
F(x) = lam ||x - g||_2^2
with x and g elements in... | r"""Proximal operator factory of the squared l2-norm/distance.
Function for the proximal operator of the convex conjugate of the
functional F where F is the l2-norm (or distance to g, if given)::
F(x) = lam ||x - g||_2^2
with x and g elements in ``space``, scaling factor lam, and given data g.
... |
def get_context(self, name, value, attrs):
"""
Django >= 1.11 variant.
"""
context = super(DynamicRawIDWidget, self).get_context(
name, value, attrs
)
model = self.rel.model if VERSION[0] == 2 else self.rel.to
related_url = reverse(
'admin:... | Django >= 1.11 variant. |
def get_url(self, obj, view_name, request, format):
"""
Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Unsaved objects ... | Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf. |
def stalk_buffer(self, pid, address, size, action = None):
"""
Sets a one-shot page breakpoint and notifies
when the given buffer is accessed.
@see: L{dont_watch_variable}
@type pid: int
@param pid: Process global ID.
@type address: int
@param address... | Sets a one-shot page breakpoint and notifies
when the given buffer is accessed.
@see: L{dont_watch_variable}
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@param s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.