INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
r Return a string that once printed is colorized. | 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... |
r Add extra quotes to a string. | 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... |
Return a string with a frame record pretty - formatted. | 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... |
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:
self[name].value.itemset(value.squeeze())
... |
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):
if ii % 2:
odd_total += int(digit)
... |
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:
value = int(digit)
except V... |
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. | 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... |
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 = []
try:
wordlist = set(wordlist)... |
Vectorize a sentence by replacing all items with their vectors. | 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
... |
Create a bow representation of a list of tokens. | 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 ... |
Transform a corpus by repeated calls to vectorize defined above. | 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
... |
Return the num most similar items to a given list of items. | 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
---------... |
Return all items whose similarity is higher than threshold. | 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... |
Find the nearest neighbors to some arbitrary vector. | 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... |
Find the nearest neighbors to some arbitrary vector. | def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find ... |
Batched cosine distance. | def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single tran... |
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.
reference_transposed = self.no... |
Normalize a matrix of row vectors to unit length. | 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... |
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.dot(items_vec.T) |
Compute the similarity between two sets of items. | 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
... |
Prune the current reach instance by removing items. | 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
... |
Save the current vector space in word2vec format. | 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... |
Save a reach instance in a fast format. | 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... |
Load a reach instance in fast format. | 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... |
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_index, name, vectors |
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 ) | 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... |
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
(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:... |
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"]
else:
... |
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 GitHub request tokens. "
if i... |
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_page))
if len(response) == 0:
break
else:
... |
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:
r = response
if type(r) == 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"])
for key in j["data"]["repository"]["issues"]["nodes"]:
auth... |
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 explicitly join a ... | 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 $... |
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 Unix usually us... | 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 ... |
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 which was not th... | 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 ... |
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 the status is
non-zero.'''
with spawn_output_reader() as (stdout_capture, stdout_thread):
with spawn_output_reader() as (stderr_capture,... |
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 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... |
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 `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... |
execute a command at the device using the RESTful API | 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... |
set the current device ( that will be used for following API calls ) | 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))... |
returns widget_id for given package_name does not care about multiple widget ids at the moment just picks the first | 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
... |
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:
# raise an exception on error
... |
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. | 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... |
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 != []:
with codecs.open(self._devices_filename, "wb", "utf-8") as f:
... |
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)
)
with codecs.open(se... |
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 | 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
... |
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"]
return self._exec(cmd, url) |
returns a specific notification by given id | 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... |
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_display"]
return self._exec(cmd, url) |
allows to modify display state ( change brightness ) | def set_display(self, brightness=100, brightness_mode="auto"):
"""
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
[aut... |
set the display s screensaver mode | def set_screensaver(
self, mode, is_mode_enabled, start_time=None, end_time=None,
is_screensaver_enabled=True
):
"""
set the display's screensaver mode
:param str mode: mode of the screensaver
[when_dark, time_based]
:param bool is_mode_enabl... |
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 | def set_volume(self, volume=50):
"""
allows to change the volume
:param int volume: volume to be set for the current device
[0..100] (default: 50)
"""
assert(volume in range(101))
log.debug("setting volume...")
cmd, url = DEVICE_URLS[... |
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, url = DEVICE_URLS["set_bluetooth"]
json_data = {}
... |
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"]
result = self._exec(cmd, url)
self.available_apps = [
... |
activates an app that is specified by package. Selects the first app it finds in the app list | def switch_to_app(self, package):
"""
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
"""
log.debug("switching to app '... |
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 | 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 id for the package
widget_id = self._get_widget_id(package)
url = url.form... |
meta method for all interactions with apps | def _app_exec(self, package, action, params=None):
"""
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
... |
set the alarm clock | def alarm_set(self, time, wake_with_radio=False):
"""
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
"""
# TODO: c... |
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 | def countdown_set(self, duration, start_now):
"""
set the countdown
:param str duration:
:param str start_now:
"""
log.debug("countdown => set...")
params = {'duration': duration, 'start_now': start_now}
self._app_exec(
"com.lametric.countdown... |
Call external script. | def action(self, includes: dict, variables: dict) -> tuple:
"""
Call external script.
:param includes: testcase's includes
:param variables: variables
:return: script's output
"""
json_args = fill_template_str(json.dumps(self.data), variables)
p = subproc... |
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 change
self._session = None |
init a new oauth2 session that is required to access the cloud | def init_session(self, get_token=True):
"""
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
"""
if (self._client_id is None) or (self._clien... |
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 | def simple_input(self, variables):
"""
Use this method to get simple input as python object, with all
templates filled in
:param variables:
:return: python object
"""
json_args = fill_template_str(json.dumps(self.data), variables)
return try_get_objects(... |
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", "")
self.config.set("lametric"... |
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) |
Sleep if rate limiting is required based on current time and last query. | def rate_limit_wait(self):
"""
Sleep if rate limiting is required based on current time and last
query.
"""
if self._rate_limit_dt and self._last_query is not None:
dt = time.time() - self._last_query
wait = self._rate_limit_dt - dt
if wait > ... |
Query a route. | def route(self, arg, destination=None, waypoints=None, raw=False, **kwargs):
"""
Query a route.
route(locations): points can be
- a sequence of locations
- a Shapely LineString
route(origin, destination, waypoints=None)
- origin and destination are a... |
Return a Route from a GeoJSON dictionary as returned by Route. geojson () | def from_geojson(cls, data):
"""
Return a Route from a GeoJSON dictionary, as returned by Route.geojson()
"""
properties = data['properties']
distance = properties.pop('distance')
duration = properties.pop('duration')
maneuvers = []
for feature in data['... |
Scan all paths for external modules and form key - value dict.: param module_paths: list of external modules ( either python packages or third - party scripts ): param available: dict of all registered python modules ( can contain python modules from module_paths ): return: dict of external modules where keys are filen... | def prepare_modules(module_paths: list, available: dict) -> dict:
"""
Scan all paths for external modules and form key-value dict.
:param module_paths: list of external modules (either python packages or third-party scripts)
:param available: dict of all registered python modules (can contain python mod... |
sends an SSDP discovery packet to the network and collects the devices that replies to it. A dictionary is returned using the devices unique usn as key | def discover_upnp_devices(
self, st="upnp:rootdevice", timeout=2, mx=1, retries=1
):
"""
sends an SSDP discovery packet to the network and collects
the devices that replies to it. A dictionary is returned
using the devices unique usn as key
"""
# prepare UDP s... |
returns a dict of devices that contain the given model name | def get_filtered_devices(
self, model_name, device_types="upnp:rootdevice", timeout=2
):
"""
returns a dict of devices that contain the given model name
"""
# get list of all UPNP devices in the network
upnp_devices = self.discover_upnp_devices(st=device_types)
... |
A variant of multiprocessing. Pool. map that supports lazy evaluation | def lazy_map(data_processor, data_generator, n_cpus=1, stepsize=None):
"""A variant of multiprocessing.Pool.map that supports lazy evaluation
As with the regular multiprocessing.Pool.map, the processes are spawned off
asynchronously while the results are returned in order. In contrast to
multiprocessin... |
A variant of multiprocessing. Pool. imap that supports lazy evaluation | def lazy_imap(data_processor, data_generator, n_cpus=1, stepsize=None):
"""A variant of multiprocessing.Pool.imap that supports lazy evaluation
As with the regular multiprocessing.Pool.imap, the processes are spawned
off asynchronously while the results are returned in order. In contrast to
multiproces... |
Use this decorator on Step. action implementation. | def update_variables(func):
"""
Use this decorator on Step.action implementation.
Your action method should always return variables, or
both variables and output.
This decorator will update variables with output.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = f... |
set the properties of the app model by the given data dict | def _set_properties(self, data):
"""
set the properties of the app model by the given data dict
"""
for property in data.keys():
if property in vars(self):
setattr(self, property, data[property]) |
get long description from README. rst file | def get_long_description():
"""
get long description from README.rst file
"""
with codecs.open(os.path.join(here, "README.rst"), "r", "utf-8") as f:
return f.read() |
This action handler responds to the roll call emitted by the api gateway when it is brought up with the normal summary produced by the service. | async def roll_call_handler(service, action_type, payload, props, **kwds):
"""
This action handler responds to the "roll call" emitted by the api
gateway when it is brought up with the normal summary produced by
the service.
"""
# if the action type corresponds to a roll call
if ... |
This query handler builds the dynamic picture of availible services. | async def flexible_api_handler(service, action_type, payload, props, **kwds):
"""
This query handler builds the dynamic picture of availible services.
"""
# if the action represents a new service
if action_type == intialize_service_action():
# the treat the payload like json if its a str... |
This function figures out the list of orderings for the given model and argument. | def _parse_order_by(model, order_by):
"""
This function figures out the list of orderings for the given model and
argument.
Args:
model (nautilus.BaseModel): The model to compute ordering against
order_by (list of str): the list of fields to order_by. If the field
... |
Creates the example directory structure necessary for a model service. | def model(model_names):
"""
Creates the example directory structure necessary for a model service.
"""
# for each model name we need to create
for model_name in model_names:
# the template context
context = {
'name': model_name,
}
# render the model t... |
Create the folder/ directories for an ApiGateway service. | def api():
"""
Create the folder/directories for an ApiGateway service.
"""
# the template context
context = {
'name': 'api',
'secret_key': random_string(32)
}
render_template(template='common', context=context)
render_template(template='api', context=context) |
Create the folder/ directories for an Auth service. | def auth():
"""
Create the folder/directories for an Auth service.
"""
# the template context
context = {
'name': 'auth',
}
render_template(template='common', context=context)
render_template(template='auth', context=context) |
Creates the example directory structure necessary for a connection service. | def connection(model_connections):
"""
Creates the example directory structure necessary for a connection
service.
"""
# for each connection group
for connection_str in model_connections:
# the services to connect
services = connection_str.split(':')
services.so... |
This function returns the conventional action designator for a given model. | def get_model_string(model):
"""
This function returns the conventional action designator for a given model.
"""
name = model if isinstance(model, str) else model.__name__
return normalize_string(name) |
This function takes a list of type summaries and builds a dictionary with native representations of each entry. Useful for dynamically building native class records from summaries. | def build_native_type_dictionary(fields, respect_required=False, wrap_field=True, name=''):
"""
This function takes a list of type summaries and builds a dictionary
with native representations of each entry. Useful for dynamically
building native class records from summaries.
"""
# a... |
This function provides the standard form for crud mutations. | def summarize_crud_mutation(method, model, isAsync=False):
"""
This function provides the standard form for crud mutations.
"""
# create the approrpriate action type
action_type = get_crud_action(method=method, model=model)
# the name of the mutation
name = crud_mutation_name(model=mode... |
This function starts the brokers interaction with the kafka stream | def start(self):
"""
This function starts the brokers interaction with the kafka stream
"""
self.loop.run_until_complete(self._consumer.start())
self.loop.run_until_complete(self._producer.start())
self._consumer_task = self.loop.create_task(self._consume_event_callba... |
This method stops the brokers interaction with the kafka stream | def stop(self):
"""
This method stops the brokers interaction with the kafka stream
"""
self.loop.run_until_complete(self._consumer.stop())
self.loop.run_until_complete(self._producer.stop())
# attempt
try:
# to cancel the service
self... |
This method sends a message over the kafka stream. | async def send(self, payload='', action_type='', channel=None, **kwds):
"""
This method sends a message over the kafka stream.
"""
# use a custom channel if one was provided
channel = channel or self.producer_channel
# serialize the action type for the
messag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.