_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55400 | P | train | def P(Document, *fields, **kw):
"""Generate a MongoDB projection dictionary using the Django ORM style."""
__always__ = kw.pop('__always__', set())
projected = set()
omitted = set()
for field in fields:
if field[0] in ('-', '!'):
omitted.add(field[1:])
elif field[0] == '+':
projected.add(field[1:])
... | python | {
"resource": ""
} |
q55401 | MongoSession.is_valid | train | def is_valid(self, context, sid):
"""Identify if the given session ID is currently valid.
Return True if valid, False if explicitly invalid, None if unknown.
"""
record = self._Document.find_one(sid, project=('expires', ))
if not record:
return
return not record._expired | python | {
"resource": ""
} |
q55402 | MongoSession.invalidate | train | def invalidate(self, context, sid):
"""Immediately expire a session from the backing store."""
result = self._Document.get_collection().delete_one({'_id': sid})
return result.deleted_count == 1 | python | {
"resource": ""
} |
q55403 | MongoSession.persist | train | def persist(self, context):
"""Update or insert the session document into the configured collection"""
D = self._Document
document = context.session[self.name]
D.get_collection().replace_one(D.id == document.id, document, True) | python | {
"resource": ""
} |
q55404 | ws_connect | train | def ws_connect(message):
"""
Channels connection setup.
Register the current client on the related Group according to the language
"""
prefix, language = message['path'].strip('/').split('/')
gr = Group('knocker-{0}'.format(language))
gr.add(message.reply_channel)
message.channel_session... | python | {
"resource": ""
} |
q55405 | ws_disconnect | train | def ws_disconnect(message):
"""
Channels connection close.
Deregister the client
"""
language = message.channel_session['knocker']
gr = Group('knocker-{0}'.format(language))
gr.discard(message.reply_channel) | python | {
"resource": ""
} |
q55406 | AnimatedDecorator.start | train | def start(self, autopush=True):
"""Start a new animation instance"""
if self.enabled:
if autopush:
self.push_message(self.message)
self.spinner.message = ' - '.join(self.animation.messages)
if not self.spinner.running:
self.animatio... | python | {
"resource": ""
} |
q55407 | AnimatedDecorator.stop | train | def stop(cls):
"""Stop the thread animation gracefully and reset_message"""
if AnimatedDecorator._enabled:
if cls.spinner.running:
cls.spinner.running = False
cls.animation.thread.join()
if any(cls.animation.messages):
cls.pop_mess... | python | {
"resource": ""
} |
q55408 | AnimatedDecorator.auto_message | train | def auto_message(self, args):
"""Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the first arg is a function, so is... | python | {
"resource": ""
} |
q55409 | WritingDecorator.start | train | def start(self):
"""Activate the TypingStream on stdout"""
self.streams.append(sys.stdout)
sys.stdout = self.stream | python | {
"resource": ""
} |
q55410 | WritingDecorator.stop | train | def stop(cls):
"""Change back the normal stdout after the end"""
if any(cls.streams):
sys.stdout = cls.streams.pop(-1)
else:
sys.stdout = sys.__stdout__ | python | {
"resource": ""
} |
q55411 | Lockable.prolong | train | def prolong(self):
"""Prolong the working duration of an already held lock.
Attempting to prolong a lock not already owned will result in a Locked exception.
"""
D = self.__class__
collection = self.get_collection()
identity = self.Lock()
query = D.id == self
query &= D.lock.instance == identit... | python | {
"resource": ""
} |
q55412 | Lockable.release | train | def release(self, force=False):
"""Release an exclusive lock on this integration task.
Unless forcing, if we are not the current owners of the lock a Locked exception will be raised.
"""
D = self.__class__
collection = self.get_collection()
identity = self.Lock()
query = D.id == self
if not ... | python | {
"resource": ""
} |
q55413 | Animation.write | train | def write(self, message, autoerase=True):
"""Send something for stdout and erased after delay"""
super(Animation, self).write(message)
self.last_message = message
if autoerase:
time.sleep(self.interval)
self.erase(message) | python | {
"resource": ""
} |
q55414 | Clean.write | train | def write(self, message, flush=False):
"""Write something on the default stream with a prefixed message"""
# this need be threadsafe because the concurrent spinning running on
# the stderr
with self.lock:
self.paralell_stream.erase()
super(Clean, self).write(messa... | python | {
"resource": ""
} |
q55415 | Writting.write | train | def write(self, message, flush=True):
if isinstance(message, bytes): # pragma: no cover
message = message.decode('utf-8')
"""A Writting like write method, delayed at each char"""
for char in message:
time.sleep(self.delay * (4 if char == '\n' else 1))
super(... | python | {
"resource": ""
} |
q55416 | Collection._get_default_projection | train | def _get_default_projection(cls):
"""Construct the default projection document."""
projected = [] # The fields explicitly requested for inclusion.
neutral = [] # Fields returning neutral (None) status.
omitted = False # Have any fields been explicitly omitted?
for name, field in cls.__fields__.items(... | python | {
"resource": ""
} |
q55417 | adjust_attribute_sequence | train | def adjust_attribute_sequence(*fields):
"""Move marrow.schema fields around to control positional instantiation order."""
amount = None
if fields and isinstance(fields[0], int):
amount, fields = fields[0], fields[1:]
def adjust_inner(cls):
for field in fields:
if field not in cls.__dict__:
# TODO: ... | python | {
"resource": ""
} |
q55418 | get_hashes | train | def get_hashes(path, exclude=None):
'''
Get a dictionary of file paths and timestamps.
Paths matching `exclude` regex will be excluded.
'''
out = {}
for f in Path(path).rglob('*'):
if f.is_dir():
# We want to watch files, not directories.
continue
if excl... | python | {
"resource": ""
} |
q55419 | Session.request | train | def request(self, method, params=None, query_continue=None,
files=None, auth=None, continuation=False):
"""
Sends an HTTP request to the API.
:Parameters:
method : `str`
Which HTTP method to use for the request?
(Usually "POST" or "GET... | python | {
"resource": ""
} |
q55420 | Session.login | train | def login(self, username, password, login_token=None):
"""
Authenticate with the given credentials. If authentication is
successful, all further requests sent will be signed the authenticated
user.
Note that passwords are sent as plaintext. This is a limitation of the
M... | python | {
"resource": ""
} |
q55421 | Session.continue_login | train | def continue_login(self, login_token, **params):
"""
Continues a login that requires an additional step. This is common
for when login requires completing a captcha or supplying a two-factor
authentication token.
:Parameters:
login_token : `str`
A lo... | python | {
"resource": ""
} |
q55422 | Session.get | train | def get(self, query_continue=None, auth=None, continuation=False,
**params):
"""Makes an API request with the GET method
:Parameters:
query_continue : `dict`
Optionally, the value of a query continuation 'continue' field.
auth : mixed
... | python | {
"resource": ""
} |
q55423 | Session.post | train | def post(self, query_continue=None, upload_file=None, auth=None,
continuation=False, **params):
"""Makes an API request with the POST method
:Parameters:
query_continue : `dict`
Optionally, the value of a query continuation 'continue' field.
upload_f... | python | {
"resource": ""
} |
q55424 | Derived.promote | train | def promote(self, cls, update=False, preserve=True):
"""Transform this record into an instance of a more specialized subclass."""
if not issubclass(cls, self.__class__):
raise TypeError("Must promote to a subclass of " + self.__class__.__name__)
return self._as(cls, update, preserve) | python | {
"resource": ""
} |
q55425 | cut_levels | train | def cut_levels(nodes, start_level):
"""
cutting nodes away from menus
"""
final = []
removed = []
for node in nodes:
if not hasattr(node, 'level'):
# remove and ignore nodes that don't have level information
remove(node, removed)
continue
if no... | python | {
"resource": ""
} |
q55426 | Expires.from_mongo | train | def from_mongo(cls, data, expired=False, **kw):
"""In the event a value that has technically already expired is loaded, swap it for None."""
value = super(Expires, cls).from_mongo(data, **kw)
if not expired and value.is_expired:
return None
return value | python | {
"resource": ""
} |
q55427 | S | train | def S(Document, *fields):
"""Generate a MongoDB sort order list using the Django ORM style."""
result = []
for field in fields:
if isinstance(field, tuple): # Unpack existing tuple.
field, direction = field
result.append((field, direction))
continue
direction = ASCENDING
if not field.starts... | python | {
"resource": ""
} |
q55428 | Get.run | train | def run(self):
"""Reads data from CNPJ list and write results to output directory."""
self._assure_output_dir(self.output)
companies = self.read()
print '%s CNPJs found' % len(companies)
pbar = ProgressBar(
widgets=[Counter(), ' ', Percentage(), ' ', Bar(), ' ', Time... | python | {
"resource": ""
} |
q55429 | Get.read | train | def read(self):
"""Reads data from the CSV file."""
companies = []
with open(self.file) as f:
reader = unicodecsv.reader(f)
for line in reader:
if len(line) >= 1:
cnpj = self.format(line[0])
if self.valid(cnpj):
... | python | {
"resource": ""
} |
q55430 | Get.write | train | def write(self, data):
"""Writes json data to the output directory."""
cnpj, data = data
path = os.path.join(self.output, '%s.json' % cnpj)
with open(path, 'w') as f:
json.dump(data, f, encoding='utf-8') | python | {
"resource": ""
} |
q55431 | Get.valid | train | def valid(self, cnpj):
"""Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string.
"""
if len(cnpj) != 14:
return False
tam = 12
nums = cnpj[:tam]
... | python | {
"resource": ""
} |
q55432 | get_default_config_filename | train | def get_default_config_filename():
"""Returns the configuration filepath.
If PEYOTL_CONFIG_FILE is in the env that is the preferred choice; otherwise ~/.peyotl/config is preferred.
If the preferred file does not exist, then the packaged peyotl/default.conf from the installation of peyotl is
used.
A... | python | {
"resource": ""
} |
q55433 | get_raw_default_config_and_read_file_list | train | def get_raw_default_config_and_read_file_list():
"""Returns a ConfigParser object and a list of filenames that were parsed to initialize it"""
global _CONFIG, _READ_DEFAULT_FILES
if _CONFIG is not None:
return _CONFIG, _READ_DEFAULT_FILES
with _CONFIG_LOCK:
if _CONFIG is not None:
... | python | {
"resource": ""
} |
q55434 | get_config_object | train | def get_config_object():
"""Thread-safe accessor for the immutable default ConfigWrapper object"""
global _DEFAULT_CONFIG_WRAPPER
if _DEFAULT_CONFIG_WRAPPER is not None:
return _DEFAULT_CONFIG_WRAPPER
with _DEFAULT_CONFIG_WRAPPER_LOCK:
if _DEFAULT_CONFIG_WRAPPER is not None:
... | python | {
"resource": ""
} |
q55435 | ConfigWrapper.get_from_config_setting_cascade | train | def get_from_config_setting_cascade(self, sec_param_list, default=None, warn_on_none_level=logging.WARN):
"""return the first non-None setting from a series where each
element in `sec_param_list` is a section, param pair suitable for
a get_config_setting call.
Note that non-None values ... | python | {
"resource": ""
} |
q55436 | parse | train | def parse(input_: Union[str, FileStream], source: str) -> Optional[str]:
"""Parse the text in infile and save the results in outfile
:param input_: string or stream to parse
:param source: source name for python file header
:return: python text if successful
"""
# Step 1: Tokenize the input st... | python | {
"resource": ""
} |
q55437 | Client.fetch | train | def fetch(self, request, callback=None, raise_error=True, **kwargs):
"""Executes a request by AsyncHTTPClient,
asynchronously returning an `tornado.HTTPResponse`.
The ``raise_error=False`` argument currently suppresses
*all* errors, encapsulating them in `HTTPResponse` objects
... | python | {
"resource": ""
} |
q55438 | validate_config | train | def validate_config(key: str, config: dict) -> None:
"""
Call jsonschema validation to raise JSONValidation on non-compliance or silently pass.
:param key: validation schema key of interest
:param config: configuration dict to validate
"""
try:
jsonschema.validate(config, CONFIG_JSON_S... | python | {
"resource": ""
} |
q55439 | __make_id | train | def __make_id(receiver):
"""Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:... | python | {
"resource": ""
} |
q55440 | __purge | train | def __purge():
"""Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock.
"""
global __receivers
newreceivers = collections.defaultdict(list)
for signal, receivers in six.iteritems(__receivers):
alive = [x for... | python | {
"resource": ""
} |
q55441 | __live_receivers | train | def __live_receivers(signal):
"""Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal.
"""
with __lock:
__purge()
receivers = [funcref() for func... | python | {
"resource": ""
} |
q55442 | __is_bound_method | train | def __is_bound_method(method):
"""Return ``True`` if the `method` is a bound method (attached to an class
instance.
Args:
method: A method or function type object.
"""
if not(hasattr(method, "__func__") and hasattr(method, "__self__")):
return False
# Bound methods have a __sel... | python | {
"resource": ""
} |
q55443 | disconnect | train | def disconnect(signal, receiver):
"""Disconnect the receiver `func` from the signal, identified by
`signal_id`.
Args:
signal: The signal identifier.
receiver: The callable receiver to disconnect.
Returns:
True if the receiver was successfully disconnected. False otherwise.
... | python | {
"resource": ""
} |
q55444 | emit | train | def emit(signal, *args, **kwargs):
"""Emit a signal by serially calling each registered signal receiver for
the `signal`.
Note:
The receiver must accept the *args and/or **kwargs that have been
passed to it. There expected parameters are not dictated by
mixbox.
Args:
... | python | {
"resource": ""
} |
q55445 | arrayuniqify | train | def arrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy arrays.
**Parameters**
**X** : numpy array
Determine the unique elements of this numpy array.
**retainorder** : Boolean, optional
Whether or not to return in... | python | {
"resource": ""
} |
q55446 | equalspairs | train | def equalspairs(X, Y):
"""
Indices of elements in a sorted numpy array equal to those in another.
Given numpy array `X` and sorted numpy array `Y`, determine the indices in
Y equal to indices in X.
Returns `[A,B]` where `A` and `B` are numpy arrays of indices in `X` such
that::
... | python | {
"resource": ""
} |
q55447 | isin | train | def isin(X,Y):
"""
Indices of elements in a numpy array that appear in another.
Fast routine for determining indices of elements in numpy array `X` that
appear in numpy array `Y`, returning a boolean array `Z` such that::
Z[i] = X[i] in Y
**Parameters**
**X** : numpy ar... | python | {
"resource": ""
} |
q55448 | arraydifference | train | def arraydifference(X,Y):
"""
Elements of a numpy array that do not appear in another.
Fast routine for determining which elements in numpy array `X`
do not appear in numpy array `Y`.
**Parameters**
**X** : numpy array
Numpy array to comapare to numpy array `Y`.
... | python | {
"resource": ""
} |
q55449 | arraymax | train | def arraymax(X,Y):
"""
Fast "vectorized" max function for element-wise comparison of two numpy arrays.
For two numpy arrays `X` and `Y` of equal length,
return numpy array `Z` such that::
Z[i] = max(X[i],Y[i])
**Parameters**
**X** : numpy array
Numpy... | python | {
"resource": ""
} |
q55450 | Wallet._seed2did | train | async def _seed2did(self) -> str:
"""
Derive DID, as per indy-sdk, from seed.
:return: DID
"""
rv = None
dids_with_meta = json.loads(await did.list_my_dids_with_meta(self.handle)) # list
if dids_with_meta:
for did_with_meta in dids_with_meta: # di... | python | {
"resource": ""
} |
q55451 | Wallet.remove | train | async def remove(self) -> None:
"""
Remove serialized wallet if it exists.
"""
LOGGER.debug('Wallet.remove >>>')
try:
LOGGER.info('Removing wallet: %s', self.name)
await wallet.delete_wallet(json.dumps(self.cfg), json.dumps(self.access_creds))
ex... | python | {
"resource": ""
} |
q55452 | loadSV | train | def loadSV(fname, shape=None, titles=None, aligned=False, byteorder=None,
renamer=None, **kwargs):
"""
Load a delimited text file to a numpy record array.
Basically, this function calls loadSVcols and combines columns returned by
that function into a numpy ndarray with stuctured dtype. A... | python | {
"resource": ""
} |
q55453 | loadSVrecs | train | def loadSVrecs(fname, uselines=None, skiprows=0, linefixer=None,
delimiter_regex=None, verbosity=DEFAULT_VERBOSITY, **metadata):
"""
Load a separated value text file to a list of lists of strings of records.
Takes a tabular text file with a specified delimeter and end-of-line
character... | python | {
"resource": ""
} |
q55454 | parsetypes | train | def parsetypes(dtype):
"""
Parse the types from a structured numpy dtype object.
Return list of string representations of types from a structured numpy
dtype object, e.g. ['int', 'float', 'str'].
Used by :func:`tabular.io.saveSV` to write out type information in the
header.
**Parameters... | python | {
"resource": ""
} |
q55455 | thresholdcoloring | train | def thresholdcoloring(coloring, names):
"""
Threshold a coloring dictionary for a given list of column names.
Threshold `coloring` based on `names`, a list of strings in::
coloring.values()
**Parameters**
**coloring** : dictionary
Hierarchical structure on the columns g... | python | {
"resource": ""
} |
q55456 | makedir | train | def makedir(dir_name):
"""
"Strong" directory maker.
"Strong" version of `os.mkdir`. If `dir_name` already exists, this deletes
it first.
**Parameters**
**dir_name** : string
Path to a file directory that may or may not already exist.
**See Also:**
:func:`ta... | python | {
"resource": ""
} |
q55457 | pass_community | train | def pass_community(f):
"""Decorator to pass community."""
@wraps(f)
def inner(community_id, *args, **kwargs):
c = Community.get(community_id)
if c is None:
abort(404)
return f(c, *args, **kwargs)
return inner | python | {
"resource": ""
} |
q55458 | permission_required | train | def permission_required(action):
"""Decorator to require permission."""
def decorator(f):
@wraps(f)
def inner(community, *args, **kwargs):
permission = current_permission_factory(community, action=action)
if not permission.can():
abort(403)
ret... | python | {
"resource": ""
} |
q55459 | format_item | train | def format_item(item, template, name='item'):
"""Render a template to a string with the provided item in context."""
ctx = {name: item}
return render_template_to_string(template, **ctx) | python | {
"resource": ""
} |
q55460 | new | train | def new():
"""Create a new community."""
form = CommunityForm(formdata=request.values)
ctx = mycommunities_ctx()
ctx.update({
'form': form,
'is_new': True,
'community': None,
})
if form.validate_on_submit():
data = copy.deepcopy(form.data)
community_id ... | python | {
"resource": ""
} |
q55461 | edit | train | def edit(community):
"""Create or edit a community."""
form = EditCommunityForm(formdata=request.values, obj=community)
deleteform = DeleteCommunityForm()
ctx = mycommunities_ctx()
ctx.update({
'form': form,
'is_new': False,
'community': community,
'deleteform': delet... | python | {
"resource": ""
} |
q55462 | delete | train | def delete(community):
"""Delete a community."""
deleteform = DeleteCommunityForm(formdata=request.values)
ctx = mycommunities_ctx()
ctx.update({
'deleteform': deleteform,
'is_new': False,
'community': community,
})
if deleteform.validate_on_submit():
community.d... | python | {
"resource": ""
} |
q55463 | ot_find_tree | train | def ot_find_tree(arg_dict, exact=True, verbose=False, oti_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of trees including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyotl.sugar w... | python | {
"resource": ""
} |
q55464 | is_iterable | train | def is_iterable(etype) -> bool:
""" Determine whether etype is a List or other iterable """
return type(etype) is GenericMeta and issubclass(etype.__extra__, Iterable) | python | {
"resource": ""
} |
q55465 | main | train | def main(argv):
"""This function sets up a command-line option parser and then calls fetch_and_write_mrca
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to the MRCA for a set of OTT IDs.'
parser = argparse.ArgumentParser(prog='ot-tree-of-life-m... | python | {
"resource": ""
} |
q55466 | Origin.send_schema | train | async def send_schema(self, schema_data_json: str) -> str:
"""
Send schema to ledger, then retrieve it as written to the ledger and return it.
If schema already exists on ledger, log error and return schema.
:param schema_data_json: schema data json with name, version, attribute names; ... | python | {
"resource": ""
} |
q55467 | TypeAwareDocStore._locked_refresh_doc_ids | train | def _locked_refresh_doc_ids(self):
"""Assumes that the caller has the _index_lock !
"""
d = {}
for s in self._shards:
for k in s.doc_index.keys():
if k in d:
raise KeyError('doc "{i}" found in multiple repos'.format(i=k))
d[... | python | {
"resource": ""
} |
q55468 | TypeAwareDocStore.push_doc_to_remote | train | def push_doc_to_remote(self, remote_name, doc_id=None):
"""This will push the master branch to the remote named `remote_name`
using the mirroring strategy to cut down on locking of the working repo.
`doc_id` is used to determine which shard should be pushed.
if `doc_id` is None, all sha... | python | {
"resource": ""
} |
q55469 | TypeAwareDocStore.iter_doc_filepaths | train | def iter_doc_filepaths(self, **kwargs):
"""Generator that iterates over all detected documents.
and returns the filesystem path to each doc.
Order is by shard, but arbitrary within shards.
@TEMP not locked to prevent doc creation/deletion
"""
for shard in self._shards:
... | python | {
"resource": ""
} |
q55470 | CommunityForm.data | train | def data(self):
"""Form data."""
d = super(CommunityForm, self).data
d.pop('csrf_token', None)
return d | python | {
"resource": ""
} |
q55471 | CommunityForm.validate_identifier | train | def validate_identifier(self, field):
"""Validate field identifier."""
if field.data:
field.data = field.data.lower()
if Community.get(field.data, with_deleted=True):
raise validators.ValidationError(
_('The identifier already exists. '
... | python | {
"resource": ""
} |
q55472 | read_filepath | train | def read_filepath(filepath, encoding='utf-8'):
"""Returns the text content of `filepath`"""
with codecs.open(filepath, 'r', encoding=encoding) as fo:
return fo.read() | python | {
"resource": ""
} |
q55473 | download | train | def download(url, encoding='utf-8'):
"""Returns the text fetched via http GET from URL, read as `encoding`"""
import requests
response = requests.get(url)
response.encoding = encoding
return response.text | python | {
"resource": ""
} |
q55474 | pretty_dict_str | train | def pretty_dict_str(d, indent=2):
"""shows JSON indented representation of d"""
b = StringIO()
write_pretty_dict_str(b, d, indent=indent)
return b.getvalue() | python | {
"resource": ""
} |
q55475 | write_pretty_dict_str | train | def write_pretty_dict_str(out, obj, indent=2):
"""writes JSON indented representation of `obj` to `out`"""
json.dump(obj,
out,
indent=indent,
sort_keys=True,
separators=(',', ': '),
ensure_ascii=False,
encoding="utf-8") | python | {
"resource": ""
} |
q55476 | community_responsify | train | def community_responsify(schema_class, mimetype):
"""Create a community response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
"""
def view(data, code=200, headers=None, links_item_factory=None,
page=None, urlkwargs=None, links_pagination_f... | python | {
"resource": ""
} |
q55477 | InternalError.from_error | train | def from_error(exc_info, json_encoder, debug_url=None):
"""Wraps another Exception in an InternalError.
:param exc_info: The exception info for the wrapped exception
:type exc_info: (type, object, traceback)
:type json_encoder: json.JSONEncoder
:type debug_url: str | None
... | python | {
"resource": ""
} |
q55478 | SchemaCache.contains | train | def contains(self, index: Union[SchemaKey, int, str]) -> bool:
"""
Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the ... | python | {
"resource": ""
} |
q55479 | RevoCacheEntry.cull | train | def cull(self, delta: bool) -> None:
"""
Cull cache entry frame list to size, favouring most recent query time.
:param delta: True to operate on rev reg deltas, False for rev reg states
"""
LOGGER.debug('RevoCacheEntry.cull >>> delta: %s', delta)
rr_frames = self.rr_de... | python | {
"resource": ""
} |
q55480 | RevocationCache.dflt_interval | train | def dflt_interval(self, cd_id: str) -> (int, int):
"""
Return default non-revocation interval from latest 'to' times on delta frames
of revocation cache entries on indices stemming from input cred def id.
Compute the 'from'/'to' values as the earliest/latest 'to' values of all
c... | python | {
"resource": ""
} |
q55481 | Caches.parse | train | def parse(base_dir: str, timestamp: int = None) -> int:
"""
Parse and update from archived cache files. Only accept new content;
do not overwrite any existing cache content.
:param base_dir: archive base directory
:param timestamp: epoch time of cache serving as subdirectory, de... | python | {
"resource": ""
} |
q55482 | detect_nexson_version | train | def detect_nexson_version(blob):
"""Returns the nexml2json attribute or the default code for badgerfish"""
n = get_nexml_el(blob)
assert isinstance(n, dict)
return n.get('@nexml2json', BADGER_FISH_NEXSON_VERSION) | python | {
"resource": ""
} |
q55483 | _add_value_to_dict_bf | train | def _add_value_to_dict_bf(d, k, v):
"""Adds the `k`->`v` mapping to `d`, but if a previous element exists it changes
the value of for the key to list.
This is used in the BadgerFish mapping convention.
This is a simple multi-dict that is only suitable when you know that you'll never
store a list o... | python | {
"resource": ""
} |
q55484 | _add_uniq_value_to_dict_bf | train | def _add_uniq_value_to_dict_bf(d, k, v):
"""Like _add_value_to_dict_bf but will not add v if another
element in under key `k` has the same value.
"""
prev = d.get(k)
if prev is None:
d[k] = v
elif isinstance(prev, list):
if not isinstance(v, list):
v = [v]
for... | python | {
"resource": ""
} |
q55485 | _debug_dump_dom | train | def _debug_dump_dom(el):
"""Debugging helper. Prints out `el` contents."""
import xml.dom.minidom
s = [el.nodeName]
att_container = el.attributes
for i in range(att_container.length):
attr = att_container.item(i)
s.append(' @{a}="{v}"'.format(a=attr.name, v=attr.value))
for c in... | python | {
"resource": ""
} |
q55486 | _convert_hbf_meta_val_for_xml | train | def _convert_hbf_meta_val_for_xml(key, val):
"""Convert to a BadgerFish-style dict for addition to a dict suitable for
addition to XML tree or for v1.0 to v0.0 conversion."""
if isinstance(val, list):
return [_convert_hbf_meta_val_for_xml(key, i) for i in val]
is_literal = True
content = Non... | python | {
"resource": ""
} |
q55487 | find_nested_meta_first | train | def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = '^' + prop_name
return d.get(p) | python | {
"resource": ""
} |
q55488 | decode | train | def decode(value: str) -> Union[str, None, bool, int, float]:
"""
Decode encoded credential attribute value.
:param value: numeric string to decode
:return: decoded value, stringified if original was neither str, bool, int, nor float
"""
assert value.isdigit() or value[0] == '-' and value[1:].... | python | {
"resource": ""
} |
q55489 | validate_params_match | train | def validate_params_match(method, parameters):
"""Validates that the given parameters are exactly the method's declared parameters.
:param method: The method to be called
:type method: function
:param parameters: The parameters to use in the call
:type parameters: dict[str, object] | list[object]
... | python | {
"resource": ""
} |
q55490 | check_types | train | def check_types(parameters, parameter_types, strict_floats):
"""Checks that the given parameters have the correct types.
:param parameters: List of (name, value) pairs of the given parameters
:type parameters: dict[str, object]
:param parameter_types: Parameter type by name.
:type parameter_types: ... | python | {
"resource": ""
} |
q55491 | check_type_declaration | train | def check_type_declaration(parameter_names, parameter_types):
"""Checks that exactly the given parameter names have declared types.
:param parameter_names: The names of the parameters in the method declaration
:type parameter_names: list[str]
:param parameter_types: Parameter type by name
:type par... | python | {
"resource": ""
} |
q55492 | check_return_type | train | def check_return_type(value, expected_type, strict_floats):
"""Checks that the given return value has the correct type.
:param value: Value returned by the method
:type value: object
:param expected_type: Expected return type
:type expected_type: type
:param strict_floats: If False, treat integ... | python | {
"resource": ""
} |
q55493 | _make_phylesystem_cache_region | train | def _make_phylesystem_cache_region(**kwargs):
"""Only intended to be called by the Phylesystem singleton.
"""
global _CACHE_REGION_CONFIGURED, _REGION
if _CACHE_REGION_CONFIGURED:
return _REGION
_CACHE_REGION_CONFIGURED = True
try:
# noinspection PyPackageRequirements
fro... | python | {
"resource": ""
} |
q55494 | GitActionBase.path_for_doc | train | def path_for_doc(self, doc_id):
"""Returns doc_dir and doc_filepath for doc_id.
"""
full_path = self.path_for_doc_fn(self.repo, doc_id)
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn))
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc re... | python | {
"resource": ""
} |
q55495 | GitActionBase.current_branch | train | def current_branch(self):
"""Return the current branch name"""
branch_name = git(self.gitdir, self.gitwd, "symbolic-ref", "HEAD")
return branch_name.replace('refs/heads/', '').strip() | python | {
"resource": ""
} |
q55496 | GitActionBase.branch_exists | train | def branch_exists(self, branch):
"""Returns true or false depending on if a branch exists"""
try:
git(self.gitdir, self.gitwd, "rev-parse", branch)
except sh.ErrorReturnCode:
return False
return True | python | {
"resource": ""
} |
q55497 | GitActionBase.fetch | train | def fetch(self, remote='origin'):
"""fetch from a remote"""
git(self.gitdir, "fetch", remote, _env=self.env()) | python | {
"resource": ""
} |
q55498 | GitActionBase.get_version_history_for_file | train | def get_version_history_for_file(self, filepath):
""" Return a dict representation of this file's commit history
This uses specially formatted git-log output for easy parsing, as described here:
http://blog.lost-theory.org/post/how-to-parse-git-log-output/
For a full list of availab... | python | {
"resource": ""
} |
q55499 | GitActionBase._add_and_commit | train | def _add_and_commit(self, doc_filepath, author, commit_msg):
"""Low level function used internally when you have an absolute filepath to add and commit"""
try:
git(self.gitdir, self.gitwd, "add", doc_filepath)
git(self.gitdir, self.gitwd, "commit", author=author, message=commit_m... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.