_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37500 | URL.qs_add | train | def qs_add(self, *args, **kwargs):
'''Add value to QuerySet MultiDict'''
query = self.query.copy()
if args:
mdict = MultiDict(args[0])
for k, v in mdict.items():
query.add(k, v)
for k, v in kwargs.items():
query.add(k, v)
return... | python | {
"resource": ""
} |
q37501 | URL.qs_delete | train | def qs_delete(self, *keys):
'''Delete value from QuerySet MultiDict'''
query = self.query.copy()
for key in set(keys):
try:
del query[key]
except KeyError:
pass
return self._copy(query=query) | python | {
"resource": ""
} |
q37502 | URL.qs_get | train | def qs_get(self, key, default=None):
'''Get a value from QuerySet MultiDict'''
return self.query.get(key, default=default) | python | {
"resource": ""
} |
q37503 | warehouse_query | train | def warehouse_query(line, cell):
"my cell magic"
from IPython import get_ipython
parts = line.split()
w_var_name = parts.pop(0)
w = get_ipython().ev(w_var_name)
w.query(cell).close() | python | {
"resource": ""
} |
q37504 | list_product_releases | train | def list_product_releases(page_size=200, page_index=0, sort="", q=""):
"""
List all ProductReleases
"""
data = list_product_releases_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37505 | update_release | train | def update_release(id, **kwargs):
"""
Update an existing ProductRelease with new information
"""
data = update_release_raw(id, **kwargs)
if data:
return utils.format_json(data) | python | {
"resource": ""
} |
q37506 | Library.get | train | def get(self, identifier):
"""get provider by id"""
for provider in self._providers:
if provider.identifier == identifier:
return provider
return None | python | {
"resource": ""
} |
q37507 | Library.list_song_standby | train | def list_song_standby(self, song, onlyone=True):
"""try to list all valid standby
Search a song in all providers. The typical usage scenario is when a
song is not available in one provider, we can try to acquire it from other
providers.
Standby choosing strategy: search from al... | python | {
"resource": ""
} |
q37508 | import_class_by_string | train | def import_class_by_string(name):
"""Return a class by importing its module from a fully qualified string."""
components = name.split('.')
clazz = components.pop()
mod = __import__('.'.join(components))
components += [clazz]
for comp in components[1:]:
mod = getattr(mod, comp)
retu... | python | {
"resource": ""
} |
q37509 | SimSymbolicDbgMemory.get_unconstrained_bytes | train | def get_unconstrained_bytes(self, name, bits, source=None, key=None, inspect=True, events=True, **kwargs):
"""
Get some consecutive unconstrained bytes.
:param name: Name of the unconstrained variable
:param bits: Size of the unconstrained variable
:param source: Where those byt... | python | {
"resource": ""
} |
q37510 | BuildConfigurationRest.build_type | train | def build_type(self, build_type):
"""
Sets the build_type of this BuildConfigurationRest.
:param build_type: The build_type of this BuildConfigurationRest.
:type: str
"""
allowed_values = ["MVN", "NPM"]
if build_type not in allowed_values:
raise Value... | python | {
"resource": ""
} |
q37511 | failUnlessWarns | train | def failUnlessWarns(self, category, message, filename, f,
*args, **kwargs):
"""
Fail if the given function doesn't generate the specified warning when
called. It calls the function, checks the warning, and forwards the
result of the function if everything is fine.
@param category... | python | {
"resource": ""
} |
q37512 | cases.cases | train | def cases(self, env, data):
'''Calls each nested handler until one of them returns nonzero result.
If any handler returns `None`, it is interpreted as
"request does not match, the handler has nothing to do with it and
`web.cases` should try to call the next handler".'''
for ha... | python | {
"resource": ""
} |
q37513 | create_win32tz_map | train | def create_win32tz_map(windows_zones_xml):
"""Creates a map between Windows and Olson timezone names.
Args:
windows_zones_xml: The CLDR XML mapping.
Yields:
(win32_name, olson_name, comment)
"""
coming_comment = None
win32_name = None
territory = None
parser = genshi.input.XMLParser(StringIO(w... | python | {
"resource": ""
} |
q37514 | update_stored_win32tz_map | train | def update_stored_win32tz_map():
"""Downloads the cldr win32 timezone map and stores it in win32tz_map.py."""
windows_zones_xml = download_cldr_win32tz_map_xml()
source_hash = hashlib.md5(windows_zones_xml).hexdigest()
if hasattr(windows_zones_xml, "decode"):
windows_zones_xml = windows_zones_xml.decode("u... | python | {
"resource": ""
} |
q37515 | SimDbgMemory.load_objects | train | def load_objects(self, addr, num_bytes, ret_on_segv=False):
"""
Load memory objects from paged memory.
:param addr: Address to start loading.
:param num_bytes: Number of bytes to load.
:param bool ret_on_segv: True if you want load_bytes to return directly when a SIGSEV is trigg... | python | {
"resource": ""
} |
q37516 | SimDbgMemory.permissions | train | def permissions(self, addr, permissions=None):
"""
Returns the permissions for a page at address `addr`.
If optional argument permissions is given, set page permissions to that prior to returning permissions.
"""
if self.state.solver.symbolic(addr):
raise SimMemoryE... | python | {
"resource": ""
} |
q37517 | call_interval | train | def call_interval(freq, **kwargs):
"""Decorator for the CallInterval wrapper"""
def wrapper(f):
return CallInterval(f, freq, **kwargs)
return wrapper | python | {
"resource": ""
} |
q37518 | ProgressSection.add | train | def add(self, *args, **kwargs):
"""Add a new record to the section"""
if self.start and self.start.state == 'done' and kwargs.get('log_action') != 'done':
raise ProgressLoggingError("Can't add -- process section is done")
self.augment_args(args, kwargs)
kwargs['log_action'... | python | {
"resource": ""
} |
q37519 | ProgressSection.update | train | def update(self, *args, **kwargs):
"""Update the last section record"""
self.augment_args(args, kwargs)
kwargs['log_action'] = kwargs.get('log_action', 'update')
if not self.rec:
return self.add(**kwargs)
else:
for k, v in kwargs.items():
... | python | {
"resource": ""
} |
q37520 | ProgressSection.add_update | train | def add_update(self, *args, **kwargs):
"""A records is added, then on subsequent calls, updated"""
if not self._ai_rec_id:
self._ai_rec_id = self.add(*args, **kwargs)
else:
au_save = self._ai_rec_id
self.update(*args, **kwargs)
self._ai_rec_id = a... | python | {
"resource": ""
} |
q37521 | ProgressSection.update_done | train | def update_done(self, *args, **kwargs):
"""Clear out the previous update"""
kwargs['state'] = 'done'
self.update(*args, **kwargs)
self.rec = None | python | {
"resource": ""
} |
q37522 | ProgressSection.done | train | def done(self, *args, **kwargs):
"""Mark the whole ProgressSection as done"""
kwargs['state'] = 'done'
pr_id = self.add(*args, log_action='done', **kwargs)
self._session.query(Process).filter(Process.group == self._group).update({Process.state: 'done'})
self.start.state = 'done'... | python | {
"resource": ""
} |
q37523 | ProcessLogger.start | train | def start(self, phase, stage, **kwargs):
"""Start a new routine, stage or phase"""
return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs) | python | {
"resource": ""
} |
q37524 | ProcessLogger.clean | train | def clean(self):
"""Delete all of the records"""
# Deleting seems to be really weird and unrelable.
self._session \
.query(Process) \
.filter(Process.d_vid == self._d_vid) \
.delete(synchronize_session='fetch')
for r in self.records:
self... | python | {
"resource": ""
} |
q37525 | ProcessLogger.build | train | def build(self):
"""Access build configuration values as attributes. See self.process
for a usage example"""
from ambry.orm.config import BuildConfigGroupAccessor
# It is a lightweight object, so no need to cache
return BuildConfigGroupAccessor(self.dataset, 'buildstate', se... | python | {
"resource": ""
} |
q37526 | BuildEnvironmentRest.system_image_type | train | def system_image_type(self, system_image_type):
"""
Sets the system_image_type of this BuildEnvironmentRest.
:param system_image_type: The system_image_type of this BuildEnvironmentRest.
:type: str
"""
allowed_values = ["DOCKER_IMAGE", "VIRTUAL_MACHINE_RAW", "VIRTUAL_MAC... | python | {
"resource": ""
} |
q37527 | ExtDoc.group_by_source | train | def group_by_source(self):
"""Return a dict of all of the docs, with the source associated
with the doc as a key"""
from collections import defaultdict
docs = defaultdict(list)
for k, v in self.items():
if 'source' in v:
docs[v.source].append(dict(v.i... | python | {
"resource": ""
} |
q37528 | FilePath.preauthChild | train | def preauthChild(self, path):
"""
Use me if `path' might have slashes in it, but you know they're safe.
(NOT slashes at the beginning. It still needs to be a _child_).
"""
newpath = abspath(joinpath(self.path, normpath(path)))
if not newpath.startswith(self.path):
... | python | {
"resource": ""
} |
q37529 | FilePath.childSearchPreauth | train | def childSearchPreauth(self, *paths):
"""Return my first existing child with a name in 'paths'.
paths is expected to be a list of *pre-secured* path fragments; in most
cases this will be specified by a system administrator and not an
arbitrary user.
If no appropriately-named ch... | python | {
"resource": ""
} |
q37530 | FilePath.siblingExtensionSearch | train | def siblingExtensionSearch(self, *exts):
"""Attempt to return a path with my name, given multiple possible
extensions.
Each extension in exts will be tested and the first path which exists
will be returned. If no path exists, None will be returned. If '' is
in exts, then if th... | python | {
"resource": ""
} |
q37531 | FilePath.globChildren | train | def globChildren(self, pattern):
"""
Assuming I am representing a directory, return a list of
FilePaths representing my children that match the given
pattern.
"""
import glob
path = self.path[-1] == '/' and self.path + pattern or slash.join([self.path, pattern])
... | python | {
"resource": ""
} |
q37532 | FilePath.create | train | def create(self):
"""Exclusively create a file, only if this file previously did not exist.
"""
fdint = os.open(self.path, (os.O_EXCL |
os.O_CREAT |
os.O_RDWR))
# XXX TODO: 'name' attribute of returned files is not ... | python | {
"resource": ""
} |
q37533 | FilePath.temporarySibling | train | def temporarySibling(self):
"""
Create a path naming a temporary sibling of this path in a secure fashion.
"""
sib = self.parent().child(_secureEnoughString() + self.basename())
sib.requireCreate()
return sib | python | {
"resource": ""
} |
q37534 | start | train | def start():
"""
Start recording stats. Call this from a benchmark script when your setup
is done. Call this at most once.
@raise RuntimeError: Raised if the parent process responds with anything
other than an acknowledgement of this message.
"""
os.write(BenchmarkProcess.BACKCHANNEL_OUT,... | python | {
"resource": ""
} |
q37535 | main | train | def main():
"""
Run me with the filename of a benchmark script as an argument. I will time
it and append the results to a file named output in the current working
directory.
"""
name = sys.argv[1]
path = filepath.FilePath('.stat').temporarySibling()
path.makedirs()
func = makeBenchm... | python | {
"resource": ""
} |
q37536 | BasicProcess.spawn | train | def spawn(cls, executable, args, path, env, spawnProcess=None):
"""
Run an executable with some arguments in the given working directory with
the given environment variables.
Returns a Deferred which fires with a two-tuple of (exit status, output
list) if the process terminates ... | python | {
"resource": ""
} |
q37537 | get | train | def get(orcid_id):
"""
Get an author based on an ORCID identifier.
"""
resp = requests.get(ORCID_PUBLIC_BASE_URL + unicode(orcid_id),
headers=BASE_HEADERS)
json_body = resp.json()
return Author(json_body) | python | {
"resource": ""
} |
q37538 | create_product | train | def create_product(name, abbreviation, **kwargs):
"""
Create a new Product
"""
data = create_product_raw(name, abbreviation, **kwargs)
if data:
return utils.format_json(data) | python | {
"resource": ""
} |
q37539 | update_product | train | def update_product(product_id, **kwargs):
"""
Update a Product with new information
"""
content = update_product_raw(product_id, **kwargs)
if content:
return utils.format_json(content) | python | {
"resource": ""
} |
q37540 | get_product | train | def get_product(id=None, name=None):
"""
Get a specific Product by name or ID
"""
content = get_product_raw(id, name)
if content:
return utils.format_json(content) | python | {
"resource": ""
} |
q37541 | list_versions_for_product | train | def list_versions_for_product(id=None, name=None, page_size=200, page_index=0, sort='', q=''):
"""
List all ProductVersions for a given Product
"""
content = list_versions_for_product_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | {
"resource": ""
} |
q37542 | list_products | train | def list_products(page_size=200, page_index=0, sort="", q=""):
"""
List all Products
"""
content = list_products_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | python | {
"resource": ""
} |
q37543 | DstkGeocoder.geocode | train | def geocode(self):
"""A Generator that reads from the address generators and returns
geocode results.
The generator yields ( address, geocode_results, object)
"""
submit_set = []
data_map = {}
for address, o in self.gen:
submit_set.append(address)
... | python | {
"resource": ""
} |
q37544 | migrate | train | def migrate(connection, dsn):
""" Collects all migrations and applies missed.
Args:
connection (sqlalchemy connection):
"""
all_migrations = _get_all_migrations()
logger.debug('Collected migrations: {}'.format(all_migrations))
for version, modname in all_migrations:
if _is_mis... | python | {
"resource": ""
} |
q37545 | get_stored_version | train | def get_stored_version(connection):
""" Returns database version.
Args:
connection (sqlalchemy connection):
Raises: Assuming user_version pragma (sqlite case) and user_version table (postgresql case)
exist because they created with the database creation.
Returns:
int: version ... | python | {
"resource": ""
} |
q37546 | _validate_version | train | def _validate_version(connection, dsn):
""" Performs on-the-fly schema updates based on the models version.
Raises:
DatabaseError: if user uses old sqlite database.
"""
try:
version = get_stored_version(connection)
except VersionIsNotStored:
logger.debug('Version not stored... | python | {
"resource": ""
} |
q37547 | _migration_required | train | def _migration_required(connection):
""" Returns True if ambry models do not match to db tables. Otherwise returns False. """
stored_version = get_stored_version(connection)
actual_version = SCHEMA_VERSION
assert isinstance(stored_version, int)
assert isinstance(actual_version, int)
assert store... | python | {
"resource": ""
} |
q37548 | _update_version | train | def _update_version(connection, version):
""" Updates version in the db to the given version.
Args:
connection (sqlalchemy connection): sqlalchemy session where to update version.
version (int): version of the migration.
"""
if connection.engine.name == 'sqlite':
connection.exe... | python | {
"resource": ""
} |
q37549 | _get_all_migrations | train | def _get_all_migrations():
""" Returns sorted list of all migrations.
Returns:
list of (int, str) tuples: first elem of the tuple is migration number, second if module name.
"""
from . import migrations
package = migrations
prefix = package.__name__ + '.'
all_migrations = []
f... | python | {
"resource": ""
} |
q37550 | Database.create | train | def create(self):
"""Create the database from the base SQL."""
if not self.exists():
self._create_path()
self.create_tables()
return True
return False | python | {
"resource": ""
} |
q37551 | Database._create_path | train | def _create_path(self):
"""Create the path to hold the database, if one wwas specified."""
if self.driver == 'sqlite' and 'memory' not in self.dsn and self.dsn != 'sqlite://':
dir_ = os.path.dirname(self.path)
if dir_ and not os.path.exists(dir_):
try:
... | python | {
"resource": ""
} |
q37552 | Database.exists | train | def exists(self):
"""Return True if the database exists, or for Sqlite, which will create the file on the
first reference, the file has been initialized with the root config """
if self.driver == 'sqlite' and not os.path.exists(self.path):
return False
# init engine
... | python | {
"resource": ""
} |
q37553 | Database.engine | train | def engine(self):
"""return the SqlAlchemy engine for this database."""
if not self._engine:
if 'postgres' in self.driver:
if 'connect_args' not in self.engine_kwargs:
self.engine_kwargs['connect_args'] = {
'application_name': '{... | python | {
"resource": ""
} |
q37554 | Database.connection | train | def connection(self):
"""Return an SqlAlchemy connection."""
if not self._connection:
logger.debug('Opening connection to: {}'.format(self.dsn))
self._connection = self.engine.connect()
logger.debug('Opened connection to: {}'.format(self.dsn))
# logger.debug(... | python | {
"resource": ""
} |
q37555 | Database.session | train | def session(self):
"""Return a SqlAlchemy session."""
from sqlalchemy.orm import sessionmaker
from sqlalchemy.event import listen
if not self.Session:
self.Session = sessionmaker(bind=self.engine)
if not self._session:
self._session = self.Session()
... | python | {
"resource": ""
} |
q37556 | Database.metadata | train | def metadata(self):
"""Return an SqlAlchemy MetaData object, bound to the engine."""
from sqlalchemy import MetaData
metadata = MetaData(bind=self.engine, schema=self._schema)
metadata.reflect(self.engine)
return metadata | python | {
"resource": ""
} |
q37557 | Database._add_config_root | train | def _add_config_root(self):
""" Adds the root dataset, which holds configuration values for the database. """
try:
self.session.query(Dataset).filter_by(id=ROOT_CONFIG_NAME).one()
self.close_session()
except NoResultFound:
o = Dataset(
id=ROOT... | python | {
"resource": ""
} |
q37558 | Database.new_dataset | train | def new_dataset(self, *args, **kwargs):
""" Creates a new dataset
:param args: Positional args passed to the Dataset constructor.
:param kwargs: Keyword args passed to the Dataset constructor.
:return: :class:`ambry.orm.Dataset`
:raises: :class:`ambry.orm.ConflictError` if the ... | python | {
"resource": ""
} |
q37559 | Database.root_dataset | train | def root_dataset(self):
"""Return the root dataset, which hold configuration values for the library"""
ds = self.dataset(ROOT_CONFIG_NAME_V)
ds._database = self
return ds | python | {
"resource": ""
} |
q37560 | Database.dataset | train | def dataset(self, ref, load_all=False, exception=True):
"""Return a dataset, given a vid or id
:param ref: Vid or id for a dataset. If an id is provided, will it will return the one with the
largest revision number
:param load_all: Use a query that eagerly loads everything.
:re... | python | {
"resource": ""
} |
q37561 | BaseMigration.create_table | train | def create_table(table, connection, schema=None):
"""Create a single table, primarily used din migrations"""
orig_schemas = {}
# These schema shenanigans are almost certainly wrong.
# But they are expedient. For Postgres, it puts the library
# tables in the Library schema. We n... | python | {
"resource": ""
} |
q37562 | return_locals | train | def return_locals(func):
'''Modifies decorated function to return its locals'''
@functools.wraps(func)
def wrap(*args, **kwargs):
frames = []
def tracer(frame, event, arg): # pragma: no cover
# coverage does not work in this function because the tracer
# is deactiva... | python | {
"resource": ""
} |
q37563 | generate_repo_list | train | def generate_repo_list(product_name=None, product_version=None, product_milestone=None):
"""
Generates list of artifacts for offline repository.
"""
if not validate_input_parameters(product_name, product_version, product_milestone):
sys.exit(1)
product_version = pnc_api.product_versions.get_... | python | {
"resource": ""
} |
q37564 | DelayedCall.cancel | train | def cancel(self):
"""Unschedule this call
@raise AlreadyCancelled: Raised if this call has already been
unscheduled.
@raise AlreadyCalled: Raised if this call has already been made.
"""
if self.cancelled:
raise error.AlreadyCancelled
elif self.called... | python | {
"resource": ""
} |
q37565 | DelayedCall.reset | train | def reset(self, secondsFromNow):
"""Reschedule this call for a different time
@type secondsFromNow: C{float}
@param secondsFromNow: The number of seconds from the time of the
C{reset} call at which this call will be scheduled.
@raise AlreadyCancelled: Raised if this call has be... | python | {
"resource": ""
} |
q37566 | DelayedCall.delay | train | def delay(self, secondsLater):
"""Reschedule this call for a later time
@type secondsLater: C{float}
@param secondsLater: The number of seconds after the originally
scheduled time for which to reschedule this call.
@raise AlreadyCancelled: Raised if this call has been cancelled... | python | {
"resource": ""
} |
q37567 | main | train | def main():
"""
Start the AMP server and the reactor.
"""
startLogging(stdout)
checker = InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("testuser", "examplepass")
realm = AdditionRealm()
factory = CredAMPServerFactory(Portal(realm, [checker]))
reactor.listenTCP(7805, facto... | python | {
"resource": ""
} |
q37568 | LandingPageDetailView.set_meta | train | def set_meta(self, instance):
"""
Set django-meta stuff from LandingPageModel instance.
"""
self.use_title_tag = True
self.title = instance.title | python | {
"resource": ""
} |
q37569 | FieldPerm.check | train | def check(self, field):
'''
Returns permissions determined by object itself
'''
if self.permissions is None:
return field.parent.permissions
return self.permissions | python | {
"resource": ""
} |
q37570 | View._load_view | train | def _load_view(self, template_engine_name, template_dir):
"""
Load view by name and return an instance.
"""
file_name = template_engine_name.lower()
class_name = "{}View".format(template_engine_name.title())
try:
view_module = import_module("rails.views.{}".fo... | python | {
"resource": ""
} |
q37571 | terminate | train | def terminate(pid, sig, timeout):
'''Terminates process with PID `pid` and returns True if process finished
during `timeout`. Current user must have permission to access process
information.'''
os.kill(pid, sig)
start = time.time()
while True:
try:
# This is requireed if it's... | python | {
"resource": ""
} |
q37572 | doublefork | train | def doublefork(pidfile, logfile, cwd, umask): # pragma: nocover
'''Daemonize current process.
After first fork we return to the shell and removing our self from
controling terminal via `setsid`.
After second fork we are not session leader any more and cant get
controlling terminal when opening files... | python | {
"resource": ""
} |
q37573 | Partitions.partition | train | def partition(self, id_):
"""Get a partition by the id number.
Arguments:
id_ -- a partition id value
Returns:
A partitions.Partition object
Throws:
a Sqlalchemy exception if the partition either does not exist or
is not unique
... | python | {
"resource": ""
} |
q37574 | Partitions._find_orm | train | def _find_orm(self, pnq):
"""Return a Partition object from the database based on a PartitionId.
An ORM object is returned, so changes can be persisted.
"""
# import sqlalchemy.orm.exc
from ambry.orm import Partition as OrmPartition # , Table
from sqlalchemy.orm import... | python | {
"resource": ""
} |
q37575 | Partitions.new_db_from_pandas | train | def new_db_from_pandas(self, frame, table=None, data=None, load=True, **kwargs):
"""Create a new db partition from a pandas data frame.
If the table does not exist, it will be created
"""
from ..orm import Column
# from dbexceptions import ConfigurationError
# Create ... | python | {
"resource": ""
} |
q37576 | update_project | train | def update_project(id, **kwargs):
"""
Update an existing Project with new information
"""
content = update_project_raw(id, **kwargs)
if content:
return utils.format_json(content) | python | {
"resource": ""
} |
q37577 | get_project | train | def get_project(id=None, name=None):
"""
Get a specific Project by ID or name
"""
content = get_project_raw(id, name)
if content:
return utils.format_json(content) | python | {
"resource": ""
} |
q37578 | delete_project | train | def delete_project(id=None, name=None):
"""
Delete a Project by ID or name.
"""
content = delete_project_raw(id, name)
if content:
return utils.format_json(content) | python | {
"resource": ""
} |
q37579 | list_projects | train | def list_projects(page_size=200, page_index=0, sort="", q=""):
"""
List all Projects
"""
content = list_projects_raw(page_size=page_size, page_index=page_index, sort=sort, q=q)
if content:
return utils.format_json_list(content) | python | {
"resource": ""
} |
q37580 | BaseSession.set_handler | train | def set_handler(self, handler):
""" Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin}
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler... | python | {
"resource": ""
} |
q37581 | BaseSession.delayed_close | train | def delayed_close(self):
""" Delayed close - won't close immediately, but on the next reactor
loop. """
self.state = SESSION_STATE.CLOSING
reactor.callLater(0, self.close) | python | {
"resource": ""
} |
q37582 | BaseSession.is_closed | train | def is_closed(self):
""" Check if session was closed. """
return (self.state == SESSION_STATE.CLOSED
or self.state == SESSION_STATE.CLOSING) | python | {
"resource": ""
} |
q37583 | SessionMixin._random_key | train | def _random_key(self):
""" Return random session key """
hashstr = '%s%s' % (random.random(), self.time_module.time())
return hashlib.md5(hashstr).hexdigest() | python | {
"resource": ""
} |
q37584 | SessionMixin.promote | train | def promote(self):
""" Mark object as alive, so it won't be collected during next
run of the garbage collector.
"""
if self.expiry is not None:
self.promoted = self.time_module.time() + self.expiry | python | {
"resource": ""
} |
q37585 | Session.close | train | def close(self, code=3000, message='Go away!'):
""" Close session.
@param code: Closing code
@param message: Closing message
"""
if self.state != SESSION_STATE.CLOSED:
# Notify handler
if self.handler is not None:
self.handler.send_pack(p... | python | {
"resource": ""
} |
q37586 | CensusStateGeoid.parser | train | def parser(cls, v):
"""Ensure that the upstream parser gets two digits. """
return geoid.census.State.parse(str(v).zfill(2)) | python | {
"resource": ""
} |
q37587 | ConfigReader.get_dependency_structure | train | def get_dependency_structure(self, artifact=None, include_dependencies=False):
"""
Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete
structure is returned.
:param artifact: an artifact task or artifact name if only an artifact's... | python | {
"resource": ""
} |
q37588 | transform_generator | train | def transform_generator(fn):
"""A decorator that marks transform pipes that should be called to create the real transform"""
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
fn.__dict__['is_transform_generator'] = True
return fn | python | {
"resource": ""
} |
q37589 | is_transform_generator | train | def is_transform_generator(fn):
"""Return true of the function has been marked with @transform_generator"""
try:
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
return fn.__dict__.get('is_transform_generator', False)
except AttributeE... | python | {
"resource": ""
} |
q37590 | nullify | train | def nullify(v):
"""Convert empty strings and strings with only spaces to None values. """
if isinstance(v, six.string_types):
v = v.strip()
if v is None or v == '':
return None
else:
return v | python | {
"resource": ""
} |
q37591 | parse_int | train | def parse_int(v, header_d):
"""Parse as an integer, or a subclass of Int."""
v = nullify(v)
if v is None:
return None
try:
# The converson to float allows converting float strings to ints.
# The conversion int('2.134') will fail.
return int(round(float(v), 0))
exce... | python | {
"resource": ""
} |
q37592 | _parse_text | train | def _parse_text(v, header_d):
""" Parses unicode.
Note:
unicode types for py2 and str types for py3.
"""
v = nullify(v)
if v is None:
return None
try:
return six.text_type(v).strip()
except Exception as e:
raise CastingError(six.text_type, header_d, v, st... | python | {
"resource": ""
} |
q37593 | _parse_binary | train | def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but it ocassionally converts numbers into strings
v = nullify(v)
if v is None:
return None
if six.PY2:
try:
return six.bi... | python | {
"resource": ""
} |
q37594 | parseJuiceHeaders | train | def parseJuiceHeaders(lines):
"""
Create a JuiceBox from a list of header lines.
@param lines: a list of lines.
"""
b = JuiceBox()
bodylen = 0
key = None
for L in lines:
if L[0] == ' ':
# continuation
assert key is not None
b[key] += '\r\n'+L[... | python | {
"resource": ""
} |
q37595 | DispatchMixin.lookupFunction | train | def lookupFunction(self, proto, name, namespace):
"""Return a callable to invoke when executing the named command.
"""
# Try to find a method to be invoked in a transaction first
# Otherwise fallback to a "regular" method
fName = self.autoDispatchPrefix + name
fObj = geta... | python | {
"resource": ""
} |
q37596 | Juice._switchTo | train | def _switchTo(self, newProto, clientFactory=None):
""" Switch this Juice instance to a new protocol. You need to do this
'simultaneously' on both ends of a connection; the easiest way to do
this is to use a subclass of ProtocolSwitchCommand.
"""
assert self.innerProtocol is Non... | python | {
"resource": ""
} |
q37597 | Juice.sendPacket | train | def sendPacket(self, completeBox):
"""
Send a juice.Box to my peer.
Note: transport.write is never called outside of this method.
"""
assert not self.__locked, "You cannot send juice packets when a connection is locked"
if self._startingTLSBuffer is not None:
... | python | {
"resource": ""
} |
q37598 | Plot.dataframe | train | def dataframe(self, filtered_dims={}, unstack=False, df_class=None, add_code=False):
"""
Yield rows in a reduced format, with one dimension as an index, one measure column per
secondary dimension, and all other dimensions filtered.
:param measure: The column names of one or more measur... | python | {
"resource": ""
} |
q37599 | DatasetSQLiteIndex._index_document | train | def _index_document(self, document, force=False):
""" Adds document to the index. """
query = text("""
INSERT INTO dataset_index(vid, title, keywords, doc)
VALUES(:vid, :title, :keywords, :doc);
""")
self.backend.library.database.connection.execute(query, **docume... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.