text stringlengths 81 112k |
|---|
Normalizes a single frame
Returns a structured conglomeration of the input parameters to serve as
a signature. The parameter names of this function reflect the exact
names of the fields from the jsonMDSW frame output. This allows this
function to be invoked by passing a frame as ``**a_f... |
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
- irrelevant: Append this element only after seeing a prefix frame
The signature is ... |
Fix up some garbage errors.
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 wit... |
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.
def local_settings(settings, prefix):
"""Localizes the ... |
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*12342)
'12.1 MB'
>>> humanize_bytes(1024*12... |
return the parent URL, with params, query, and fragment in place
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
... |
join a list of url elements, and include any keyword arguments, as a new URL
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 |
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: list
:param service: the service of the message
:type servi... |
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`
:returns: None
... |
initialize process timing for the current stack
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() |
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.
def report(self, fraction=None):
"""report the total pr... |
record the current stack process as finished
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].... |
Add the directive header and options to the generated content.
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()
... |
Initiate the connection to a proxying hub
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._pee... |
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 made, ``False`` if one or more
failed.
de... |
Close the current failed connection and prepare for a new one
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._... |
Close the hub connection
def shutdown(self):
'Close the hub connection'
log.info("shutting down")
self._peer.go_down(reconnect=False, expected=True) |
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 registered handlers of the
service.
:type routing_id: int
:param method: the method name ... |
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 routing_id:
the id used for narrowing within the service handlers
:type routing_i... |
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 registered handlers of the
service.
:type routing_id: int
:param method: the method na... |
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:
the id used for narrowing within the service handlers
:type routing_id: i... |
Return the default headers and others as necessary
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 |
Read the config file with spec validation
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),
# ... |
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 returned is :code:`'None'`; otherwise, the string
retu... |
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'`,
:code:`'magenta'`, :code:`'cyan'`, :code:`... |
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!')
'"Hello!"'
... |
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 extended: Flag that indicates whether contents of the ... |
Set variable values via a dictionary mapping name to value.
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:
... |
Return a subset of variables according to ``fixed``.
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}) |
Return True if this is a valid USPS tracking number.
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):
... |
Return True if this is a valid UPS tracking number.
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:
... |
Track a UPS package by number. Returns just a delivery date.
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) |
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whe... |
Load a matrix and wordlist from a .vec file.
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 = []
... |
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
Whether to remove OOV items. If False, OOV items are replaced by
... |
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 the input.
If this is True, the length of the ret... |
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
can either be strings or lists of tokens.
remove_oov : bool, o... |
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_s... |
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
ba... |
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily no... |
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily no... |
Batched cosine distance.
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vecto... |
Batched cosine distance.
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
refe... |
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.array
The vectors to normalize.... |
Compute the similarity between a vector and a set of items.
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... |
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
An array of similarity scores between 1 and ... |
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
wordlist, but not in the reach insta... |
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 header as the first line of the
file
def save(self, ... |
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 prefix to add to the saved filename. Note that this is not th... |
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
----------
filename : str
The filename prefix from whi... |
Sub for fast loader.
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_i... |
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 --ntail 3 --n-fit 500000 --n-data 50000
Usage example for plotting:
$ python sine.... |
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).
def demo_err():
"""
This demo shows how the error in the estimate varies depending
on how many data points are included in the interpolation
(... |
Fancy display.
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"... |
Handle headers and json for us :3
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 Git... |
For a GitHub URI, walk all the pages until there's no more content
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_pag... |
Simple API endpoint get, return only the keys we care about
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:
... |
Not sure if there's a better way to walk the ... interesting result
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"])
fo... |
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 $PATH. To work around both
issues, we e... |
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 parent's cwd, but because of the
fork-chdir-exec pattern,... |
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 is to set close_fds=True
on POSIX, w... |
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.
def run(self):
'''Execute the expression and return a Result, which includes the exit
status and any captured output. Raise an exception if t... |
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.
def read(self):
'''Execute the expression and capture its output, similar to backticks
or $() in ... |
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.
def start(self):
'''Equivalent to `... |
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 attached to the command
def _exec(self, cmd, url, json_data=None... |
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)
def set_device(self, dev):
"""
set the current device (that will be used for following API calls)... |
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
:rtype: str
def _get_widget_id(self, package_name):
... |
get the user details via the cloud
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:
... |
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: When True, devices are read again from cloud
:param bool save_devices: When... |
save devices that have been obtained from LaMetric cloud
to a local file
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 ... |
returns API version and endpoint map
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) |
load stored devices from the local file
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)
... |
returns the full device state
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) |
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
[info, warning or critical] (default: warning)
:param str icon_type: the icon type of the notification
... |
returns the list of all notifications in queue
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) |
returns the current notification (i.e. the one that is visible)
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"]
ret... |
returns a specific notification by given id
:param str notification_id: the ID of the notification
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... |
returns information about the display, including
brightness, screensaver etc.
def get_display(self):
"""
returns information about the display, including
brightness, screensaver etc.
"""
log.debug("getting display information...")
cmd, url = DEVICE_URLS["get_disp... |
allows to modify display state (change brightness)
:param int brightness: display brightness [0, 100] (default: 100)
:param str brightness_mode: the brightness mode of the display
[auto, manual] (default: auto)
def set_display(self, brightness=100, brightness_mode="... |
set the display's screensaver mode
:param str mode: mode of the screensaver
[when_dark, time_based]
:param bool is_mode_enabled: specifies if mode is enabled or disabled
:param str start_time: start time, only used in time_based mode
(form... |
returns the current volume
def get_volume(self):
"""
returns the current volume
"""
log.debug("getting volumne...")
cmd, url = DEVICE_URLS["get_volume"]
return self._exec(cmd, url) |
allows to change the volume
:param int volume: volume to be set for the current device
[0..100] (default: 50)
def set_volume(self, volume=50):
"""
allows to change the volume
:param int volume: volume to be set for the current device
... |
returns the bluetooth state
def get_bluetooth_state(self):
"""
returns the bluetooth state
"""
log.debug("getting bluetooth state...")
cmd, url = DEVICE_URLS["get_bluetooth_state"]
return self._exec(cmd, url) |
allows to activate/deactivate bluetooth and change the name
def set_bluetooth(self, active=None, name=None):
"""
allows to activate/deactivate bluetooth and change the name
"""
assert(active is not None or name is not None)
log.debug("setting bluetooth state...")
cmd, ... |
returns the current Wi-Fi state the device is connected to
def get_wifi_state(self):
"""
returns the current Wi-Fi state the device is connected to
"""
log.debug("getting wifi state...")
cmd, url = DEVICE_URLS["get_wifi_state"]
return self._exec(cmd, url) |
gets installed apps and puts them into the available_apps list
def set_apps_list(self):
"""
gets installed apps and puts them into the available_apps list
"""
log.debug("getting apps and setting them in the internal app list...")
cmd, url = DEVICE_URLS["get_apps_list"]
... |
activates an app that is specified by package. Selects the first
app it finds in the app list
:param package: name of package/app
:type package: str
:return: None
:rtype: None
def switch_to_app(self, package):
"""
activates an app that is specified by package. S... |
switches to the next app
def switch_to_next_app(self):
"""
switches to the next app
"""
log.debug("switching to next app...")
cmd, url = DEVICE_URLS["switch_to_next_app"]
self.result = self._exec(cmd, url) |
activate the widget of the given package
:param str package: name of the package
def activate_widget(self, package):
"""
activate the widget of the given package
:param str package: name of the package
"""
cmd, url = DEVICE_URLS["activate_widget"]
# get widget... |
meta method for all interactions with apps
:param package: name of package/app
:type package: str
:param action: the action to be executed
:type action: str
:param params: optional parameters for this action
:type params: dict
:return: None
:rtype: None
... |
set the alarm clock
:param str time: time of the alarm (format: %H:%M:%S)
:param bool wake_with_radio: if True, radio will be used for the alarm
instead of beep sound
def alarm_set(self, time, wake_with_radio=False):
"""
set the alarm clock
... |
disable the alarm
def alarm_disable(self):
"""
disable the alarm
"""
log.debug("alarm => disable...")
params = {"enabled": False}
self._app_exec("com.lametric.clock", "clock.alarm", params=params) |
set the countdown
:param str duration:
:param str start_now:
def countdown_set(self, duration, start_now):
"""
set the countdown
:param str duration:
:param str start_now:
"""
log.debug("countdown => set...")
params = {'duration': duration, 'sta... |
Call external script.
:param includes: testcase's includes
:param variables: variables
:return: script's output
def action(self, includes: dict, variables: dict) -> tuple:
"""
Call external script.
:param includes: testcase's includes
:param variables: variable... |
set given credentials and reset the session
def set_credentials(self, client_id=None, client_secret=None):
"""
set given credentials and reset the session
"""
self._client_id = client_id
self._client_secret = client_secret
# make sure to reset session due to credential ... |
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
def init_session(self, get_token=True):
"""
init a new oauth2 session that is required to access the cloud
... |
get current oauth token
def get_token(self):
"""
get current oauth token
"""
self.token = self._session.fetch_token(
token_url=CLOUD_URLS["get_token"][1],
client_id=self._client_id,
client_secret=self._client_secret
) |
Use this method to get simple input as python object, with all
templates filled in
:param variables:
:return: python object
def simple_input(self, variables):
"""
Use this method to get simple input as python object, with all
templates filled in
:param variable... |
creates an empty configuration file
def create(self):
"""
creates an empty configuration file
"""
if not self.exists():
# create new empyt config file based on template
self.config.add_section("lametric")
self.config.set("lametric", "client_id", "")
... |
save current config to the file
def save(self):
"""
save current config to the file
"""
with open(self._filename, "w") as f:
self.config.write(f) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.