text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_library(self, library):
"""
Return the library instance. Can generally use slicing to return the library:
arctic_store[library]
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
"""
if... | 0.004614 |
def timed_request(self, subject, payload, timeout=0.5):
"""
Implements the request/response pattern via pub/sub
using an ephemeral subscription which will be published
with a limited interest of 1 reply returning the response
or raising a Timeout error.
->> SUB _INBOX.... | 0.001808 |
def remove_thumbnail(self, thumbnail):
"""Remove thumbnail."""
if thumbnail in self._thumbnails:
index = self._thumbnails.index(thumbnail)
self._thumbnails.remove(thumbnail)
self.layout().removeWidget(thumbnail)
thumbnail.deleteLater()
thumbnail.sig_canvas... | 0.002597 |
def extract_intro(filename):
""" Extract the first paragraph of module-level docstring. max:95 char"""
docstring, _ = get_docstring_and_rest(filename)
# lstrip is just in case docstring has a '\n\n' at the beginning
paragraphs = docstring.lstrip().split('\n\n')
if len(paragraphs) > 1:
firs... | 0.001269 |
def help_center_user_comments(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/comments#list-comments"
api_path = "/api/v2/help_center/users/{id}/comments.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | 0.010274 |
def getReadGroup(self, id_):
"""
Returns the ReadGroup with the specified id if it exists in this
ReadGroupSet, or raises a ReadGroupNotFoundException otherwise.
"""
if id_ not in self._readGroupIdMap:
raise exceptions.ReadGroupNotFoundException(id_)
return se... | 0.005831 |
def _data_dict_to_bokeh_chart_data(self, data):
"""
Take a dictionary of data, as returned by the :py:class:`~.ProjectStats`
per_*_data properties, return a 2-tuple of data dict and x labels list
usable by bokeh.charts.
:param data: data dict from :py:class:`~.ProjectStats` prop... | 0.002828 |
def get_pkg_info_revision():
"""
Get a -r### off of PKG-INFO Version in case this is an sdist of
a subversion revision.
"""
warnings.warn("get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning)
if os.path.exists('PKG-INFO'):
with io.open('PKG-INFO') as f:
for line ... | 0.004202 |
def getData4cryptID(self, tablename, ID):
"""get the whole row from the database and store it in a dict"""
fields = self._getFieldsInDB(tablename)
SQL = 'SELECT *,MAKETIME(0,0,TIMESTAMPDIFF(SECOND, StartDate, EndDate)),DATE_ADD(EndDate, INTERVAL %s DAY),TIMESTAMPDIFF(DAY,DATE_ADD(EndDate, INTERVAL %s DA... | 0.035433 |
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the ... | 0.000942 |
def pool_list(self, name_matches=None, pool_ids=None, category=None,
description_matches=None, creator_name=None, creator_id=None,
is_deleted=None, is_active=None, order=None):
"""Get a list of pools.
Parameters:
name_matches (str):
pool_ids (... | 0.003213 |
def get_task_doc(self, path):
"""
Get the entire task doc for a path, including any post-processing.
"""
logger.info("Getting task doc for base dir :{}".format(path))
files = os.listdir(path)
vasprun_files = OrderedDict()
if "STOPCAR" in files:
#Stoppe... | 0.005811 |
def finalize(self):
"""
Connects the wires.
"""
self._check_finalized()
self._final = True
for dest_w, values in self.dest_instrs_info.items():
mux_vals = dict(zip(self.instructions, values))
dest_w <<= sparse_mux(self.signal_wire, mux_vals) | 0.006369 |
def raise_error(e):
"""Take a bravado-core Error model and raise it as an exception"""
code = e.error
if code in code_to_class:
raise code_to_class[code](e.error_description)
else:
raise InternalServerError(e.error_description) | 0.003861 |
def handle_exit_code(d, code):
"""Sample function showing how to interpret the dialog exit codes.
This function is not used after every call to dialog in this demo
for two reasons:
1. For some boxes, unfortunately, dialog returns the code for
ERROR when the user presses ESC (instead of th... | 0.000636 |
def _generate_validation_scripts(self):
"""
Include the scripts used by solutions.
"""
id_script_list_validation_fields = (
AccessibleFormImplementation.ID_SCRIPT_LIST_VALIDATION_FIELDS
)
local = self.parser.find('head,body').first_result()
if local i... | 0.000477 |
def _decrypt_object(obj):
'''
Recursively try to find a pass path (string) that can be handed off to pass
'''
if isinstance(obj, six.string_types):
return _fetch_secret(obj)
elif isinstance(obj, dict):
for pass_key, pass_path in six.iteritems(obj):
obj[pass_key] = _decryp... | 0.002033 |
def fix(x, digs):
"""Format x as [-]ddd.ddd with 'digs' digits after the point
and at least one digit before.
If digs <= 0, the point is suppressed."""
if type(x) != type(''): x = repr(x)
try:
sign, intpart, fraction, expo = extract(x)
except NotANumber:
return x
intpart, fra... | 0.01157 |
def override(func, auto = False):
"""Decorator applicable to methods only.
For a version applicable also to classes or modules use auto_override.
Asserts that for the decorated method a parent method exists in its mro.
If both the decorated method and its parent method are type annotated,
the decora... | 0.003994 |
def to_one_hot(dataY):
"""Convert the vector of labels dataY into one-hot encoding.
:param dataY: vector of labels
:return: one-hot encoded labels
"""
nc = 1 + np.max(dataY)
onehot = [np.zeros(nc, dtype=np.int8) for _ in dataY]
for i, j in enumerate(dataY):
onehot[i][j] = 1
retu... | 0.00304 |
def lazily(self, name, callable, args):
"""
Load something lazily
"""
self._lazy[name] = callable, args
self._all.add(name) | 0.01227 |
async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
... | 0.004549 |
def renew_compose(self, compose_id):
"""Renew, or extend, existing compose
If the compose has already been removed, ODCS creates a new compose.
Otherwise, it extends the time_to_expire of existing compose. In most
cases, caller should assume the compose ID will change.
:param c... | 0.003916 |
def wait_for_ajax_calls_to_complete(self, timeout=5):
"""
Waits until there are no active or pending ajax requests.
Raises TimeoutException should silence not be had.
:param timeout: time to wait for silence (default: 5 seconds)
:return: None
"""
from selenium.w... | 0.006397 |
def splitstring(string):
"""
>>> string = 'apple orange "banana tree" green'
>>> splitstring(string)
['apple', 'orange', 'green', '"banana tree"']
"""
patt = re.compile(r'"[\w ]+"')
if patt.search(string):
quoted_item = patt.search(string).group()
newstring = patt.sub('', str... | 0.002421 |
def listTheExtras(self, deleteAlso):
""" Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items.
"""
# get list of extras
... | 0.006811 |
def get_stats(a, full=False):
"""Compute and print statistics for input array
Needs to be cleaned up, return a stats object
"""
from scipy.stats.mstats import mode
a = checkma(a)
thresh = 4E6
if full or a.count() < thresh:
q = (iqr(a))
p16, p84, spread = robust_spread(a)
... | 0.013354 |
def read_wv_master_file(wv_master_file, lines='brightest', debugplot=0):
"""read arc line wavelengths from external file.
Parameters
----------
wv_master_file : string
File name of txt file containing the wavelength database.
lines : string
Indicates which lines to read. For files w... | 0.000781 |
def search(self, q=''):
"""GET /v1/search"""
if q:
q = '?q=' + q
return self._http_call('/v1/search' + q, get) | 0.013699 |
def import_class(name):
"""Load class from fully-qualified python module name.
ex: import_class('bulbs.content.models.Content')
"""
module, _, klass = name.rpartition('.')
mod = import_module(module)
return getattr(mod, klass) | 0.003968 |
def get_start_stops(transcript_sequence, start_codons=None, stop_codons=None):
"""Return start and stop positions for all frames in the given
transcript.
"""
transcript_sequence = transcript_sequence.upper() # for comparison with codons below
if not start_codons:
st... | 0.002174 |
def fi_ssn(ssn, allow_temporal_ssn=True):
"""
Validate a Finnish Social Security Number.
This validator is based on `django-localflavor-fi`_.
.. _django-localflavor-fi:
https://github.com/django/django-localflavor-fi/
Examples::
>>> fi_ssn('010101-0101')
True
>>>... | 0.000923 |
def count_var(nex):
"""
count number of sites with cov=4, and number of variable sites.
"""
arr = np.array([list(i.split()[-1]) for i in nex])
miss = np.any(arr=="N", axis=0)
nomiss = arr[:, ~miss]
nsnps = np.invert(np.all(nomiss==nomiss[0, :], axis=0)).sum()
return nomiss.shape[1], nsnp... | 0.009346 |
def hparams_to_batching_scheme(hparams,
drop_long_sequences=False,
shard_multiplier=1,
length_multiplier=1):
"""Wrapper around _batching_scheme with hparams."""
return batching_scheme(
batch_size=hparams.batch_size,
... | 0.004785 |
def inicializar_y_capturar_excepciones(func):
"Decorador para inicializar y capturar errores (version para webservices)"
@functools.wraps(func)
def capturar_errores_wrapper(self, *args, **kwargs):
try:
# inicializo (limpio variables)
self.Errores = [] # listas de st... | 0.00119 |
def cmServiceAccept():
"""CM SERVICE ACCEPT Section 9.2.5"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x21) # 00100001
packet = a / b
return packet | 0.005952 |
def get_value(self):
"""Retreive usage value within report"""
if self.__is_value_array:
if self.__bit_size == 8: #matching c_ubyte
return list(self.__value)
else:
result = []
for i in range(self.__report_count):
... | 0.00907 |
def update_notebooks(source_path, dest_path=None, update_html=True, document_new_fns=False,
update_nb_links=True, html_path=None, force=False):
"`source_path` can be a directory or a file. Assume all modules reside in the fastai directory."
from .convert2html import convert_nb
source_pa... | 0.006759 |
def SPEEDY_band_fraction(T):
'''Python / numpy implementation of the formula used by SPEEDY and MITgcm
to partition longwave emissions into 4 spectral bands.
Input: temperature in Kelvin
returns: a four-element array of band fraction
Reproducing here the FORTRAN code from MITgcm/pkg/aim_v23/phy_r... | 0.026429 |
def _add_comments(self, comments, original_string=""):
"""
Returns a string with comments added
"""
return comments and "{0} # {1}".format(self._strip_comments(original_string)[0],
"; ".join(comments)) or original_string | 0.013115 |
def murmur3_64(data: Union[bytes, bytearray], seed: int = 19820125) -> int:
"""
Pure 64-bit Python implementation of MurmurHash3; see
http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash
(plus RNC bugfixes).
Args:
data: data to hash
s... | 0.006623 |
async def publish(self, endpoint: str, payload: str):
"""
Publish to an endpoint.
:param str endpoint: Key by which the endpoint is recognised.
Subscribers will use this key to listen to events
:param str payload: Payload to publish with the event
:return... | 0.00304 |
def is_equal_type(type_a: GraphQLType, type_b: GraphQLType):
"""Check whether two types are equal.
Provided two types, return true if the types are equal (invariant)."""
# Equivalent types are equal.
if type_a is type_b:
return True
# If either type is non-null, the other must also be non-... | 0.001238 |
def get_all_manifests(image, registry, insecure=False, dockercfg_path=None,
versions=('v1', 'v2', 'v2_list')):
"""Return manifest digests for image.
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
... | 0.003198 |
def delete(self):
"""Delete the note, removing it from it's task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> note = task.ad... | 0.00335 |
def graphdata(data):
"""returns ratings and episode number
to be used for making graphs"""
data = jh.get_ratings(data)
num = 1
rating_final = []
episode_final = []
for k,v in data.iteritems():
rating=[]
epinum=[]
for r in v:
if r != None:
r... | 0.013699 |
def setpurpose(self, purpose):
"""
Sets certificate purpose which verified certificate should match
@param purpose - number from 1 to 9 or standard strind defined
in Openssl
possible strings - sslcient,sslserver, nssslserver, smimesign,i
... | 0.002594 |
def make_frequency_series(vec):
"""Return a frequency series of the input vector.
If the input is a frequency series it is returned, else if the input
vector is a real time series it is fourier transformed and returned as a
frequency series.
Parameters
----------
vector : TimeSeries or Fre... | 0.003254 |
def cluster_types(types, max_clust=12):
"""
Generates a dictionary mapping each binary number in types to an integer
from 0 to max_clust. Hierarchical clustering is used to determine which
which binary numbers should map to the same integer.
"""
if len(types) < max_clust:
max_clust = le... | 0.001515 |
def delete_database(self, name_or_obj):
"""
Deletes the specified database. If no database by that name
exists, no exception will be raised; instead, nothing at all
is done.
"""
name = utils.get_name(name_or_obj)
self._database_manager.delete(name) | 0.006579 |
def search_ipv6_environment(self, ipv6, id_environment):
"""Get IPv6 with an associated environment.
:param ipv6: IPv6 address in the format x1:x2:x3:x4:x5:x6:x7:x8.
:param id_environment: Environment identifier. Integer value and greater than zero.
:return: Dictionary with the followi... | 0.003179 |
def update_asset(self, asset_form=None):
"""Updates an existing asset.
:param asset_form: the form containing the elements to be updated
:type asset_form: ``osid.repository.AssetForm``
:raise: ``IllegalState`` -- ``asset_form`` already used in anupdate transaction
:raise: ``Inva... | 0.003297 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(UsersCollector, self).get_default_config()
config.update({
'path': 'users',
'utmp': None,
})
return config | 0.006993 |
def yield_expr__26(self, yield_loc, exprs):
"""(2.6, 2.7, 3.0, 3.1, 3.2) yield_expr: 'yield' [testlist]"""
if exprs is not None:
return ast.Yield(value=exprs,
yield_loc=yield_loc, loc=yield_loc.join(exprs.loc))
else:
return ast.Yield(value=Non... | 0.007752 |
def _encode_gif(images, fps):
"""Encodes numpy images into gif string.
Args:
images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape
`[time, height, width, channels]` where `channels` is 1 or 3.
fps: frames per second of the animation
Returns:
The encoded gif string.
Raises:
... | 0.010823 |
def account(self):
""" Returns the :class:`~plexapi.server.Account` object this server belongs to. """
data = self.query(Account.key)
return Account(self, data) | 0.016304 |
def remove_subscriptions(self, server_id, sub_paths):
# pylint: disable=line-too-long
"""
Remove indication subscription(s) from a WBEM server, by deleting the
indication subscription instances in the server.
The indication subscriptions must be owned or permanent (i.e. not
... | 0.001934 |
def iterator(self, symbol, chunk_range=None):
"""
Returns a generator that accesses each chunk in ascending order
Parameters
----------
symbol: str
the symbol for the given item in the DB
chunk_range: None, or a range object
allows you to subset t... | 0.004093 |
def init_widget(self):
""" Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget`
"""
if not self.toast:
return
super(AndroidToast, self).init_widget()
d = self.declaration
if not ... | 0.007707 |
def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... | 0.000359 |
def _extract_t_indices(self, X, X2=None, dL_dK=None):
"""Extract times and output indices from the input matrix X. Times are ordered according to their index for convenience of computation, this ordering is stored in self._order and self.order2. These orderings are then mapped back to the original ordering (in ... | 0.006597 |
def _draw_button(self, overlay, text, location):
"""Draws a button on the won and lost overlays, and return its hitbox."""
label = self.button_font.render(text, True, (119, 110, 101))
w, h = label.get_size()
# Let the callback calculate the location based on
# the width and heigh... | 0.005362 |
def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body) | 0.00641 |
def _reduce(self):
"""Perform a greedy reduction of token stream.
If a reducer method matches, it will be executed, then the
:meth:`reduce` method will be called recursively to search
for any more possible reductions.
"""
for reduction, methname in self.reducers:
... | 0.002286 |
def _store_basic_estimation_results(self, results_dict):
"""
Extracts the basic estimation results (i.e. those that need no further
calculation or logic applied to them) and stores them on the model
object.
Parameters
----------
results_dict : dict.
... | 0.001138 |
def load_data_and_labels(filename, encoding='utf-8'):
"""Loads data and label from a file.
Args:
filename (str): path to the file.
encoding (str): file encoding format.
The file format is tab-separated values.
A blank line is required at the end of a sentence.
For exam... | 0.000829 |
def nbody_separation(expr, qs):
"""Convert n-body problem to 2-body problem.
Args:
expr: sympy expressions to be separated.
qs: sympy's symbols to be used as supplementary variable.
Return:
new_expr(sympy expr), constraints(sympy expr), mapping(dict(str, str -> Symbol)):
... | 0.002444 |
def usermacro_get(macro=None, hostids=None, templateids=None, hostmacroids=None,
globalmacroids=None, globalmacro=False, **kwargs):
'''
Retrieve user macros according to the given parameters.
Args:
macro: name of the usermacro
hostids: Return macros for the... | 0.003532 |
def start(name, call=None):
'''
Start a VM in Linode.
name
The name of the VM to start.
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
if call != 'action':
raise SaltCloudException(
'The start action must be called with -a or --action... | 0.001082 |
def svd_convolution(inp, outmaps, kernel, r, pad=None, stride=None,
dilation=None, uv_init=None, b_init=None, base_axis=1,
fix_parameters=False, rng=None, with_bias=True):
"""SVD convolution is a low rank approximation of the convolution
layer. It can be seen as a depth w... | 0.001184 |
def reference(self, ):
"""Reference a file
:returns: None
:rtype: None
:raises: None
"""
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.reference(tfi) | 0.008547 |
def dump_csv(data: List[dict], fieldnames: Sequence[str], with_header: bool = False, crlf: bool = False,
tsv: bool = False) -> str:
"""
:param data:
:param fieldnames:
:param with_header:
:param crlf:
:param tsv:
:return: unicode
"""
def force_str(v):
# XXX: Dou... | 0.004825 |
def build_docker_run_command(configuration):
"""
Translate a declarative docker `configuration` to a `docker run` command.
Parameters
----------
configuration : dict
configuration
Returns
-------
args : list
sequence of command line arguments to run a command in a conta... | 0.002415 |
def fspaths(draw, allow_pathlike=None):
"""A strategy which generates filesystem path values.
The generated values include everything which the builtin
:func:`python:open` function accepts i.e. which won't lead to
:exc:`ValueError` or :exc:`TypeError` being raised.
Note that the range of the retur... | 0.00046 |
def init_argument_parser(name=None, **kwargs):
"""Creates a global ArgumentParser instance with the given name,
passing any args other than "name" to the ArgumentParser constructor.
This instance can then be retrieved using get_argument_parser(..)
"""
if name is None:
name = "default"
... | 0.004267 |
def outgoing_caller_ids(self):
"""
Access the outgoing_caller_ids
:returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
"""
if self._outgoing_caller_ids is None:
... | 0.010684 |
def build_from_source(version, **kwargs):
"""
Builds specified Spark version from source.
:param version:
:param kwargs:
:return: (Integer) Status code of build/mvn command.
"""
mvn = os.path.join(Spark.svm_version_path(version), 'build', 'mvn')
Spark.chmo... | 0.006122 |
def add_log_level(value, name):
"""
Add a new log level to the :mod:`logging` module.
:param value: The log level's number (an integer).
:param name: The name for the log level (a string).
"""
logging.addLevelName(value, name)
setattr(logging, name, value) | 0.003509 |
def get_parser():
"""Return a parser for the command-line arguments."""
parser = argparse.ArgumentParser(
add_help=False,
description='Analysis of your architecture strength based on DSM data')
parser.add_argument(
'-c', '--config', action='store', type=valid_file, dest='config_file'... | 0.000654 |
def _get_network(self, kind, router=True, vlans=True, vlan_ids=True):
"""Wrapper for getting details about networks.
:param string kind: network kind. Typically 'public' or 'private'
:param boolean router: flag to include router information
:param boolean vlans: flag to incl... | 0.002384 |
def _wrap_result(name, data, sparse_index, fill_value, dtype=None):
"""
wrap op result to have correct dtype
"""
if name.startswith('__'):
# e.g. __eq__ --> eq
name = name[2:-2]
if name in ('eq', 'ne', 'lt', 'gt', 'le', 'ge'):
dtype = np.bool
fill_value = lib.item_from_... | 0.001653 |
def dot_path(obj: t.Union[t.Dict, object],
path: str,
default: t.Any = None,
separator: str = '.'):
"""
Provides an access to elements of a mixed dict/object type by a delimiter-separated path.
::
class O1:
my_dict = {'a': {'b': 1}}
class ... | 0.001764 |
def get_outcome(self, outcome):
"""
Returns the details of the outcome with the given id.
:calls: `GET /api/v1/outcomes/:id \
<https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_
:param outcome: The outcome object or ID to return.
:type outc... | 0.002653 |
def valid_ip_prefix(ip_prefix):
"""Perform a sanity check on ip_prefix.
Arguments:
ip_prefix (str): The IP-Prefix to validate
Returns:
True if ip_prefix is a valid IPv4 address with prefix length 32 or a
valid IPv6 address with prefix length 128, otherwise False
"""
try:
... | 0.00158 |
def onex(self):
"""
delete all X columns except the first one.
"""
xCols=[i for i in range(self.nCols) if self.colTypes[i]==3]
if len(xCols)>1:
for colI in xCols[1:][::-1]:
self.colDelete(colI) | 0.019157 |
def upload_to_s3(self, region='us-east-1'):
"""
Uploads the vmdk file to aws s3
:param file_location: location of vmdk
:return:
"""
s3_import_cmd = "aws s3 cp {} s3://{} --profile '{}' --region {}".format(self.upload_file, self.bucket_name,
... | 0.007028 |
def customPRF512(key, amac, smac, anonce, snonce):
"""Source https://stackoverflow.com/questions/12018920/"""
A = b"Pairwise key expansion"
B = b"".join(sorted([amac, smac]) + sorted([anonce, snonce]))
blen = 64
i = 0
R = b''
while i <= ((blen * 8 + 159) / 160):
hmacsha1 = hmac.new(... | 0.002299 |
def binify_and_jsd(df1, df2, bins, pair=None):
"""Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bin... | 0.001138 |
def bind(self, name, filterset):
""" attach filter to filterset
gives a name to use to extract arguments from querydict
"""
if self.name is not None:
name = self.name
self.field.bind(name, self) | 0.008097 |
def _copy_across(self, rel_path, cb=None):
"""If the upstream doesn't have the file, get it from the alternate and store it in the upstream"""
from . import copy_file_or_flo
if not self.upstream.has(rel_path):
if not self.alternate.has(rel_path):
return None
... | 0.005891 |
def input_format(self, content_type):
"""Returns the set input_format handler for the given content_type"""
return getattr(self, '_input_format', {}).get(content_type, hug.defaults.input_format.get(content_type, None)) | 0.012821 |
def all(self, campaign_id, get_all=False, **queryparams):
"""
Get information about members who have unsubscribed from a specific
campaign.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
:param get_all: Should the query get all res... | 0.00443 |
def read_routes6():
"""Return a list of IPv6 routes than can be used by Scapy."""
# Call netstat to retrieve IPv6 routes
fd_netstat = os.popen("netstat -rn -f inet6")
# List interfaces IPv6 addresses
lifaddr = in6_getifaddr()
if not lifaddr:
return []
# Routes header information
... | 0.000248 |
def update(self, **args):
"""
Update the current :class:`InstanceResource`
"""
self_dict = self.to_dict()
if args:
self_dict = dict(list(self_dict.items()) + list(args.items()))
response = self.requester.put(
'/{endpoint}/{id}', endpoint=self.endpo... | 0.003817 |
def update_transfer(
self,
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
partner_signature: Signature,
signature: Signature,
block_identifier: BlockSpecification,
):
""" Updates the channel using ... | 0.003968 |
def save(self, filename, format=None, **kwargs):
""" Save the object to file given by filename.
"""
if format is None:
# try to derive protocol from file extension
format = format_from_extension(filename)
with file(filename, 'wb') as fp:
self.save_to_f... | 0.005682 |
def stresser(self, stress_rule='FSR'):
"""
Args:
:param stress_rule: Stress Rule, valid options:
'FSR': French Stress Rule, stress falls on the ultima, unless
it contains schwa (ends with e), in which case the penult is
stressed
... | 0.002207 |
def load_conf(yml_file, conf={}):
"""
To load the config
:param yml_file: the config file path
:param conf: dict, to override global config
:return: dict
"""
with open(yml_file) as f:
data = yaml.load(f)
if conf:
data.update(conf)
return dictdot(data) | 0.003175 |
def paths(self):
"""
Sequence of closed paths, encoded by entity index.
Returns
---------
paths: (n,) sequence of (*,) int referencing self.entities
"""
paths = traversal.closed_paths(self.entities,
self.vertices)
re... | 0.006061 |
def update_process_work_item_type_rule(self, process_rule, process_id, wit_ref_name, rule_id):
"""UpdateProcessWorkItemTypeRule.
[Preview API] Updates a rule in the work item type of the process.
:param :class:`<UpdateProcessRuleRequest> <azure.devops.v5_0.work_item_tracking_process.models.Updat... | 0.006757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.