text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def permission_required(perm, queryset=None,
login_url=None, raise_exception=False):
"""
Permission check decorator for classbased/functionbased generic view
This decorator works as method or function decorator
DO NOT use ``method_decorator`` or whatever while this decorator wil... | 0.00036 |
def linesplit(string, columns):
# type: (Union[Text, FmtStr], int) -> List[FmtStr]
"""Returns a list of lines, split on the last possible space of each line.
Split spaces will be removed. Whitespaces will be normalized to one space.
Spaces will be the color of the first whitespace character of the
... | 0.004068 |
def recycle():
"""
the purpose of this tasks is to recycle the data from the cache
with version=2 in the main cache
"""
# http://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk
for service in cache.iter_keys('th_*'):
try:
# get the value from the cache... | 0.001558 |
def lsdb(self, lsdb=None, url=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False):
"""Method to query :class:`.models.LSDB` objects in database
:param lsdb: name(s) of the Locus Specific Mutation Database
:type lsdb: str or tuple(str) or None
:param url: URL of the L... | 0.002924 |
def convert_string_value_to_type_value(string_value, data_type):
"""Helper function to convert a given string to a given data type
:param str string_value: the string to convert
:param type data_type: the target data type
:return: the converted value
"""
from ast import literal_eval
try:
... | 0.001737 |
def barv(d, plt, title=None, rotation='vertical'):
"""A convenience function for plotting a vertical bar plot from a Counter"""
labels = sorted(d, key=d.get, reverse=True)
index = range(len(labels))
plt.xticks(index, labels, rotation=rotation)
plt.bar(index, [d[v] for v in labels])
if title is ... | 0.00565 |
def pymux_key_to_prompt_toolkit_key_sequence(key):
"""
Turn a pymux description of a key. E.g. "C-a" or "M-x" into a
prompt-toolkit key sequence.
Raises `ValueError` if the key is not known.
"""
# Make the c- and m- prefixes case insensitive.
if key.lower().startswith('m-c-'):
key ... | 0.001435 |
def export(self, output_type='df', filename=None, x_axis='energy', y_axis='attenuation', mixed=True,
all_layers=False, all_elements=False, all_isotopes=False, items_to_export=None,
offset_us=0., source_to_detector_m=16.,
t_start_us=1, time_resolution_us=0.16, time_unit='us')... | 0.004088 |
def insert(self, button):
"""
Insert button to last row
:param button:
:return: self
:rtype: :obj:`types.InlineKeyboardMarkup`
"""
if self.inline_keyboard and len(self.inline_keyboard[-1]) < self.row_width:
self.inline_keyboard[-1].append(button)
... | 0.007937 |
def get_outgoing_sequence_names(self):
"""
Returns a list of the names of outgoing sequences. Some may be None.
"""
return sorted([s.name for s in
list(self.outgoing_sequence_flows_by_id.values())]) | 0.007905 |
def reverse(self):
"""Reverse in place."""
r = self[:]
r.reverse()
self.clear()
self.extend(r) | 0.014925 |
def source_changed(self, event):
"""Generate a simplified chain by joining adjacent transforms.
"""
# bail out early if the chain is empty
transforms = self._chain.transforms[:]
if len(transforms) == 0:
self.transforms = []
return
# If the... | 0.003724 |
def _align_iteration_with_cl_boundary(self, iteration, subtract=True):
"""Align iteration with cacheline boundary."""
# FIXME handle multiple datatypes
element_size = self.kernel.datatypes_size[self.kernel.datatype]
cacheline_size = self.machine['cacheline size']
elements_per_cac... | 0.003834 |
def linguist_field_names(self):
"""
Returns linguist field names (example: "title" and "title_fr").
"""
return list(self.model._linguist.fields) + list(
utils.get_language_fields(self.model._linguist.fields)
) | 0.007663 |
def popone(self, key, *default):
"""Remove first of given key and return corresponding value.
If key is not found, default is returned if given.
>>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)])
>>> m.popone('b')
2
>>> m.items()
[... | 0.008245 |
def join(self, joiner, formatter=lambda s, t: t.format(s),
template="{}"):
"""Join values and convert to string
Example:
>>> from ww import l
>>> lst = l('012')
>>> lst.join(',')
u'0,1,2'
>>> lst.join(',', template="{}#")
... | 0.005263 |
def _cursorUp(self):
""" Handles "cursor up" events """
if self.historyPos > 0:
self.historyPos -= 1
clearLen = len(self.inputBuffer)
self.inputBuffer = list(self.history[self.historyPos])
self.cursorPos = len(self.inputBuffer)
self._refreshInp... | 0.005917 |
def _common_query_parameters(self, doc_type, includes, owner,
promulgated_only, series, sort):
'''
Extract common query parameters between search and list into slice.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type... | 0.002091 |
def normalize(ast: Node) -> Node:
"""
Normalize an AST nodes.
all builtins containers are replace by referencable subclasses
"""
res = ast
typemap = {DictNode, ListNode, TupleNode}
if type(ast) is dict:
res = DictNode(ast)
elif type(ast) is list:
res = ListNode(ast)
... | 0.001252 |
def _list_rjust(self, L, width, fillchar=0):
'''Left pad with the specified value to obtain a list of the specified width (length)'''
length = max(0, width - len(L))
return [fillchar]*length + L | 0.013761 |
def set_local(self, name, stmt):
"""Define that the given name is declared in the given statement node.
.. seealso:: :meth:`scope`
:param name: The name that is being defined.
:type name: str
:param stmt: The statement that defines the given name.
:type stmt: NodeNG
... | 0.004425 |
def cached_object(self, path, compute_fn):
"""
If `cached_object` has already been called for a value of `path` in this
running Python instance, then it should have a cached value in the
_memory_cache; return that value.
If this function was never called before with a particula... | 0.003704 |
def _cancel(self, action: Callable = None, aid: int = None):
"""
Cancel scheduled events
:param action: (optional) scheduled action. If specified, all
scheduled events for the action are cancelled.
:param aid: (options) scheduled event id. If specified,
... | 0.002994 |
def wirevector_subset(self, cls=None, exclude=tuple()):
"""Return set of wirevectors, filtered by the type or tuple of types provided as cls.
If no cls is specified, the full set of wirevectors associated with the Block are
returned. If cls is a single type, or a tuple of types, only those wir... | 0.008783 |
def resolve_signing_intent(self):
"""Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy.
"""
all_signing_intents = [
sel... | 0.005644 |
def get_accessible_time(self, plugin_override=True):
""" Get the accessible time of this task """
vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible)
return vals[0] if len(vals) and plugin_override else self._accessible | 0.009585 |
def get_argument_parser(prog=None, desc=None, formatter_class=None):
"""Create an argument parser.
Parameters
----------
prog: str
The program name.
desc: str
The program description.
formatter_class: argparse formatter class, optional
The argparse formatter class to use... | 0.001002 |
def remove_usage_rights_groups(self, group_id, file_ids, folder_ids=None):
"""
Remove usage rights.
Removes copyright and license information associated with one or more files
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
... | 0.005709 |
def fix_shapes(self):
"""
Fixes the shape of the data fields on edges. Left edges should be
column vectors, and top edges should be row vectors, for example.
"""
for i in xrange(self.n_chunks):
for side in ['left', 'right', 'top', 'bottom']:
edge = get... | 0.00303 |
def generate_csr(private_key_bytes, subject_name, fqdn_list):
"""Generate a Certificate Signing Request (CSR).
Args:
private_key_bytes: bytes
Private key with which the CSR will be signed.
subject_name: str
Certificate Subject Name
fqdn_list:
List o... | 0.001934 |
def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, f... | 0.004028 |
def _parse_file_spec(self, spec):
'''
Separate wildcard specs into more specs
'''
# separate wildcard specs into more specs
if '*' in spec['file']:
expanded_paths = _expand_paths(spec['file'])
if not expanded_paths:
return []
ex... | 0.003521 |
def insert_1d_permute_layers(self):
"""
Insert permutation layers before a 1D start point or after 1D end point
"""
idx, nb_layers = 0, len(self.layer_list)
in_edges, out_edges = self._get_1d_interface_edges()
# Hacky Warning: (1) use a 4-D permute, which is not likely t... | 0.010347 |
async def create(cls, fsm_context: FSMContext):
"""
:param fsm_context:
:return:
"""
proxy = cls(fsm_context)
await proxy.load()
return proxy | 0.010152 |
def text_search(self, search, *, limit=0, table='assets'):
"""Return an iterator of assets that match the text search
Args:
search (str): Text search string to query the text index
limit (int, optional): Limit the number of returned documents.
Returns:
iter:... | 0.003883 |
def staged_rewards(self):
"""
Helper function to return staged rewards based on current physical states.
Returns:
r_reach (float): reward for reaching and grasping
r_lift (float): reward for lifting and aligning
r_stack (float): reward for stacking
""... | 0.002601 |
def download_selenium_server():
"""
Downloads the Selenium Server JAR file from its
online location and stores it locally.
"""
try:
local_file = open(JAR_FILE, 'wb')
remote_file = urlopen(SELENIUM_JAR)
print('Downloading the Selenium Server JAR file...\n')
local_file.... | 0.001686 |
def login(self, url=None, api_key=None, login=None, pwd=None,
api_version=None, timeout=None, verify=True, alt_filepath=None,
domain=None, **kwargs):
"""
Login to SMC API and retrieve a valid session.
Sessions use a pool connection manager to provide dynamic scalability
... | 0.006521 |
def index():
"""Show the index with all posts.
:param int all: Whether or not should show all posts
"""
context = {'postform': NewPostForm(),
'pageform': NewPageForm(),
'delform': DeleteForm()}
n = request.args.get('all')
if n is None:
wants_now = None
... | 0.000911 |
def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):
"""Logging Setup"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
try:
config ... | 0.002301 |
def transform(self, vector):
"""
Computes the Hadamard product of the vector.
"""
if isinstance(vector, RDD):
vector = vector.map(_convert_to_vector)
else:
vector = _convert_to_vector(vector)
return callMLlibFunc("elementwiseProductVector", self.s... | 0.008798 |
def write_vcf(tree_dict, file_name):#, compress=False):
"""
Writes out a VCF-style file (which seems to be minimally handleable
by vcftools and pyvcf) of the alignment. This is created from a dict
in a similar format to what's created by :py:meth:`treetime.vcf_utils.read_vcf`
Positions of var... | 0.01343 |
def _ExtractProxyConfig(product_yaml_key, proxy_config_data):
"""Returns an initialized ProxyConfig using the given proxy_config_data.
Args:
product_yaml_key: a string indicating the client being loaded.
proxy_config_data: a dict containing the contents of proxy_config from the
YAML file.
Returns:... | 0.00754 |
def solve(self, value, filter_):
"""Returns the value of an attribute of the value, or the result of a call to a function.
Arguments
---------
value : ?
A value to solve in combination with the given filter.
filter_ : dataql.resource.Filter
An instance of... | 0.004644 |
def pairs_to_dict(pairs, result=None):
"""
Convert a given list of ``key=value`` strings ::
["key_1=value_1", "key_2=value_2", ..., "key_n=value_n"]
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] =... | 0.001168 |
def _open_xarray_dataset(self, val, chunks=CHUNK_SIZE):
"""Read the band in blocks."""
dask_arr = from_sds(val, chunks=chunks)
attrs = val.attributes()
return xr.DataArray(dask_arr, dims=('y', 'x'),
attrs=attrs) | 0.00738 |
def _proxy_parameters(self):
"""
Builds Proxy parameters Dict from
client options.
"""
proxy_protocol = ''
if self.proxy_host.startswith('https'):
proxy_protocol = 'https'
else:
proxy_protocol = 'http'
proxy = '{0}://'.format(prox... | 0.004342 |
def load(self, filename, subset=None):
"""Load data into the registered fields
Argument:
| ``filename`` -- the filename to read from
Optional argument:
| ``subset`` -- a list of field names that are read from the file.
If not give... | 0.003696 |
def _parse_or_match(self, text, pos, method_name):
"""Execute a parse or match on the default grammar, followed by a
visitation.
Raise RuntimeError if there is no default grammar specified.
"""
if not self.grammar:
raise RuntimeError(
"The {cls}.{met... | 0.002976 |
def _set_endpoint_configuration(self, rest_api, value):
"""
Sets endpoint configuration property of AWS::ApiGateway::RestApi resource
:param rest_api: RestApi resource
:param string/dict value: Value to be set
"""
rest_api.EndpointConfiguration = {"Types": [value]}
... | 0.007853 |
def drop_not_null(self, model, *names):
"""Drop not null."""
for name in names:
field = model._meta.fields[name]
field.null = True
self.ops.append(self.migrator.drop_not_null(model._meta.table_name, field.column_name))
return model | 0.010309 |
def get_requirement(name, requires):
"""
Yield matching requirement strings.
The strings are presented in the format demanded by
pip._vendor.distlib.util.parse_requirement. Hopefully
I'll be able to figure out a better way to handle this
in the future. Perhaps figure out... | 0.002205 |
def _configure_logging(application, verbosity=0, syslog=False):
"""Configure logging for the application, setting the appropriate
verbosity and adding syslog if it's enabled.
:param str application: The application module/package name
:param int verbosity: 1 == INFO, 2 == DEBUG
... | 0.001908 |
def estimate_cp(ts, method="mean", Q=1, penalty_value=0.175):
""" Estimate changepoints in a time series by using R. """
"""
ts: time series
method: look for a single changepoint in 'mean' , 'var', 'mean and var'
or use binary segmentatiom to detect multiple changepoints in
... | 0.002613 |
def remove(self, param, author=None):
"""Remove by url or name"""
if isinstance(param, SkillEntry):
skill = param
else:
skill = self.find_skill(param, author)
skill.remove()
skills = [s for s in self.skills_data['skills']
if s['name'] != ... | 0.005128 |
def register_product_key(self, key):
"""Register/Redeem a CD-Key
:param key: CD-Key
:type key: :class:`str`
:return: format ``(eresult, result_details, receipt_info)``
:rtype: :class:`tuple`
Example ``receipt_info``:
.. code:: python
{'BasePrice':... | 0.002004 |
def _tf_batch_map_offsets(self, inputs, offsets, grid_offset):
"""Batch map offsets into input
Parameters
------------
inputs : ``tf.Tensor``
shape = (b, h, w, c)
offsets: ``tf.Tensor``
shape = (b, h, w, 2*n)
grid_offset: `tf.Tensor``
... | 0.004329 |
def get_sql_statement_with_environment(item, args=None):
""" Given a SQLStatement, string or module plus command line args or a dictionary,
return a SqlStatement and final dictionary for variable resolution.
Args:
item: a SqlStatement, %%sql module, or string containing a query.
args: a string... | 0.01083 |
def get_resource(cls, request_args, id):
r"""
Used to fetch a single resource object with the given id in response to a GET request.\
get_resource should only be invoked on a resource when the client specifies a GET request.
:param request_args:
:return: The query parameters sup... | 0.006865 |
def get_object_from_content(entity, key):
"""Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_content_function(service, message):
... | 0.001325 |
def upload_part(self, bucket, object_name, upload_id, part_number,
data=None, content_type=None, metadata={},
body_producer=None):
"""
Upload a part of data corresponding to a multipart upload.
@param bucket: The bucket name
@param object_name: Th... | 0.004511 |
def dbStore(self, typ, py_value):
"""
Prepares to store this column for the a particular backend database.
:param backend: <orb.Database>
:param py_value: <variant>
:return: <variant>
"""
if isinstance(py_value, datetime.datetime):
# ensure we have s... | 0.005333 |
def parse_fastqc_report(self, file_contents, s_name=None, f=None):
""" Takes contents from a fastq_data.txt file and parses out required
statistics and data. Returns a dict with keys 'stats' and 'data'.
Data is for plotting graphs, stats are for top table. """
# Make the sample name fro... | 0.004225 |
def check_schema_transforms_match(schema, inverted_features):
"""Checks that the transform and schema do not conflict.
Args:
schema: schema list
inverted_features: inverted_features dict
Raises:
ValueError if transform cannot be applied given schema type.
"""
num_target_transforms = 0
for col... | 0.00585 |
def render_head_repr(
expr: Any, sub_render=None, key_sub_render=None) -> str:
"""Render a textual representation of `expr` using
Positional and keyword arguments are recursively
rendered using `sub_render`, which defaults to `render_head_repr` by
default. If desired, a different renderer may b... | 0.000511 |
def next_frame_glow_shapes():
"""Hparams for qualitative and quantitative results on shapes dataset."""
hparams = next_frame_glow_bair_quant()
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 2
hparams.num_train_frames = 2
hparams.num_cond_latents = 1
hparams.coupling = "additive"
hp... | 0.028283 |
def infer(cls, nij, Ti, root_state, fixed_pi=None, pc=5.0, gap_limit=0.01, **kwargs):
"""
Infer a GTR model by specifying the number of transitions and time spent in each
character. The basic equation that is being solved is
:math:`n_{ij} = pi_i W_{ij} T_j`
where :math:`n_{ij}`... | 0.010758 |
def p_autoscaling_setting_list(p):
"""
autoscaling_setting_list : autoscaling_setting autoscaling_setting_list
| autoscaling_setting
"""
if len(p) == 3:
p[0] = merge_map(p[1], p[2])
elif len(p) == 2:
p[0] = p[1]
else:
raise RuntimeError("Inval... | 0.00274 |
def _encode(cls, lits, weights=None, bound=1, top_id=None,
encoding=EncType.best, comparator='<'):
"""
This is the method that wraps the encoder of PyPBLib. Although the
method can be invoked directly, a user is expected to call one of
the following methods instea... | 0.002464 |
def get_auth(self):
"""
Cached value of authenticate() + the logic for the dynamic auth
"""
if self.dynamic:
return self.dynamic
if self.settings_dict['USER'] == 'dynamic auth':
return {'instance_url': self.settings_dict['HOST']}
# If another threa... | 0.003101 |
def __map_button(self, button):
"""Get the linux xpad code from the Windows xinput code."""
_, start_code, start_value = button
value = start_value
ev_type = "Key"
code = self.manager.codes['xpad'][start_code]
if 1 <= start_code <= 4:
ev_type = "Absolute"
... | 0.004024 |
def vspec(data):
"""
Takes the vector mean of replicate measurements at a given step
"""
vdata, Dirdata, step_meth = [], [], []
tr0 = data[0][0] # set beginning treatment
data.append("Stop")
k, R = 1, 0
for i in range(k, len(data)):
Dirdata = []
if data[i][0] != tr0:
... | 0.002083 |
def language(self, value):
"""
Setter for **self.__language** 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(
"lan... | 0.008197 |
def c2l(c):
"char[4] to unsigned long"
l = U32(c[0])
l = l | (U32(c[1]) << 8)
l = l | (U32(c[2]) << 16)
l = l | (U32(c[3]) << 24)
return l | 0.030864 |
def new_log_level(level, name, logger_name=None):
"""
Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name
"""
@CustomLogLevel(level, name, logger_name)
... | 0.004902 |
def _create_new_jobs(self, job, successor, new_block_id, new_call_stack):
"""
Create a list of new VFG jobs for the successor state.
:param VFGJob job: The VFGJob instance.
:param SimState successor: The succeeding state.
:param BlockID new_block_id: Block ... | 0.003996 |
def getHighestVersion(name, region=None, table="credential-store",
**kwargs):
'''
Return the highest version of `name` in the table
'''
session = get_session(**kwargs)
dynamodb = session.resource('dynamodb', region_name=region)
secrets = dynamodb.Table(table)
response... | 0.002721 |
def _convert_schema(bundle):
""" Converts schema of the dataset to resource dict ready to save to CKAN. """
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create
schema_csv = None
for f in bundle.dataset.files:
if f.path.endswith('schema.csv'):
contents = f.u... | 0.002353 |
def _append(self, target, value):
"""Replace PHP's []= idiom
"""
return self.__p(target) + '[] = ' + self.__p(value) + ';' | 0.013605 |
def show_link(self):
'''show link information'''
for master in self.mpstate.mav_master:
linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3
if master.linkerror:
status = "DOWN"
else:
status = "OK"
sign_string... | 0.005999 |
def typed_returnvalue(self, type_name, formatter=None):
"""Add type information to the return value of this function.
Args:
type_name (str): The name of the type of the return value.
formatter (str): An optional name of a formatting function specified
for the typ... | 0.007059 |
def get_treenodes(self):
"test format of intree nex/nwk, extra features"
if not self.multitree:
# get TreeNodes from Newick
extractor = Newick2TreeNode(self.data[0].strip(), fmt=self.fmt)
# extract one tree
self.treenodes.append(extractor.newick_... | 0.006536 |
def load(self, filename, ctx=None, allow_missing=False,
ignore_extra=False, restore_prefix=''):
"""Load parameters from file.
Parameters
----------
filename : str
Path to parameter file.
ctx : Context or list of Context
Context(s) initialize ... | 0.00724 |
def build(self, parallel=True, debug=False, force=False,
machine_readable=False):
"""Executes a `packer build`
:param bool parallel: Run builders in parallel
:param bool debug: Run in debug mode
:param bool force: Force artifact output even if exists
:param bool ma... | 0.003901 |
def from_dict(cls, async):
"""Return an async job from a dict output by Async.to_dict."""
async_options = decode_async_options(async)
target, args, kwargs = async_options.pop('job')
return cls(target, args, kwargs, **async_options) | 0.015094 |
def mac_address_table_static_forward(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
static = ET.SubElement(mac_address_table, "static"... | 0.002768 |
def update(self, observable, actions):
"""Called when a local reader is added or removed.
Create remote pyro reader objects for added readers.
Delete remote pyro reader objects for removed readers."""
(addedreaders, removedreaders) = actions
for reader in addedreaders:
... | 0.002436 |
def _realToVisibleColumn(self, text, realColumn):
"""If \t is used, real position of symbol in block and visible position differs
This function converts real to visible
"""
generator = self._visibleCharPositionGenerator(text)
for i in range(realColumn):
val = next(gen... | 0.007979 |
def _find_short_paths(self, paths):
"""
Find short paths of given paths.
E.g. if both `/home` and `/home/aoik` exist, only keep `/home`.
:param paths:
Paths.
:return:
Set of short paths.
"""
# Split each path to parts.
# E.g. '/h... | 0.001324 |
def etag_cache(max_age, check_perms=bool):
"""
A decorator for caching views and handling etag conditional requests.
The decorator adds headers to GET requests that help with caching: Last-
Modified, Expires and ETag. It also handles conditional requests, when the
client send an If-Matches header.
... | 0.001623 |
def stopPolitely(self, disconnect=False):
"""Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back."""
logger.info('stopping politely')
if disconnect:
logger.info('will disconnect when stopped')
self.discon... | 0.00243 |
def add_field(self, name, ftype, docfield=None):
""" Add a field to the document (and to the underlying schema)
:param name: name of the new field
:type name: str
:param ftype: type of the new field
:type ftype: subclass of :class:`.GenericType`
"""
self.... | 0.007371 |
def _batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Create the next batched insert, update, or delete command.
"""
buf = StringIO()
# Save space for message length and request id
buf.write(_ZERO_64)
# responseTo, opCode
buf.write(b"\x00\x00\x0... | 0.001376 |
async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
retur... | 0.001736 |
def _thread(self):
""" Thread entry point: does the job once, stored results, and dies. """
# Get
args, kwargs = self._jobs.get()
# Stop thread when (None, None) comes in
if args is None and kwargs is None:
return None # Wrappers should exit as well
# Work
... | 0.004673 |
def complete_message(buf):
"returns msg,buf_remaining or None,buf"
# todo: read dollar-length for strings; I dont think I can blindly trust newlines. learn about escaping
# note: all the length checks are +1 over what I need because I'm asking for *complete* lines.
lines=buf.split('\r\n')
if len(lines)<=... | 0.05303 |
def complete_offer(self, offer_id, complete_dict):
"""
Completes an offer
:param complete_dict: the complete dict with the template id
:param offer_id: the offer id
:return: Response
"""
return self._create_put_request(
resource=OFFERS,
bi... | 0.004819 |
def embedded_in(self):
"""
Used in the view for the InfoObject (in order to be able to use the standard class-based object view.
Should be removed from here and put into a proper custom view for the object.
This query only returns embedding objects of the latest revision: to change
... | 0.007813 |
def zipsafe(dist):
"""Returns whether or not we determine a distribution is zip-safe."""
# zip-safety is only an attribute of eggs. wheels are considered never
# zip safe per implications of PEP 427.
if hasattr(dist, 'egg_info') and dist.egg_info.endswith('EGG-INFO'):
egg_metadata = dist.metadata... | 0.011287 |
def send_command_return(self, obj, command, *arguments):
""" Send command and wait for single line output. """
index_command = obj._build_index_command(command, *arguments)
return obj._extract_return(command, self.chassis_list[obj.chassis].sendQuery(index_command)) | 0.010381 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.