Search is not available for this dataset
text stringlengths 75 104k |
|---|
def post(self, action, data=None, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='POST', data=data,
headers=headers) |
def delete(self, action, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='DELETE',
headers=headers) |
def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
"""
Calculates a good piece size for a size
"""
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size): # 20 = 1MB
if size / (2**i) < max_piece_count:
... |
def split_pieces(piece_list, segments, num):
"""
Prepare a list of all pieces grouped together
"""
piece_groups = []
pieces = list(piece_list)
while pieces:
for i in range(segments):
p = pieces[i::segments][:num]
if not p:
break
piece_g... |
def rglob(dirname, pattern, dirs=False, sort=True):
"""recursive glob, gets all files that match the pattern within the directory tree"""
fns = []
path = str(dirname)
if os.path.isdir(path):
fns = glob(os.path.join(escape(path), pattern))
dns = [fn for fn
in [os.p... |
def after(parents, func=None):
'''Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
... |
def wait_any(futures, timeout=None):
'''Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One o... |
def wait_all(futures, timeout=None):
'''Wait for the completion of all futures in a list
:param list future: a list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, can block indefinitely.
:type timeout: float or None
:raises WaitTimeout: if a timeout is provid... |
def value(self):
'''The final value, if it has arrived
:raises: AttributeError, if not yet complete
:raises: an exception if the Future was :meth:`abort`\ed
'''
if not self._done.is_set():
raise AttributeError("value")
if self._failure:
raise self... |
def finish(self, value):
'''Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete
'''
if self._done.is_set():
... |
def abort(self, klass, exc, tb=None):
'''Finish this future (maybe early) in an error state
Takes a standard exception triple as arguments (like returned by
``sys.exc_info``) and will re-raise them as the value.
Any :class:`Dependents` that are children of this one will also be
... |
def on_finish(self, func):
'''Assign a callback function to be run when successfully complete
:param function func:
A callback to run when complete. It will be given one argument (the
value that has arrived), and it's return value is ignored.
'''
if self._done.is... |
def on_abort(self, func):
'''Assign a callback function to be run when :meth:`abort`\ed
:param function func:
A callback to run when aborted. It will be given three arguments:
- ``klass``: the exception class
- ``exc``: the exception instance
... |
def after(self, func=None, other_parents=None):
'''Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in whic... |
def partial_results(self):
'''The results that the RPC has received *so far*
This may also be the complete results if :attr:`complete` is ``True``.
'''
results = []
for r in self._results:
if isinstance(r, Exception):
results.append(type(r)(*deepcopy(... |
def os_path_transform(self, s, sep=os.path.sep):
""" transforms any os path into unix style """
if sep == '/':
return s
else:
return s.replace(sep, '/') |
def transform(self, tr_list, files):
"""
replaces $tokens$ with values
will be replaced with config rendering
"""
singular = False
if not isinstance(files, list) and not isinstance(files, tuple):
singular = True
files = [files]
for _find, ... |
def resolve_dst(self, dst_dir, src):
"""
finds the destination based on source
if source is an absolute path, and there's no pattern, it copies the file to base dst_dir
"""
if os.path.isabs(src):
return os.path.join(dst_dir, os.path.basename(src))
return os.pa... |
def write(self, fn=None):
"""copy the zip file from its filename to the given filename."""
fn = fn or self.fn
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
f = open(self.fn, 'rb')
b = f.read()
f.close()
f = open(fn, 'wb')... |
def assign(self, attrs):
"""Merge new attributes
"""
for k, v in attrs.items():
setattr(self, k, v) |
def normalize_rust_function(self, function, line):
"""Normalizes a single rust frame with a function"""
# Drop the prefix and return type if there is any
function = drop_prefix_and_return_type(function)
# Collapse types
function = collapse(
function,
open... |
def normalize_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function"""
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len... |
def normalize_frame(
self,
module=None,
function=None,
file=None,
line=None,
module_offset=None,
offset=None,
normalized=None,
**kwargs # eat any extra kwargs passed in
):
"""Normalizes a single frame
Returns a structured cong... |
def _do_generate(self, source_list, hang_type, crashed_thread, delimiter=' | '):
"""
each element of signatureList names a frame in the crash stack; and is:
- a prefix of a relevant frame: Append this element to the signature
- a relevant frame: Append this element and stop looking
... |
def _clean_tag(t):
"""Fix up some garbage errors."""
# TODO: when score present, include info.
t = _scored_patt.sub(string=t, repl='')
if t == '_country_' or t.startswith('_country:'):
t = 'nnp_country'
elif t == 'vpb':
t = 'vb' # "carjack" is listed with vpb tag.
elif t == 'nnd... |
def local_settings(settings, prefix):
"""Localizes the settings for the dotted prefix.
For example, if the prefix where 'xyz'::
{'xyz.foo': 'bar', 'other': 'something'}
Would become::
{'foo': 'bar'}
Note, that non-prefixed items are left out and the prefix is dropped.
"""
pre... |
def humanize_bytes(bytes, precision=1):
"""Return a humanized string representation of a number of bytes.
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
'1 byte'
>>> humanize_bytes(1024)
'1.0 kB'
>>> humanize_bytes(1024*123)
'123.0 kB'
>>> humanize_bytes(1024*1234... |
def parent(self):
"""return the parent URL, with params, query, and fragment in place"""
path = '/'.join(self.path.split('/')[:-1])
s = path.strip('/').split(':')
if len(s)==2 and s[1]=='':
return None
else:
return self.__class__(self, path=path) |
def join(C, *args, **kwargs):
"""join a list of url elements, and include any keyword arguments, as a new URL"""
u = C('/'.join([str(arg).strip('/') for arg in args]), **kwargs)
return u |
def select_peer(peer_addrs, service, routing_id, method):
'''Choose a target from the available peers for a singular message
:param peer_addrs:
the ``(host, port)``s of the peers eligible to handle the RPC, and
possibly a ``None`` entry if this hub can handle it locally
:type peer_addrs: li... |
def setup(app):
"""Setup the sphinx extension
This will setup autodoc and autosummary.
Add the :class:`ext.ModDocstringDocumenter`.
Add the config values.
Connect builder-inited event to :func:`gendoc.main`.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
... |
def start(self, key=None, **params):
"""initialize process timing for the current stack"""
self.params.update(**params)
key = key or self.stack_key
if key is not None:
self.current_times[key] = time() |
def report(self, fraction=None):
"""report the total progress for the current stack, optionally given the local fraction completed.
fraction=None: if given, used as the fraction of the local method so far completed.
runtimes=None: if given, used as the expected runtimes for the current stack.
"""
r = Dict()
... |
def finish(self):
"""record the current stack process as finished"""
self.report(fraction=1.0)
key = self.stack_key
if key is not None:
if self.data.get(key) is None:
self.data[key] = []
start_time = self.current_times.get(key) or time()
self.data[key].append(Dict(runtime=time()-start_time, **self.... |
def add_directive_header(self, sig):
"""Add the directive header and options to the generated content."""
domain = getattr(self, 'domain', 'py')
directive = getattr(self, 'directivetype', "module")
name = self.format_name()
self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, n... |
def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down we are going to cycle to the next potential peer from the Client
self._peer = connection.Peer(
None, ... |
def wait_connected(self, timeout=None):
'''Wait for connections to be made and their handshakes to finish
:param timeout:
maximum time to wait in seconds. with None, there is no timeout.
:type timeout: float or None
:returns:
``True`` if all connections were mad... |
def reset(self):
"Close the current failed connection and prepare for a new one"
log.info("resetting client")
rpc_client = self._rpc_client
self._addrs.append(self._peer.addr)
self.__init__(self._addrs)
self._rpc_client = rpc_client
self._dispatcher.rpc_client = r... |
def shutdown(self):
'Close the hub connection'
log.info("shutting down")
self._peer.go_down(reconnect=False, expected=True) |
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the regis... |
def publish_receiver_count(
self, service, routing_id, method, timeout=None):
'''Get the number of peers that would handle a particular publish
This method will block until a response arrives
:param service: the service name
:type service: anything hash-able
:param ... |
def send_rpc(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send out an RPC request
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
The id used for routing within the r... |
def rpc_receiver_count(self, service, routing_id, method, timeout=None):
'''Get the number of peers that would handle a particular RPC
This method will block until a response arrives
:param service: the service name
:type service: anything hash-able
:param routing_id:
... |
def _headers(self, others={}):
"""Return the default headers and others as necessary"""
headers = {
'Content-Type': 'application/json'
}
for p in others.keys():
headers[p] = others[p]
return headers |
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
'''
Read the config file with spec validation
'''
# configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
# encoding='UTF8',
# ... |
def elapsed_time_string(start_time, stop_time):
r"""
Return a formatted string with the elapsed time between two time points.
The string includes years (365 days), months (30 days), days (24 hours),
hours (60 minutes), minutes (60 seconds) and seconds. If both arguments
are equal, the string return... |
def pcolor(text, color, indent=0):
r"""
Return a string that once printed is colorized.
:param text: Text to colorize
:type text: string
:param color: Color to use, one of :code:`'black'`, :code:`'red'`,
:code:`'green'`, :code:`'yellow'`, :code:`'blue'`,
:co... |
def quote_str(obj):
r"""
Add extra quotes to a string.
If the argument is not a string it is returned unmodified.
:param obj: Object
:type obj: any
:rtype: Same as argument
For example:
>>> import pmisc
>>> pmisc.quote_str(5)
5
>>> pmisc.quote_str('Hello... |
def strframe(obj, extended=False):
"""
Return a string with a frame record pretty-formatted.
The record is typically an item in a list generated by `inspect.stack()
<https://docs.python.org/3/library/inspect.html#inspect.stack>`_).
:param obj: Frame record
:type obj: tuple
:param extende... |
def set(self, x):
"""
Set variable values via a dictionary mapping name to value.
"""
for name, value in iter(x.items()):
if hasattr(value, "ndim"):
if self[name].value.ndim < value.ndim:
self[name].value.itemset(value.squeeze())
... |
def select(self, fixed):
"""
Return a subset of variables according to ``fixed``.
"""
names = [n for n in self.names() if self[n].isfixed == fixed]
return Variables({n: self[n] for n in names}) |
def validate(self, tracking_number):
"Return True if this is a valid USPS tracking number."
tracking_num = tracking_number[:-1].replace(' ', '')
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num):
if ii % 2:
odd_total += int(digit)
... |
def validate(self, tracking_number):
"Return True if this is a valid UPS tracking number."
tracking_num = tracking_number[2:-1]
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num.upper()):
try:
value = int(digit)
except V... |
def track(self, tracking_number):
"Track a UPS package by number. Returns just a delivery date."
resp = self.send_request(tracking_number)
return self.parse_response(resp) |
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which d... |
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)... |
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
... |
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from ... |
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
... |
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
---------... |
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
it... |
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This func... |
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find ... |
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single tran... |
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.no... |
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np... |
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T) |
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
... |
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
... |
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style head... |
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The pre... |
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
fil... |
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors |
def demo_usage(n_data=50, n_fit=537, nhead=5, ntail=5, plot=False, alt=0):
"""
Plots a noisy sine curve and the fitting to it.
Also presents the error and the error in the
approximation of its first derivative (cosine curve)
Usage example for benchmarking:
$ time python sine.py --nhead 3 --nta... |
def demo_err():
"""
This demo shows how the error in the estimate varies depending
on how many data points are included in the interpolation
(m parameter in this function).
"""
max_order = 7
n = 20
l = 0.25
fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}'
fmt2 = '{0:... |
def display_results(repo_name, contributors, api_len):
"""
Fancy display.
"""
print("\n")
print("All Contributors:")
# Sort and consolidate on Name
seen = []
for user in sorted(contributors, key=_sort_by_name):
if user.get("name"):
key = user["name"]
else:
... |
def get_json(uri):
"""
Handle headers and json for us :3
"""
response = requests.get(API + uri, headers=HEADERS)
limit = int(response.headers.get("x-ratelimit-remaining"))
if limit == 0:
sys.stdout.write("\n")
message = "You have run out of GitHub request tokens. "
if i... |
def api_walk(uri, per_page=100, key="login"):
"""
For a GitHub URI, walk all the pages until there's no more content
"""
page = 1
result = []
while True:
response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page))
if len(response) == 0:
break
else:
... |
def api_get(uri, key=None):
"""
Simple API endpoint get, return only the keys we care about
"""
response = get_json(uri)
if response:
if type(response) == list:
r = response[0]
elif type(response) == dict:
r = response
if type(r) == dict:
... |
def reducejson(j):
"""
Not sure if there's a better way to walk the ... interesting result
"""
authors = []
for key in j["data"]["repository"]["commitComments"]["edges"]:
authors.append(key["node"]["author"])
for key in j["data"]["repository"]["issues"]["nodes"]:
auth... |
def stringify_with_dot_if_path(x):
'''Pathlib never renders a leading './' in front of a local path. That's an
issue because on POSIX subprocess.py (like bash) won't execute scripts in
the current directory without it. In the same vein, we also don't want
Path('echo') to match '/usr/bin/echo' from the $... |
def maybe_canonicalize_exe_path(exe_name, iocontext):
'''There's a tricky interaction between exe paths and `dir`. Exe paths can
be relative, and so we have to ask: Is an exe path interpreted relative to
the parent's cwd, or the child's? The answer is that it's platform
dependent! >.< (Windows uses the ... |
def safe_popen(*args, **kwargs):
'''This wrapper works around two major deadlock issues to do with pipes.
The first is that, before Python 3.2 on POSIX systems, os.pipe() creates
inheritable file descriptors, which leak to all child processes and prevent
reads from reaching EOF. The workaround for this ... |
def run(self):
'''Execute the expression and return a Result, which includes the exit
status and any captured output. Raise an exception if the status is
non-zero.'''
with spawn_output_reader() as (stdout_capture, stdout_thread):
with spawn_output_reader() as (stderr_capture,... |
def read(self):
'''Execute the expression and capture its output, similar to backticks
or $() in the shell. This is a wrapper around run() which captures
stdout, decodes it, trims it, and returns it directly.'''
result = self.stdout_capture().run()
stdout_str = decode_with_univer... |
def start(self):
'''Equivalent to `run`, but instead of blocking the current thread,
return a WaitHandle that doesn't block until `wait` is called. This is
currently implemented with a simple background thread, though in theory
it could avoid using threads in most cases.'''
threa... |
def _exec(self, cmd, url, json_data=None):
"""
execute a command at the device using the RESTful API
:param str cmd: one of the REST commands, e.g. GET or POST
:param str url: URL of the REST API the command should be applied to
:param dict json_data: json data that should be at... |
def set_device(self, dev):
"""
set the current device (that will be used for following API calls)
:param dict dev: device that should be used for the API calls
(can be obtained via get_devices function)
"""
log.debug("setting device to '{}'".format(dev))... |
def _get_widget_id(self, package_name):
"""
returns widget_id for given package_name does not care
about multiple widget ids at the moment, just picks the first
:param str package_name: package to check for
:return: id of first widget which belongs to the given package_name
... |
def get_user(self):
"""
get the user details via the cloud
"""
log.debug("getting user information from LaMetric cloud...")
_, url = CLOUD_URLS["get_user"]
res = self._cloud_session.session.get(url)
if res is not None:
# raise an exception on error
... |
def get_devices(self, force_reload=False, save_devices=True):
"""
get all devices that are linked to the user, if the local device
file is not existing the devices will be obtained from the LaMetric
cloud, otherwise the local device file will be read.
:param bool force_reload: W... |
def save_devices(self):
"""
save devices that have been obtained from LaMetric cloud
to a local file
"""
log.debug("saving devices to ''...".format(self._devices_filename))
if self._devices != []:
with codecs.open(self._devices_filename, "wb", "utf-8") as f:
... |
def get_endpoint_map(self):
"""
returns API version and endpoint map
"""
log.debug("getting end points...")
cmd, url = DEVICE_URLS["get_endpoint_map"]
return self._exec(cmd, url) |
def load_devices(self):
"""
load stored devices from the local file
"""
self._devices = []
if os.path.exists(self._devices_filename):
log.debug(
"loading devices from '{}'...".format(self._devices_filename)
)
with codecs.open(se... |
def get_device_state(self):
"""
returns the full device state
"""
log.debug("getting device state...")
cmd, url = DEVICE_URLS["get_device_state"]
return self._exec(cmd, url) |
def send_notification(
self, model, priority="warning", icon_type=None, lifetime=None
):
"""
sends new notification to the device
:param Model model: an instance of the Model class that should be used
:param str priority: the priority of the notification
... |
def get_notifications(self):
"""
returns the list of all notifications in queue
"""
log.debug("getting notifications in queue...")
cmd, url = DEVICE_URLS["get_notifications_queue"]
return self._exec(cmd, url) |
def get_current_notification(self):
"""
returns the current notification (i.e. the one that is visible)
"""
log.debug("getting visible notification...")
cmd, url = DEVICE_URLS["get_current_notification"]
return self._exec(cmd, url) |
def get_notification(self, notification_id):
"""
returns a specific notification by given id
:param str notification_id: the ID of the notification
"""
log.debug("getting notification '{}'...".format(notification_id))
cmd, url = DEVICE_URLS["get_notification"]
re... |
def get_display(self):
"""
returns information about the display, including
brightness, screensaver etc.
"""
log.debug("getting display information...")
cmd, url = DEVICE_URLS["get_display"]
return self._exec(cmd, url) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.