text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def shutdown(self): 'Close the hub connection' log.info("shutting down") self._peer.go_down(reconnect=False, expected=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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', # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if start_time > stop_time: raise RuntimeError("Invalid time delta specification") delta_time = stop_time - start_time # Python 2.6 datetime objects do not have total_seconds() method tot_seconds = int( ( delta_time.microseconds + (delta_time.seconds + delta_time....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 u...
esc_dict = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "none": -1, } if not isinstance(text, str): raise RuntimeError("Argument `text` is not valid") if not isins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if not isinstance(obj, str): return obj return "'{obj}'".format(obj=obj) if '"' in obj else '"{obj}"'.format(obj=obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.stac...
# Stack frame -> (frame object [0], filename [1], line number of current # line [2], function name [3], list of lines of context from source # code [4], index of current line within list [5]) fname = normalize_windows_fname(obj[1]) ret = list() ret.append(pcolor("Frame object ID: {0}".format(he...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()) else: self[name].value = value else: self[name].value.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 funct...
vectors, items = Reach._load(pathtovector, wordlist, num_to_load, truncate_embeddings, sep) if unk_word is not None: if unk_word not in set(ite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) except ValueError: wordlist = set() logger.info("Loading {0}".format(pathtovector)) firstline = open(pathtovector).readline().strip() try: num,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vectorize(self, tokens, remove_oov=False, norm=False): """ Vectorize a sentence by replacing all items with their vectors. Parameters tokens : object or list...
if not tokens: raise ValueError("You supplied an empty list.") index = list(self.bow(tokens, remove_oov=remove_oov)) if not index: raise ValueError("You supplied a list with only OOV tokens: {}, " "which then got removed. Set remove_oov to Fa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if remove_oov: tokens = [x for x in tokens if x in self.items] for t in tokens: try: yield self.items[t] except KeyError: if self.unk_index is None: raise ValueError("You supplied OOV items but didn't " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, corpus, remove_oov=False, norm=False): """ Transform a corpus by repeated calls to vectorize, defined above. Parameters corpus : A list of st...
return [self.vectorize(s, remove_oov=remove_oov, norm=norm) for s in corpus]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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....
# This line allows users to input single items. # We used to rely on string identities, but we now also allow # anything hashable as keys. # Might fail if a list of passed items is also in the vocabulary. # but I can't think of cases when this would happen, and what # us...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold(self, items, threshold=.5, batch_size=100, show_progressbar=False, return_names=True): """ Return all items whose similarity is higher than thresho...
# This line allows users to input single items. # We used to rely on string identities, but we now also allow # anything hashable as keys. # Might fail if a list of passed items is also in the vocabulary. # but I can't think of cases when this would happen, and what # us...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 v...
if np.ndim(vectors) == 1: norm = np.linalg.norm(vectors) if norm == 0: return np.zeros_like(vectors) return vectors / norm norm = np.linalg.norm(vectors, axis=1) if np.any(norm == 0): nonzero = norm > 0 result = np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
try: if i1 in self.items: i1 = [i1] except TypeError: pass try: if i2 in self.items: i2 = [i2] except TypeError: pass i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1]) i2_vec ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 word...
# Remove duplicates wordlist = set(wordlist).intersection(set(self.items.keys())) indices = [self.items[w] for w in wordlist if w in self.items] if self.unk_index is not None and self.unk_index not in indices: raise ValueError("Your unknown item is not in your list of items....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_h...
with open(path, 'w') as f: if write_header: f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]), str(self.vectors.shape[1]))) for i in range(len(self.items)): w = self.indices[i] vec = self.vectors[i] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 separate...
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1])) items = {"items": items, "unk_index": self.unk_index, "name": self.name} json.dump(items, open("{}_items.json".format(filename), 'w')) np.save(open("{}_vectors.npy".format(filename), 'wb')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
words, unk_index, name, vectors = Reach._load_fast(filename) return Reach(vectors, words, unk_index=unk_index, name=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: page += 1 for r in response: if key == USER_LOGIN: result.append(user_log...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: # Special nested value we care about if key == USER_LOGIN: return user_login(r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reducejson(j): """ """
authors = [] for key in j["data"]["repository"]["commitComments"]["edges"]: authors.append(key["node"]["author"]) for key in j["data"]["repository"]["issues"]["nodes"]: authors.append(key["author"]) for c in key["comments"]["nodes"]: authors.append...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 :...
assert(cmd in ("GET", "POST", "PUT", "DELETE")) assert(self.dev is not None) if json_data is None: json_data = {} # add device address to the URL url = url.format(self.dev["ipv4_internal"]) # set basic authentication auth = HTTPBasicAuth("dev", sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
widget_id = "" for app in self.get_apps_list(): if app.package == package_name: widget_id = list(app.widgets.keys())[0] return widget_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 res.raise_for_status() return res.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 devic...
if ( (not os.path.exists(self._devices_filename)) or (force_reload is True) ): # -- load devices from LaMetric cloud -- log.debug("getting devices from LaMetric cloud...") _, url = CLOUD_URLS["get_devices"] res = self._cloud_sessio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: json.dump(self._devices, f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(self._devices_filename, "rb", "utf-8") as f: self._devices = json.load(f) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_notification( self, model, priority="warning", icon_type=None, lifetime=None ): """ sends new notification to the device :param Model model: an instance...
assert(priority in ("info", "warning", "critical")) assert(icon_type in (None, "none", "info", "alert")) assert((lifetime is None) or (lifetime > 0)) log.debug("sending notification...") cmd, url = DEVICE_URLS["send_notification"] json_data = {"model": model.json(), "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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"] return self._exec(cmd, url.replace(":id", notification_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 st...
assert(mode in ("when_dark", "time_based")) log.debug("setting screensaver to '{}'...".format(mode)) cmd, url = DEVICE_URLS["set_display"] json_data = { "screensaver": { "enabled": is_screensaver_enabled, "mode": mode, "mode_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_volume(self): """ returns the current volume """
log.debug("getting volumne...") cmd, url = DEVICE_URLS["get_volume"] return self._exec(cmd, url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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["set_volume"] json_data = { "volume": volume, } return self._exec(cmd, url, json_data=json_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = [ AppModel(result[app]) for app in result ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 packa...
log.debug("switching to app '{}'...".format(package)) cmd, url = DEVICE_URLS["switch_to_app"] widget_id = self._get_widget_id(package) url = url.format('{}', package, widget_id) self.result = self._exec(cmd, url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.format('{}', package, widget_id) self.result = self._exec(cmd, url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 a...
# get list of possible commands from app.actions allowed_commands = [] for app in self.get_apps_list(): if app.package == package: allowed_commands = list(app.actions.keys()) break # check if action is in this list assert(action in al...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 T...
# TODO: check for correct time format log.debug("alarm => set...") params = { "enabled": True, "time": time, "wake_with_radio": wake_with_radio } self._app_exec("com.lametric.clock", "clock.alarm", params=params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alarm_disable(self): """ disable the alarm """
log.debug("alarm => disable...") params = {"enabled": False} self._app_exec("com.lametric.clock", "clock.alarm", params=params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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", "countdown.configure", params )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def action(self, includes: dict, variables: dict) -> tuple: """ Call external script. :param includes: testcase's includes :param variables: variables :return: sc...
json_args = fill_template_str(json.dumps(self.data), variables) p = subprocess.Popen([self.module, json_args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if p.wait() == 0: out = p.stdout.read().decode() debug(out) return variables, json.loads(out) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 obtain...
if (self._client_id is None) or (self._client_secret is None): sys.exit( "Please make sure to set the client id and client secret " "via the constructor, the environment variables or the config " "file; otherwise, the LaMetric cloud cannot be accessed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_input(self, variables): """ Use this method to get simple input as python object, with all templates filled in :param variables: :return: python objec...
json_args = fill_template_str(json.dumps(self.data), variables) return try_get_objects(json_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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", "client_secret", "") # save new config self.save() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """ save current config to the file """
with open(self._filename, "w") as f: self.config.write(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 > 0: time.sleep(wait)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route(self, arg, destination=None, waypoints=None, raw=False, **kwargs): """ Query a route. route(locations): points can be - a sequence of locations - a Sh...
points = _parse_points(arg, destination, waypoints) if len(points) < 2: raise ValueError('You must specify at least 2 points') self.rate_limit_wait() data = self.raw_query(points, **kwargs) self._last_query = time.time() if raw: return data ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
# prepare UDP socket to transfer the SSDP packets s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP ) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) s.settimeout(timeo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) # go through all UPNP devices and filter wanted devices filtered_devices = collections.defaultdict(dict) for dev in upnp_devices.values(): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if not n_cpus: n_cpus = mp.cpu_count() elif n_cpus < 0: n_cpus = mp.cpu_count() - n_cpus if stepsize is None: stepsize = n_cpus results = [] with mp.Pool(processes=n_cpus) as p: while True: r = p.map(data_processor, islice(data_generator, stepsize)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 regul...
if not n_cpus: n_cpus = mp.cpu_count() elif n_cpus < 0: n_cpus = mp.cpu_count() - n_cpus if stepsize is None: stepsize = n_cpus with mp.Pool(processes=n_cpus) as p: while True: r = p.map(data_processor, islice(data_generator, stepsize)) if r: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_variables(func): """ Use this decorator on Step.action implementation. Your action method should always return variables, or both variables and output...
@wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if isinstance(result, tuple): return self.process_register(result[0], result[1]) else: return self.process_register(result) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# if the action type corresponds to a roll call if action_type == roll_call_type(): # then announce the service await service.announce()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 string model = json.loads(payload) if isinstance(payload, str) else payload # the list of known models models = service._external_service_data['mode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): Th...
# the list of filters for the models out = [] # for each attribute we have to order by for key in order_by: # remove any whitespace key = key.strip() # if the key starts with a plus if key.startswith("+"): # add the ascending filter to the list ou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 template render_template(template='common', context=context) render_template(template='model', context=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.sort() service_name = ''.join([service.title() for service in services]) # the template context context = { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_native_type_dictionary(fields, respect_required=False, wrap_field=True, name=''): """ This function takes a list of type summaries and builds a diction...
# a place to start when building the input field attributes input_fields = {} # go over every input in the summary for field in fields: field_name = name + field['name'] field_type = field['type'] # if the type field is a string if isinstance(field_type, str): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=model, action=method) # a mapping of methods to input factories input_map = { 'create': create_mutation_inputs, 'update': u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_callback())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._consumer_task.cancel() # if there was no service except AttributeError: # keep going ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 message = serialize_action(action_type=action_type, payload=payload, **kwds) # send the message return await self._producer.send(channel, message.en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_action(action_type, payload, **extra_fields): """ This function returns the conventional form of the actions. """
action_dict = dict( action_type=action_type, payload=payload, **extra_fields ) # return a serializable version return json.dumps(action_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fields_for_model(model): """ This function returns the fields for a schema that matches the provided nautilus model. Args: model (nautilus.model.BaseModel): ...
# the attribute arguments (no filters) args = {field.name.lower() : convert_peewee_field(field) \ for field in model.fields()} # use the field arguments, without the segments return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_connection_model(service): """ Create an SQL Alchemy table that connects the provides services """
# the services connected services = service._services # the mixins / base for the model bases = (BaseModel,) # the fields of the derived attributes = {model_service_name(service): fields.CharField() for service in services} # create an instance of base model with the right attributes ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_handler(Model, name=None, **kwds): """ This factory returns an action handler that creates a new instance of the specified model when a create action ...
async def action_handler(service, action_type, payload, props, notify=True, **kwds): # if the payload represents a new instance of `Model` if action_type == get_crud_action('create', name or Model): # print('handling create for ' + name or Model) try: # the p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _has_id(self, *args, **kwds): """ Equality checks are overwitten to perform the actual check in a semantic way. """
# if there is only one positional argument if len(args) == 1: # parse the appropriate query result = await parse_string( self._query, self.service.object_resolver, self.service.connection_resolver, self.service.muta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_id(self, result, uid): """ This method performs a depth-first search for the given uid in the dictionary of results. """
# if the result is a list if isinstance(result, list): # if the list has a valid entry if any([self._find_id(value, uid) for value in result]): # then we're done return True # otherwise results could be dictionaries if isinstance(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_before(self): """Returns a builder inserting a new block before the current block"""
idx = self._container.structure.index(self) return BlockBuilder(self._container, idx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_after(self): """Returns a builder inserting a new block after the current block"""
idx = self._container.structure.index(self) return BlockBuilder(self._container, idx+1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment(self, text, comment_prefix='#'): """Creates a comment block Args: text (str): content of comment without # comment_prefix (str): character indicati...
comment = Comment(self._container) if not text.startswith(comment_prefix): text = "{} {}".format(comment_prefix, text) if not text.endswith('\n'): text = "{}{}".format(text, '\n') comment.add_line(text) self._container.structure.insert(self._idx, comment)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def section(self, section): """Creates a section block Args: section (str or :class:`Section`): name of section or object Returns: self for chaining """
if not isinstance(self._container, ConfigUpdater): raise ValueError("Sections can only be added at section level!") if isinstance(section, str): # create a new section section = Section(section, container=self._container) elif not isinstance(section, Section)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def space(self, newlines=1): """Creates a vertical space of newlines Args: newlines (int): number of empty lines Returns: self for chaining """
space = Space() for line in range(newlines): space.add_line('\n') self._container.structure.insert(self._idx, space) self._idx += 1 return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def option(self, key, value=None, **kwargs): """Creates a new option inside a section Args: key (str): key of the option value (str or None): value of the opti...
if not isinstance(self._container, Section): raise ValueError("Options can only be added inside a section!") option = Option(key, value, container=self._container, **kwargs) option.value = value self._container.structure.insert(self._idx, option) self._idx += 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_comment(self, line): """Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment """
if not isinstance(self.last_item, Comment): comment = Comment(self._structure) self._structure.append(comment) self.last_item.add_line(line) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_space(self, line): """Add a Space object to the section Used during initial parsing mainly Args: line (str): one line that defines the space, maybe whit...
if not isinstance(self.last_item, Space): space = Space(self._structure) self._structure.append(space) self.last_item.add_line(line) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, option, value=None): """Set an option for chaining. Args: option (str): option name value (str): value, default None """
option = self._container.optionxform(option) if option in self.options(): self.__getitem__(option).value = value else: self.__setitem__(option, value) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, filename, encoding=None): """Read and parse a filename. Args: filename (str): path to file encoding (str): encoding of file, default None """
with open(filename, encoding=encoding) as fp: self._read(fp, filename) self._filename = os.path.abspath(filename)