_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q38800 | SiteRootMixin.locateChild | train | def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined by a site root
plugin or an avatar from guard.
"""
request = IRequest(context)
webViewer = IWebViewer(self.store, None)
childAndSegments = self.siteProduceResource(r... | python | {
"resource": ""
} |
q38801 | SiteRootMixin.siteProduceResource | train | def siteProduceResource(self, req, segments, webViewer):
"""
Retrieve a child resource and segments from rootChild_ methods on this
object and SiteRootPlugins.
@return: a 2-tuple of (resource, segments), suitable for return from
locateChild.
@param req: an L{IRequest} p... | python | {
"resource": ""
} |
q38802 | VirtualHostWrapper.subdomain | train | def subdomain(self, hostname):
"""
Determine of which known domain the given hostname is a subdomain.
@return: A two-tuple giving the subdomain part and the domain part or
C{None} if the domain is not a subdomain of any known domain.
"""
hostname = hostname.split(":"... | python | {
"resource": ""
} |
q38803 | _webTranslator | train | def _webTranslator(store, fallback):
"""
Discover a web translator based on an Axiom store and a specified default.
Prefer the specified default.
This is an implementation detail of various initializers in this module
which require an L{IWebTranslator} provider. Some of those initializers
did ... | python | {
"resource": ""
} |
q38804 | _ScrollableBase.resort | train | def resort(self, columnName):
"""
Re-sort the table.
@param columnName: the name of the column to sort by. This is a string
because it is passed from the browser.
"""
csc = self.currentSortColumn
newSortColumn = self.columns[columnName]
if newSortColumn ... | python | {
"resource": ""
} |
q38805 | InequalityModel.inequalityQuery | train | def inequalityQuery(self, constraint, count, isAscending):
"""
Perform a query to obtain some rows from the table represented
by this model, at the behest of a networked client.
@param constraint: an additional constraint to apply to the
query.
@type constraint: L{axiom.... | python | {
"resource": ""
} |
q38806 | InequalityModel.rowsAfterValue | train | def rowsAfterValue(self, value, count):
"""
Retrieve some rows at or after a given sort-column value.
@param value: Starting value in the index for the current sort column
at which to start returning results. Rows with a column value for the
current sort column which is greater... | python | {
"resource": ""
} |
q38807 | InequalityModel.rowsBeforeValue | train | def rowsBeforeValue(self, value, count):
"""
Retrieve display data for rows with sort-column values less than the
given value.
@type value: Some type compatible with the current sort column.
@param value: Starting value in the index for the current sort column
at which t... | python | {
"resource": ""
} |
q38808 | InequalityModel.rowsBeforeItem | train | def rowsBeforeItem(self, item, count):
"""
The inverse of rowsAfterItem.
@param item: then L{Item} to request rows before.
@type item: this L{InequalityModel}'s L{itemType} attribute.
@param count: The maximum number of rows to return.
@type count: L{int}
@retu... | python | {
"resource": ""
} |
q38809 | IndexingModel.requestRowRange | train | def requestRowRange(self, rangeBegin, rangeEnd):
"""
Retrieve display data for the given range of rows.
@type rangeBegin: C{int}
@param rangeBegin: The index of the first row to retrieve.
@type rangeEnd: C{int}
@param rangeEnd: The index of the last row to retrieve.
... | python | {
"resource": ""
} |
q38810 | IndexingModel.getTableMetadata | train | def getTableMetadata(self):
"""
Retrieve a description of the various properties of this scrolltable.
@return: A sequence containing 5 elements. They are, in order, a
list of the names of the columns present, a mapping of column names
to two-tuples of their type and a boolean i... | python | {
"resource": ""
} |
q38811 | ScrollableView.constructRows | train | def constructRows(self, items):
"""
Build row objects that are serializable using Athena for sending to the
client.
@param items: an iterable of objects compatible with my columns'
C{extractValue} methods.
@return: a list of dictionaries, where each dictionary has a str... | python | {
"resource": ""
} |
q38812 | ScrollingElement.getInitialArguments | train | def getInitialArguments(self):
"""
Return the constructor arguments required for the JavaScript client class,
Mantissa.ScrollTable.ScrollTable.
@return: a 3-tuple of::
- The unicode attribute ID of my current sort column
- A list of dictionaries with 'name' and 'typ... | python | {
"resource": ""
} |
q38813 | printChannelColRow | train | def printChannelColRow(campaign, ra, dec):
"""Prints the channel, col, row for a given campaign and coordinate."""
fovobj = fields.getKeplerFov(campaign)
ch, col, row = fovobj.getChannelColRow(ra, dec)
print("Position in C{}: channel {}, col {:.0f}, row {:.0f}.".format(campaign, int(ch), col, row)) | python | {
"resource": ""
} |
q38814 | findCampaigns | train | def findCampaigns(ra, dec):
"""Returns a list of the campaigns that cover a given position.
Parameters
----------
ra, dec : float, float
Position in decimal degrees (J2000).
Returns
-------
campaigns : list of int
A list of the campaigns that cover the given position.
"... | python | {
"resource": ""
} |
q38815 | findCampaignsByName | train | def findCampaignsByName(target):
"""Returns a list of the campaigns that cover a given target.
Parameters
----------
target : str
Name of the celestial object.
Returns
-------
campaigns : list of int
A list of the campaigns that cover the given target name.
ra, dec : f... | python | {
"resource": ""
} |
q38816 | K2findCampaigns_csv_main | train | def K2findCampaigns_csv_main(args=None):
"""Exposes K2findCampaigns-csv to the command line."""
parser = argparse.ArgumentParser(
description="Check which objects listed in a CSV table "
"are (or were) observable by NASA's K2 mission.")
parser.add_argument... | python | {
"resource": ""
} |
q38817 | mock_import | train | def mock_import(do_not_mock=None, **mock_kwargs):
"""
Mocks import statements by ignoring ImportErrors
and replacing the missing module with a Mock.
:param str|unicode|list[str|unicode] do_not_mock: names of modules
that should exists, and an ImportError could be raised for.
:param mock_kwa... | python | {
"resource": ""
} |
q38818 | doapi.request | train | def request(self, url, params=None, data=None, method='GET'):
"""
Perform an HTTP request and return the response body as a decoded JSON
value
:param str url: the URL to make the request of. If ``url`` begins with
a forward slash, :attr:`endpoint` is prepended to it; otherw... | python | {
"resource": ""
} |
q38819 | doapi.paginate | train | def paginate(self, url, key, params=None):
"""
Fetch a sequence of paginated resources from the API endpoint. The
initial request to ``url`` and all subsequent requests must respond
with a JSON object; the field specified by ``key`` must be a list,
whose elements will be yielded... | python | {
"resource": ""
} |
q38820 | doapi.fetch_all_droplets | train | def fetch_all_droplets(self, tag_name=None):
r"""
Returns a generator that yields all of the droplets belonging to the
account
.. versionchanged:: 0.2.0
``tag_name`` parameter added
:param tag_name: if non-`None`, only droplets with the given tag are
ret... | python | {
"resource": ""
} |
q38821 | doapi.create_droplet | train | def create_droplet(self, name, image, size, region, ssh_keys=None,
backups=None, ipv6=None, private_networking=None,
user_data=None, **kwargs):
"""
Create a new droplet. All fields other than ``name``, ``image``,
``size``, and ``region`` are optiona... | python | {
"resource": ""
} |
q38822 | doapi.create_multiple_droplets | train | def create_multiple_droplets(self, names, image, size, region,
ssh_keys=None, backups=None, ipv6=None,
private_networking=None, user_data=None,
**kwargs):
r"""
Create multiple new droplets at once with the... | python | {
"resource": ""
} |
q38823 | doapi.fetch_all_droplet_neighbors | train | def fetch_all_droplet_neighbors(self):
r"""
Returns a generator of all sets of multiple droplets that are running
on the same physical hardware
:rtype: generator of lists of `Droplet`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
for hood i... | python | {
"resource": ""
} |
q38824 | doapi.wait_actions | train | def wait_actions(self, actions, wait_interval=None, wait_time=None):
r"""
Poll the server periodically until all actions in ``actions`` have
either completed or errored out, yielding each `Action`'s final value
as it ends.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (cont... | python | {
"resource": ""
} |
q38825 | doapi.create_ssh_key | train | def create_ssh_key(self, name, public_key, **kwargs):
"""
Add a new SSH public key resource to the account
:param str name: the name to give the new SSH key resource
:param str public_key: the text of the public key to register, in the
form used by :file:`authorized_keys` fi... | python | {
"resource": ""
} |
q38826 | doapi.fetch_all_images | train | def fetch_all_images(self, type=None, private=None):
# pylint: disable=redefined-builtin
r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); ... | python | {
"resource": ""
} |
q38827 | doapi.create_domain | train | def create_domain(self, name, ip_address, **kwargs):
"""
Add a new domain name resource to the account.
Note that this method does not actually register a new domain name; it
merely configures DigitalOcean's nameservers to provide DNS resolution
for the domain. See `How To Set ... | python | {
"resource": ""
} |
q38828 | doapi.create_floating_ip | train | def create_floating_ip(self, droplet_id=None, region=None, **kwargs):
"""
Create a new floating IP assigned to a droplet or reserved to a region.
Either ``droplet_id`` or ``region`` must be specified, but not both.
The returned `FloatingIP` object will represent the IP at the moment of
... | python | {
"resource": ""
} |
q38829 | doapi._wait | train | def _wait(self, objects, attr, value, wait_interval=None, wait_time=None):
r"""
Calls the ``fetch`` method of each object in ``objects`` periodically
until the ``attr`` attribute of each one equals ``value``, yielding the
final state of each object as soon as it satisfies the condition.
... | python | {
"resource": ""
} |
q38830 | min_tasks_per_node | train | def min_tasks_per_node(queue_id):
"""
This function is used when requesting non exclusive use
as the parallel environment might enforce a minimum number
of tasks
"""
parallel_env = queue_id.split(':')[0]
queue_name = queue_id.split(':')[1]
tasks = 1
pe_tasks = tasks
with os.popen... | python | {
"resource": ""
} |
q38831 | check_shape | train | def check_shape(meth):
"""
Decorator for larray magic methods, to ensure that the operand has
the same shape as the array.
"""
@wraps(meth)
def wrapped_meth(self, val):
if isinstance(val, (larray, numpy.ndarray)):
if val.shape != self._shape:
raise ValueError(... | python | {
"resource": ""
} |
q38832 | partial_shape | train | def partial_shape(addr, full_shape):
"""
Calculate the size of the sub-array represented by `addr`
"""
def size(x, max):
if isinstance(x, (int, long, numpy.integer)):
return None
elif isinstance(x, slice):
y = min(max, x.stop or max) # slice limits can go past th... | python | {
"resource": ""
} |
q38833 | _build_ufunc | train | def _build_ufunc(func):
"""Return a ufunc that works with lazy arrays"""
def larray_compatible_ufunc(x):
if isinstance(x, larray):
y = deepcopy(x)
y.apply(func)
return y
else:
return func(x)
return larray_compatible_ufunc | python | {
"resource": ""
} |
q38834 | larray.is_homogeneous | train | def is_homogeneous(self):
"""True if all the elements of the array are the same."""
hom_base = isinstance(self.base_value, (int, long, numpy.integer, float, bool)) \
or type(self.base_value) == self.dtype \
or (isinstance(self.dtype, type) and isinstance(self.base_v... | python | {
"resource": ""
} |
q38835 | larray._partially_evaluate | train | def _partially_evaluate(self, addr, simplify=False):
"""
Return part of the lazy array.
"""
if self.is_homogeneous:
if simplify:
base_val = self.base_value
else:
base_val = self._homogeneous_array(addr) * self.base_value
eli... | python | {
"resource": ""
} |
q38836 | larray.check_bounds | train | def check_bounds(self, addr):
"""
Check whether the given address is within the array bounds.
"""
def is_boolean_array(arr):
return hasattr(arr, 'dtype') and arr.dtype == bool
def check_axis(x, size):
if isinstance(x, (int, long, numpy.integer)):
... | python | {
"resource": ""
} |
q38837 | larray.evaluate | train | def evaluate(self, simplify=False, empty_val=0):
"""
Return the lazy array as a real NumPy array.
If the array is homogeneous and ``simplify`` is ``True``, return a
single numerical value.
"""
# need to catch the situation where a generator-based larray is evaluated a se... | python | {
"resource": ""
} |
q38838 | is_closest_date_parameter | train | def is_closest_date_parameter(task, param_name):
""" Return the parameter class of param_name on task. """
for name, obj in task.get_params():
if name == param_name:
return hasattr(obj, 'use_closest_date')
return False | python | {
"resource": ""
} |
q38839 | delistify | train | def delistify(x):
""" A basic slug version of a given parameter list. """
if isinstance(x, list):
x = [e.replace("'", "") for e in x]
return '-'.join(sorted(x))
return x | python | {
"resource": ""
} |
q38840 | BaseTask.effective_task_id | train | def effective_task_id(self):
""" Replace date in task id with closest date. """
params = self.param_kwargs
if 'date' in params and is_closest_date_parameter(self, 'date'):
params['date'] = self.closest()
task_id_parts = sorted(['%s=%s' % (k, str(v)) for k, v in params.ite... | python | {
"resource": ""
} |
q38841 | BaseTask.taskdir | train | def taskdir(self):
""" Return the directory under which all artefacts are stored. """
return os.path.join(self.BASE, self.TAG, self.task_family) | python | {
"resource": ""
} |
q38842 | MockTask.run | train | def run(self):
""" Just copy the fixture, so we have some output. """
luigi.LocalTarget(path=self.fixture).copy(self.output().path) | python | {
"resource": ""
} |
q38843 | Dispatcher.get_listeners | train | def get_listeners(self, name):
"""
Return the callables related to name
"""
return list(map(lambda listener: listener[0], self.listeners[name])) | python | {
"resource": ""
} |
q38844 | Dispatcher.add_listener | train | def add_listener(self, name, listener, priority=0):
"""
Add a new listener to the dispatch
"""
if name not in self.listeners:
self.listeners[name] = []
self.listeners[name].append((listener, priority))
# reorder event
self.listeners[name].sort(key=la... | python | {
"resource": ""
} |
q38845 | dump_etree | train | def dump_etree(data, container=None, nsmap=None, attribs=None):
"""Convert dictionary to Simple Dublin Core XML as ElementTree.
:param data: Dictionary.
:param container: Name (include namespace) of container element.
:param nsmap: Namespace mapping for lxml.
:param attribs: Default attributes for ... | python | {
"resource": ""
} |
q38846 | rule_factory | train | def rule_factory(plural, singular):
"""Element rule factory."""
@rules.rule(plural)
def f(path, values):
for v in values:
if v:
elem = etree.Element(
'{{http://purl.org/dc/elements/1.1/}}{0}'.format(singular))
elem.text = v
... | python | {
"resource": ""
} |
q38847 | RemoteStatsCollector.startReceivingBoxes | train | def startReceivingBoxes(self, sender):
"""
Start observing log events for stat events to send.
"""
AMP.startReceivingBoxes(self, sender)
log.addObserver(self._emit) | python | {
"resource": ""
} |
q38848 | RemoteStatsCollector.stopReceivingBoxes | train | def stopReceivingBoxes(self, reason):
"""
Stop observing log events.
"""
AMP.stopReceivingBoxes(self, reason)
log.removeObserver(self._emit) | python | {
"resource": ""
} |
q38849 | normalize_filename | train | def normalize_filename(filename):
"""
Remove special characters and shorten if name is too long
"""
# if the url pointed to a directory then just replace all the special chars
filename = re.sub("/|\\|;|:|\?|=", "_", filename)
if len(filename) > 150:
prefix = hashlib.md5(filename).hexdig... | python | {
"resource": ""
} |
q38850 | build_local_filename | train | def build_local_filename(download_url=None, filename=None, decompress=False):
"""
Determine which local filename to use based on the file's source URL,
an optional desired filename, and whether a compression suffix needs
to be removed
"""
assert download_url or filename, "Either filename or URL ... | python | {
"resource": ""
} |
q38851 | compare | train | def compare(file1, file2):
"""compares the contents of two files, passed in either as
open file handles or accessible file paths. Does a simple
naive string comparison, so do not use on larger files"""
if isinstance(file1, six.string_types): # pragma: no branch
file1 = open(file1, 'r', Tr... | python | {
"resource": ""
} |
q38852 | sha1sum | train | def sha1sum(f):
"""Return the SHA-1 hash of the contents of file `f`, in hex format"""
h = hashlib.sha1()
fp = open(f, 'rb')
while True:
block = fp.read(512 * 1024)
if not block:
break
h.update(block)
return h.hexdigest() | python | {
"resource": ""
} |
q38853 | safe_copyfile | train | def safe_copyfile(src, dest):
"""safely copy src to dest using a temporary intermediate and then renaming
to dest"""
fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(dest))
shutil.copyfileobj(open(src, 'rb'), os.fdopen(fd, 'wb'))
shutil.copystat(src, tmpname)
os.rename(tmpname, dest) | python | {
"resource": ""
} |
q38854 | sphericalAngSep | train | def sphericalAngSep(ra0, dec0, ra1, dec1, radians=False):
"""
Compute the spherical angular separation between two
points on the sky.
//Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html
NB: For small distances you can probably use
sqrt( dDec**2 + cos^2(dec)*... | python | {
"resource": ""
} |
q38855 | haversine | train | def haversine(x):
"""Return the haversine of an angle
haversine(x) = sin(x/2)**2, where x is an angle in radians
"""
y = .5*x
y = np.sin(y)
return y*y | python | {
"resource": ""
} |
q38856 | linkTo | train | def linkTo(sharedProxyOrItem):
"""
Generate the path part of a URL to link to a share item or its proxy.
@param sharedProxy: a L{sharing.SharedProxy} or L{sharing.Share}
@return: a URL object, which when converted to a string will look
something like '/users/user@host/shareID'.
@rtype: L{... | python | {
"resource": ""
} |
q38857 | _ShareURL.child | train | def child(self, path):
"""
Override the base implementation to inject the share ID our
constructor was passed.
"""
if self._shareID is not None:
self = url.URL.child(self, self._shareID)
self._shareID = None
return url.URL.child(self, path) | python | {
"resource": ""
} |
q38858 | _ShareURL.cloneURL | train | def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment):
"""
Override the base implementation to pass along the share ID our
constructor was passed.
"""
return self.__class__(
self._shareID, scheme, netloc, pathsegs, querysegs, fragment) | python | {
"resource": ""
} |
q38859 | _set_autocommit | train | def _set_autocommit(connection):
"""Make sure a connection is in autocommit mode."""
if hasattr(connection.connection, "autocommit"):
if callable(connection.connection.autocommit):
connection.connection.autocommit(True)
else:
connection.connection.... | python | {
"resource": ""
} |
q38860 | _patch_static_handler | train | def _patch_static_handler(handler):
"""Patch in support for static files serving if supported and enabled.
"""
if django.VERSION[:2] < (1, 3):
return
from django.contrib.staticfiles.handlers import StaticFilesHandler
return StaticFilesHandler(handler) | python | {
"resource": ""
} |
q38861 | SeleniumPlugin._inject_selenium | train | def _inject_selenium(self, test):
"""
Injects a selenium instance into the method.
"""
from django.conf import settings
test_case = get_test_case_class(test)
test_case.selenium_plugin_started = True
# Provide some reasonable default values
sel = selenium... | python | {
"resource": ""
} |
q38862 | StoppableWSGIServer.server_bind | train | def server_bind(self):
"""Bind server to socket. Overrided to store server name and
set timeout.
"""
try:
HTTPServer.server_bind(self)
except Exception as e:
raise WSGIServerException(e)
self.setup_environ()
self.socket.settimeout(1) | python | {
"resource": ""
} |
q38863 | AsyncMethodCall.result | train | def result(self, wait=False):
"""
Gets the result of the method call. If the call was successful,
return the result, otherwise, reraise the exception.
:param wait: Block until the result is available, or just get the result.
:raises: RuntimeError when called and the result is no... | python | {
"resource": ""
} |
q38864 | Extension.post_build | train | def post_build(self, container_builder, container):
"""
This method make sure the flask configuration is fine, and
check the if ioc.extra.jinja2 service is available. If so, the
flask instance will use this service, by keeping the flask template
loader and the one registered a... | python | {
"resource": ""
} |
q38865 | Mongrel2Handler.start | train | def start(self):
"""
Start to listen for incoming requests.
"""
assert not self._started
self._listening_stream.on_recv(self._recv_callback)
self._started = True | python | {
"resource": ""
} |
q38866 | Mongrel2Handler._create_listening_stream | train | def _create_listening_stream(self, pull_addr):
"""
Create a stream listening for Requests. The `self._recv_callback`
method is asociated with incoming requests.
"""
sock = self._zmq_context.socket(zmq.PULL)
sock.connect(pull_addr)
stream = ZMQStream(sock, io_loop=... | python | {
"resource": ""
} |
q38867 | Mongrel2Handler._create_sending_stream | train | def _create_sending_stream(self, pub_addr):
"""
Create a `ZMQStream` for sending responses back to Mongrel2.
"""
sock = self._zmq_context.socket(zmq.PUB)
sock.setsockopt(zmq.IDENTITY, self.sender_id)
sock.connect(pub_addr)
stream = ZMQStream(sock, io_loop=self.io_... | python | {
"resource": ""
} |
q38868 | Mongrel2Handler._recv_callback | train | def _recv_callback(self, msg):
"""
Method is called when there is a message coming from a Mongrel2 server.
This message should be a valid Request String.
"""
m2req = MongrelRequest.parse(msg[0])
MongrelConnection(m2req, self._sending_stream, self.request_callback,
... | python | {
"resource": ""
} |
q38869 | MongrelConnection._begin_request | train | def _begin_request(self):
"""
Actually start executing this request.
"""
headers = self.m2req.headers
self._request = HTTPRequest(connection=self,
method=headers.get("METHOD"),
uri=self.m2req.path,
version=headers.get("VERSION"),
h... | python | {
"resource": ""
} |
q38870 | MongrelConnection.finish | train | def finish(self):
"""
Finish this connection.
"""
assert self._request, "Request closed"
self._request_finished = True
if self.m2req.should_close() or self.no_keep_alive:
self._send("")
self._request = None | python | {
"resource": ""
} |
q38871 | MongrelConnection._send | train | def _send(self, msg):
"""
Raw send to the given connection ID at the given uuid, mostly used
internally.
"""
uuid = self.m2req.sender
conn_id = self.m2req.conn_id
header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id))
zmq_message = header + ' ' +... | python | {
"resource": ""
} |
q38872 | as_completed | train | def as_completed(*async_result_wrappers):
"""
Yields results as they become available from asynchronous method calls.
Example usage
::
async_calls = [service.call_method_async("do_stuff", (x,)) for x in range(25)]
for async_call in gemstone.as_completed(*async_calls):
pri... | python | {
"resource": ""
} |
q38873 | dynamic_load | train | def dynamic_load(module_or_member):
"""
Dynamically loads a class or member of a class.
If ``module_or_member`` is something like ``"a.b.c"``, will perform ``from a.b import c``.
If ``module_or_member`` is something like ``"a"`` will perform ``import a``
:param module_or_member: the name of a mod... | python | {
"resource": ""
} |
q38874 | BooleanField.encode | train | def encode(cls, value):
"""
convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes
"""
if value not in [True, False]:
raise InvalidValue('not a boolean')
... | python | {
"resource": ""
} |
q38875 | FloatField.encode | train | def encode(cls, value):
"""
encode a floating point number to bytes in redis
:param value: float
:return: bytes
"""
try:
if float(value) + 0 == value:
return repr(value)
except (TypeError, ValueError):
pass
raise I... | python | {
"resource": ""
} |
q38876 | IntegerField.encode | train | def encode(cls, value):
"""
take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str
"""
try:
coerced = int(value)
if coerced + 0 == value:
return repr(coerced)
e... | python | {
"resource": ""
} |
q38877 | TextField.encode | train | def encode(cls, value):
"""
take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes
"""
coerced = unicode(value)
if coerced == value:
return coerced.encode(cls._encoding)
raise InvalidValue('not text... | python | {
"resource": ""
} |
q38878 | AsciiField.encode | train | def encode(cls, value):
"""
take a list of strings and turn it into utf-8 byte-string
:param value:
:return:
"""
coerced = unicode(value)
if coerced == value and cls.PATTERN.match(coerced):
return coerced.encode(cls._encoding)
raise InvalidVa... | python | {
"resource": ""
} |
q38879 | BinaryField.encode | train | def encode(cls, value):
"""
write binary data into redis without encoding it.
:param value: bytes
:return: bytes
"""
try:
coerced = bytes(value)
if coerced == value:
return coerced
except (TypeError, UnicodeError):
... | python | {
"resource": ""
} |
q38880 | ListField.encode | train | def encode(cls, value):
"""
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
"""
try:
coerced = list(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
... | python | {
"resource": ""
} |
q38881 | ListField.decode | train | def decode(cls, value):
"""
take a utf-8 encoded byte-string from redis and
turn it back into a list
:param value: bytes
:return: list
"""
try:
return None if value is None else \
list(json.loads(value.decode(cls._encoding)))
e... | python | {
"resource": ""
} |
q38882 | DictField.encode | train | def encode(cls, value):
"""
encode the dict as a json string to be written into redis.
:param value: dict
:return: bytes
"""
try:
coerced = dict(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
e... | python | {
"resource": ""
} |
q38883 | StringListField.encode | train | def encode(cls, value):
"""
the list it so it can be stored in redis.
:param value: list
:return: bytes
"""
try:
coerced = [str(v) for v in value]
if coerced == value:
return ",".join(coerced).encode(cls._encoding) if len(
... | python | {
"resource": ""
} |
q38884 | swap_twitter_subject | train | def swap_twitter_subject(subject, body):
"""If subject starts from 'Tweet from...'
then we need to get first meaning line from the body."""
if subject.startswith('Tweet from'):
lines = body.split('\n')
for idx, line in enumerate(lines):
if re.match(r'.*, ?\d{2}:\d{2}]]', line) i... | python | {
"resource": ""
} |
q38885 | trial | train | def trial(log_dir=None,
upload_dir=None,
sync_period=None,
trial_prefix="",
param_map=None,
init_logging=True):
"""
Generates a trial within a with context.
"""
global _trial # pylint: disable=global-statement
if _trial:
# TODO: would be nic... | python | {
"resource": ""
} |
q38886 | index | train | def index(index, length):
"""Generates an index.
:param index: The index, can be positive or negative.
:param length: The length of the sequence to index.
:raises: IndexError
Negative indices are typically used to index a sequence in reverse order.
But to use them, the indexed object must con... | python | {
"resource": ""
} |
q38887 | range_to_numeric | train | def range_to_numeric(ranges):
"""Converts a sequence of string ranges to a sequence of floats.
E.g.::
>>> range_to_numeric(['1 uV', '2 mV', '1 V'])
[1E-6, 0.002, 1.0]
"""
values, units = zip(*(r.split() for r in ranges))
# Detect common unit.
unit = os.path.commonprefix([u[::-... | python | {
"resource": ""
} |
q38888 | AutoRange.range | train | def range(self, value):
"""Estimates an appropriate sensitivity range."""
self._buffer.append(abs(value))
mean = sum(self._buffer) / len(self._buffer)
estimate = next(
(r for r in self.ranges if mean < self.scale * r),
self.ranges[-1]
)
if self._ma... | python | {
"resource": ""
} |
q38889 | Context.add | train | def add(self, schema, data):
""" Stage ``data`` as a set of statements, based on the given
``schema`` definition. """
binding = self.get_binding(schema, data)
uri, triples = triplify(binding)
for triple in triples:
self.graph.add(triple)
return uri | python | {
"resource": ""
} |
q38890 | Context.save | train | def save(self):
""" Transfer the statements in this context over to the main store. """
if self.parent.buffered:
query = """
INSERT DATA { GRAPH %s { %s } }
"""
query = query % (self.identifier.n3(),
self.graph.serialize(fo... | python | {
"resource": ""
} |
q38891 | Context.delete | train | def delete(self):
""" Delete all statements matching the current context identifier
from the main store. """
if self.parent.buffered:
query = 'CLEAR SILENT GRAPH %s ;' % self.identifier.n3()
self.parent.graph.update(query)
self.flush()
else:
... | python | {
"resource": ""
} |
q38892 | Transport.read_bytes | train | def read_bytes(self, num_bytes):
"""Reads at most `num_bytes`."""
buffer_size = len(self._buffer)
if buffer_size > num_bytes:
# The buffer is larger than the requested amount of bytes.
data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:]
elif 0 ... | python | {
"resource": ""
} |
q38893 | Transport.read_until | train | def read_until(self, delimiter):
"""Reads until the delimiter is found."""
if delimiter in self._buffer:
data, delimiter, self._buffer = self._buffer.partition(delimiter)
return data
else:
self._buffer += self.__read__(self._max_bytes)
return self.... | python | {
"resource": ""
} |
q38894 | LinuxGpib.close | train | def close(self):
"""Closes the gpib transport."""
if self._device is not None:
ibsta = self._lib.ibonl(self._device, 0)
self._check_status(ibsta)
self._device = None | python | {
"resource": ""
} |
q38895 | LinuxGpib.trigger | train | def trigger(self):
"""Triggers the device.
The trigger method sens a GET(group execute trigger) command byte to
the device.
"""
ibsta = self._lib.ibtrg(self._device)
self._check_status(ibsta) | python | {
"resource": ""
} |
q38896 | LinuxGpib._check_status | train | def _check_status(self, ibsta):
"""Checks ibsta value."""
if ibsta & 0x4000:
raise LinuxGpib.Timeout()
elif ibsta & 0x8000:
raise LinuxGpib.Error(self.error_status) | python | {
"resource": ""
} |
q38897 | DownloadPage.run | train | def run(self):
""" Just run wget quietly. """
output = shellout('wget -q "{url}" -O {output}', url=self.url)
luigi.LocalTarget(output).move(self.output().path) | python | {
"resource": ""
} |
q38898 | DownloadPage.output | train | def output(self):
""" Use the digest version, since URL can be ugly. """
return luigi.LocalTarget(path=self.path(digest=True, ext='html')) | python | {
"resource": ""
} |
q38899 | JsonPage.run | train | def run(self):
""" Construct the document id from the date and the url. """
document = {}
document['_id'] = hashlib.sha1('%s:%s' % (
self.date, self.url)).hexdigest()
with self.input().open() as handle:
document['content'] = handle.read(... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.