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 isalive(path): """ Returns True if the file with the given name contains a process id that is still alive. Returns False otherwise. :type path: str :param pa...
# try to read the pid from the pidfile pid = read(path) if pid is None: return False # Check if a process with the given pid exists. try: os.kill(pid, 0) # Signal 0 does not kill, but check. except OSError as xxx_todo_changeme1: (code, text) = xxx_todo_changeme1.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 kill(path): """ Kills the process, if it still exists. :type path: str :param path: The name of the pidfile. """
# try to read the pid from the pidfile pid = read(path) if pid is None: return # Try to kill the process. logging.info("Killing PID %s", pid) try: os.kill(pid, 9) except OSError as xxx_todo_changeme2: # re-raise if the error wasn't "No such process" (code, 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 write(path): """ Writes the current process id to the given pidfile. :type path: str :param path: The name of the pidfile. """
pid = os.getpid() logging.info("Writing PID %s to '%s'", pid, path) try: pidfile = open(path, 'wb') # get a non-blocking exclusive lock fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) # clear out the file pidfile.seek(0) pidfile.truncate(0) ...
<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_username_prompt(self, regex=None): """ Defines a pattern that is used to monitor the response of the connected host for a username prompt. :type regex: R...
if regex is None: self.manual_user_re = regex else: self.manual_user_re = to_regexs(regex)
<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_password_prompt(self, regex=None): """ Defines a pattern that is used to monitor the response of the connected host for a password prompt. :type regex: R...
if regex is None: self.manual_password_re = regex else: self.manual_password_re = to_regexs(regex)
<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_login_error_prompt(self, error=None): """ Defines a pattern that is used to monitor the response of the connected host during the authentication procedur...
if error is None: self.manual_login_error_re = error else: self.manual_login_error_re = to_regexs(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, hostname=None, port=None): """ Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host o...
if hostname is not None: self.host = hostname conn = self._connect_hook(self.host, port) self.os_guesser.protocol_info(self.get_remote_version()) self.auto_driver = driver_map[self.guess_os()] if self.get_banner(): self.os_guesser.data_received(self.get_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def protocol_authenticate(self, account=None): """ Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, ...
with self._get_account(account) as account: user = account.get_name() password = account.get_password() key = account.get_key() if key is None: self._dbg(1, "Attempting to authenticate %s." % user) self._protocol_authenticate(user,...
<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_authenticate(self, account=None, flush=True, bailout=False): """ Attempt to perform application-level authentication. Application level authentication is...
with self._get_account(account) as account: user = account.get_name() password = account.get_password() self._dbg(1, "Attempting to app-authenticate %s." % user) self._app_authenticate(account, password, flush, bailout) self.app_authenticated = 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 add_monitor(self, pattern, callback, limit=80): """ Calls the given function whenever the given pattern matches the incoming data. .. HINT:: If you want to c...
self.buffer.add_monitor(pattern, partial(callback, self), limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_connection(func): """ A decorator that unpacks the host and connection from the job argument and passes them as separate arguments to the wrapped fu...
def _wrapped(job, *args, **kwargs): job_id = id(job) to_parent = job.data['pipe'] host = job.data['host'] # Create a protocol adapter. mkaccount = partial(_account_factory, to_parent, host) pargs = {'account_factory': mkaccount, 'stdout': j...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join(self): """ Waits until all jobs are completed. """
self._dbg(2, 'Waiting for the queue to finish.') self.workqueue.wait_until_done() for child in list(self.pipe_handlers.values()): child.join() self._del_status_bar() self._print_status_bar() gc.collect()
<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, force=False): """ Stop executing any further jobs. If the force argument is True, the function does not wait until any queued jobs are complet...
if not force: self.join() self._dbg(2, 'Shutting down queue...') self.workqueue.shutdown(True) self._dbg(2, 'Queue shut down.') self._del_status_bar()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Remove all accounts, hosts, etc. """
self._dbg(2, 'Resetting queue...') self.account_manager.reset() self.workqueue.shutdown(True) self.completed = 0 self.total = 0 self.failed = 0 self.status_bar_length = 0 self._dbg(2, 'Queue reset.') self._del_status_bar()
<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(scope, source, index): """ Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type sou...
try: index = int(index[0]) except IndexError: raise ValueError('index variable is required') except ValueError: raise ValueError('index is not an integer') try: return [source[index]] except IndexError: raise ValueError('no such item in the list')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(scope, command): """ Executes the given command locally. :type command: string :param command: A shell command. """
process = Popen(command[0], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) scope.define(__response__=process.stdout.read()) return 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 set(self, key, value, confidence=100): """ Defines the given value with the given confidence, unless the same value is already defined with a higher confiden...
if value is None: return if key in self.info: old_confidence, old_value = self.info.get(key) if old_confidence >= confidence: return self.info[key] = (confidence, value)
<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(self, key, confidence=0): """ Returns the info with the given key, if it has at least the given confidence. Returns None otherwise. """
if key not in self.info: return None conf, value = self.info.get(key) if conf >= confidence: return value return 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 bind(function, *args, **kwargs): """ Wraps the given function such that when it is called, the given arguments are passed in addition to the connection argum...
def decorated(*inner_args, **inner_kwargs): kwargs.update(inner_kwargs) return function(*(inner_args + args), **kwargs) copy_labels(function, decorated) return decorated
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def problem_glob(extension='.py'): """Returns ProblemFile objects for all valid problem files"""
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension)) return [ProblemFile(file) for file in filenames]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def human_time(timespan, precision=3): """Formats the timespan in a human readable format"""
if timespan >= 60.0: # Format time greater than one minute in a human-readable format # Idea from http://snipplr.com/view/5713/ def _format_long_time(time): suffixes = ('d', 'h', 'm', 's') lengths = (24*60*60, 60*60, 60, 1) for suffix, length in zip(suf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_time(start, end): """Returns string with relevant time information formatted properly"""
try: cpu_usr = end[0] - start[0] cpu_sys = end[1] - start[1] except TypeError: # `clock()[1] == None` so subtraction results in a TypeError return 'Time elapsed: {}'.format(human_time(cpu_usr)) else: times = (human_time(x) for x in (cpu_usr, cpu_sys, cpu_usr + cpu_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filename(self, prefix='', suffix='', extension='.py'): """Returns filename padded with leading zeros"""
return BASE_NAME.format(prefix, self.num, suffix, extension)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def glob(self): """Returns a sorted glob of files belonging to a given problem"""
file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*')) # Sort globbed files by tuple (filename, extension) return sorted(file_glob, key=lambda f: os.path.splitext(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 copy_resources(self): """Copies the relevant resources to a resources subdirectory"""
if not os.path.isdir('resources'): os.mkdir('resources') resource_dir = os.path.join(os.getcwd(), 'resources', '') copied_resources = [] for resource in self.resources: src = os.path.join(EULER_DATA, 'resources', resource) if os.path.isfile(src): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solution(self): """Returns the answer to a given problem"""
num = self.num solution_file = os.path.join(EULER_DATA, 'solutions.txt') solution_line = linecache.getline(solution_file, num) try: answer = solution_line.split('. ')[1].strip() except IndexError: answer = None if answer: return ans...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self): """Parses problems.txt and returns problem text"""
def _problem_iter(problem_num): problem_file = os.path.join(EULER_DATA, 'problems.txt') with open(problem_file) as f: is_problem = False last_line = '' for line in f: if line.strip() == 'Problem %i' % problem_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 cheat(num): """View the answer to a problem."""
# Define solution before echoing in case solution does not exist solution = click.style(Problem(num).solution, bold=True) click.confirm("View answer to problem %i?" % num, abort=True) click.echo("The answer to problem {} is {}.".format(num, solution))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(num, prompt_default=True): """Generates Python file for a problem."""
p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: filename = str(p.file) msg = '"{}" already exists. Overwrite?'.format(filename) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preview(num): """Prints the text of a problem."""
# Define problem_text before echoing in case problem does not exist problem_text = Problem(num).text click.secho("Project Euler Problem %i" % num, bold=True) click.echo(problem_text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip(num): """Generates Python file for the next problem."""
click.echo("Current problem is problem %i." % num) generate(num + 1, prompt_default=False) Problem(num).file.change_suffix('-skipped')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(num, filename=None, exit=True): """Verifies the solution to a problem."""
p = Problem(num) filename = filename or p.filename() if not os.path.isfile(filename): # Attempt to verify the first problem file matched by glob if p.glob: filename = str(p.file) else: click.secho('No file found for problem %i.' % p.num, fg='red') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_all(num): """ Verifies all problem files in the current directory and prints an overview of the status of each problem. """
# Define various problem statuses keys = ('correct', 'incorrect', 'error', 'skipped', 'missing') symbols = ('C', 'I', 'E', 'S', '.') colours = ('green', 'red', 'yellow', 'cyan', 'white') status = OrderedDict( (key, click.style(symbol, fg=colour, bold=True)) for key, symbol, colour...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def euler_options(fn): """Decorator to link CLI options with their appropriate functions"""
euler_functions = cheat, generate, preview, skip, verify, verify_all # Reverse functions to print help page options in alphabetical order for option in reversed(euler_functions): name, docstring = option.__name__, option.__doc__ kwargs = {'flag_value': option, 'help': docstring} #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(option, problem): """Python-based Project Euler command line tool."""
# No problem given (or given option ignores the problem argument) if problem == 0 or option in {skip, verify_all}: # Determine the highest problem number in the current directory files = problem_glob() problem = max(file.num for file in files) if files else 0 # No Project Euler...
<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, *args, **kwargs): """ Start the server thread if it wasn't created with autostart = True. """
if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.start() self._server.proxyInit() return True except Exception as err: LOG.critical("Failed to start serve...
<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, *args, **kwargs): """ Stop the server thread. """
if args: LOG.debug("args: %s" % str(args)) if kwargs: LOG.debug("kwargs: %s" % str(kwargs)) try: self._server.stop() self._server = None # Device-storage clear self.devices.clear() self.devices_all.clear() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getMetadata(self, remote, address, key): """Get metadata of device"""
if self._server is not None: # pylint: disable=E1121 return self._server.getAllMetadata(remote, address, key)
<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_hs_color(self): """ Return the color of the light as HSV color without the "value" component for the brightness. Returns (hue, saturation) tuple with val...
# Get the color from homematic. In general this is just the hue parameter. hm_color = self.getCachedOrUpdatedValue("COLOR", channel=self._color_channel) if hm_color >= 200: # 200 is a special case (white), so we have a saturation of 0. # Larger values are undefined. For...
<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_hs_color(self, hue: float, saturation: float): """ Set a fixed color and also turn off effects in order to see the color. :param hue: Hue component (rang...
self.turn_off_effect() if saturation < 0.1: # Special case (white) hm_color = 200 else: hm_color = int(round(max(min(hue, 1), 0) * 199)) self.setValue(key="COLOR", channel=self._color_channel, value=hm_color)
<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_effect(self) -> str: """Return the current color change program of the light."""
effect_value = self.getCachedOrUpdatedValue("PROGRAM", channel=self._effect_channel) try: return self._light_effect_list[effect_value] except IndexError: LOG.error("Unexpected color effect returned by CCU") return "Unknown"
<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_effect(self, effect_name: str): """Sets the color change program of the light."""
try: effect_index = self._light_effect_list.index(effect_name) except ValueError: LOG.error("Trying to set unknown light effect") return False return self.setValue(key="PROGRAM", channel=self._effect_channel, value=effect_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_http_credentials(username=None, password=None): """Build auth part for api_url."""
credentials = '' if username is None: return credentials if username is not None: if ':' in username: return credentials credentials += username if credentials and password is not None: credentials += ":%s" % password return "%s@" % credentials
<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_api_url(host=REMOTES['default']['ip'], port=REMOTES['default']['port'], path=REMOTES['default']['path'], username=None, password=None, ssl=False): """B...
credentials = make_http_credentials(username, password) scheme = 'http' if not path: path = '' if path and not path.startswith('/'): path = "/%s" % path if ssl: scheme += 's' return "%s://%s%s:%i%s" % (scheme, credentials, host, port, path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createDeviceObjects(self, interface_id): """Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass."""
global WORKING WORKING = True remote = interface_id.split('-')[-1] LOG.debug( "RPCFunctions.createDeviceObjects: iterating interface_id = %s" % (remote, )) # First create parent object for dev in self._devices_raw[remote]: if not dev['PARENT']: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def event(self, interface_id, address, value_key, value): """If a device emits some sort event, we will handle it here."""
LOG.debug("RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % ( interface_id, address, value_key.upper(), str(value))) self.devices_all[interface_id.split( '-')[-1]][address].event(interface_id, value_key.upper(), value) if self.eventcallb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __request(self, *args, **kwargs): """ Call method on server side """
with self.lock: parent = xmlrpc.client.ServerProxy # pylint: disable=E1101 return parent._ServerProxy__request(self, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseCCUSysVar(self, data): """Helper to parse type of system variables of CCU"""
if data['type'] == 'LOGIC': return data['name'], data['value'] == 'true' elif data['type'] == 'NUMBER': return data['name'], float(data['value']) elif data['type'] == 'LIST': return data['name'], int(data['value']) else: return data['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 jsonRpcLogin(self, remote): """Login to CCU and return session"""
session = False try: params = {"username": self.remotes[remote][ 'username'], "password": self.remotes[remote]['password']} response = self._rpcfunctions.jsonRpcPost( self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPOR...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jsonRpcLogout(self, remote, session): """Logout of CCU"""
logout = False try: params = {"_session_id_": session} response = self._rpcfunctions.jsonRpcPost( self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.logout", params) if response['error'] is None and response['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def homegearCheckInit(self, remote): """Check if proxy is still initialized"""
rdict = self.remotes.get(remote) if not rdict: return False if rdict.get('type') != BACKEND_HOMEGEAR: return False try: interface_id = "%s-%s" % (self._interface_id, remote) return self.proxies[interface_id].clientServerInitialized(interfa...
<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_ontime(self, ontime): """Set duration th switch stays on when toggled. """
try: ontime = float(ontime) except Exception as err: LOG.debug("SwitchPowermeter.set_ontime: Exception %s" % (err,)) return False self.actionNodeData("ON_TIME", ontime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def event(self, interface_id, key, value): """ Handle the event received by server. """
LOG.info( "HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s" % (self._ADDRESS, interface_id, key, value)) self._VALUES[key] = value # Cache the value for callback in self._eventcallbacks: LOG.debug("HMGeneric.event: Using callback %s " % 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 getParamsetDescription(self, paramset): """ Descriptions for paramsets are available to determine what can be don with the device. """
try: self._PARAMSET_DESCRIPTIONS[paramset] = self._proxy.getParamsetDescription(self._ADDRESS, paramset) except Exception as err: LOG.error("HMGeneric.getParamsetDescription: Exception: " + str(err)) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateParamset(self, paramset): """ Devices should not update their own paramsets. They rely on the state of the server. Hence we pull the specified paramset...
try: if paramset: if self._proxy: returnset = self._proxy.getParamset(self._ADDRESS, paramset) if returnset: self._paramsets[paramset] = returnset if self.PARAMSETS: 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 updateParamsets(self): """ Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets. """
try: for ps in self._PARAMSETS: self.updateParamset(ps) return True except Exception as err: LOG.error("HMGeneric.updateParamsets: Exception: " + str(err)) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def putParamset(self, paramset, data={}): """ Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specifie...
try: if paramset in self._PARAMSETS and data: self._proxy.putParamset(self._ADDRESS, paramset, data) # We update all paramsets to at least have a temporarily accurate state for the device. # This might not be true for tasks that take long to complete ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCachedOrUpdatedValue(self, key): """ Gets the device's value with the given key. If the key is not found in the cache, the value is queried from the host....
try: return self._VALUES[key] except KeyError: return self.getValue(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCachedOrUpdatedValue(self, key, channel=None): """ Gets the channel's value with the given key. If the key is not found in the cache, the value is queried...
if channel: return self._hmchannels[channel].getCachedOrUpdatedValue(key) try: return self._VALUES[key] except KeyError: value = self._VALUES[key] = self.getValue(key) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def UNREACH(self): """ Returns true if the device or any children is not reachable """
if self._VALUES.get(PARAM_UNREACH, False): return True else: for device in self._hmchannels.values(): if device.UNREACH: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAttributeData(self, name, channel=None): """ Returns a attribut """
return self._getNodeData(name, self._ATTRIBUTENODE, channel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getBinaryData(self, name, channel=None): """ Returns a binary node """
return self._getNodeData(name, self._BINARYNODE, channel)
<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_temperature(self, target_temperature): """ Set the target temperature. """
try: target_temperature = float(target_temperature) except Exception as err: LOG.debug("Thermostat.set_temperature: Exception %s" % (err,)) return False self.writeNodeData("SET_TEMPERATURE", target_temperature)
<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): """Shut down our XML-RPC server."""
LOG.info("Shutting down server") self.server.shutdown() LOG.debug("ServerThread.stop: Stopping ServerThread") self.server.server_close() LOG.info("Server stopped")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def heirarchical_help(shovel, prefix): '''Given a shovel of tasks, display a heirarchical list of the tasks''' result = [] tuples = heirarchical_helper(shovel, prefix) if not tuples: return '' # We need to figure out the longest fullname length longest = max(len(name + ' ' * level) 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 shovel_help(shovel, *names): '''Return a string about help with the tasks, or lists tasks available''' # If names are provided, and the name refers to a group of tasks, print out # the tasks and a brief docstring. Otherwise, just enumerate all the tasks # available if not len(names): ret...
<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(cls, path, base=None): '''Either load a path and return a shovel object or return None''' obj = cls() obj.read(path, base) return 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 extend(self, tasks): '''Add tasks to this particular shovel''' self._tasks.extend(tasks) for task in tasks: # We'll now go through all of our tasks and group them into # sub-shovels current = self.map modules = task.fullname.split('.') ...
<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, path, base=None): '''Import some tasks''' if base == None: base = os.getcwd() absolute = os.path.abspath(path) if os.path.isfile(absolute): # Load that particular file logger.info('Loading %s' % absolute) self.extend(Task.loa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def keys(self): '''Return all valid keys''' keys = [] for key, value in self.map.items(): if isinstance(value, Shovel): keys.extend([key + '.' + k for k in value.keys()]) else: keys.append(key) return sorted(keys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def items(self): '''Return a list of tuples of all the keys and tasks''' pairs = [] for key, value in self.map.items(): if isinstance(value, Shovel): pairs.extend([(key + '.' + k, v) for k, v in value.items()]) else: pairs.append((key, valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tasks(self, name): '''Get all the tasks that match a name''' found = self[name] if isinstance(found, Shovel): return [v for _, v in found.items()] return [found]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make(cls, obj): '''Given a callable object, return a new callable object''' try: cls._cache.append(Task(obj)) except Exception: logger.exception('Unable to make task for %s' % repr(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 load(cls, path, base=None): '''Return a list of the tasks stored in a file''' base = base or os.getcwd() absolute = os.path.abspath(path) parent = os.path.dirname(absolute) name, _, _ = os.path.basename(absolute).rpartition('.py') fobj, path, description = imp.find_mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def capture(self, *args, **kwargs): '''Run a task and return a dictionary with stderr, stdout and the return value. Also, the traceback from the exception if there was one''' import traceback try: from StringIO import StringIO except ImportError: 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 dry(self, *args, **kwargs): '''Perform a dry-run of the task''' return 'Would have executed:\n%s%s' % ( self.name, Args(self.spec).explain(*args, **kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def help(self): '''Return the help string of the task''' # This returns a help string for a given task of the form: # # ================================================== # <name> # ============================== (If supplied) # <docstring> # =============...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def explain(self, *args, **kwargs): '''Return a string that describes how these args are interpreted''' args = self.get(*args, **kwargs) results = ['%s = %s' % (name, value) for name, value in args.required] results.extend(['%s = %s (overridden)' % ( name, value) for name, va...
<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(self, *args, **kwargs): '''Evaluate this argspec with the provided arguments''' # We'll go through all of our required args and make sure they're # present required = [arg for arg in self._args if arg not in kwargs] if len(args) < len(required): raise TypeErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sumnum(*args): '''Computes the sum of the provided numbers''' print('%s = %f' % (' + '.join(args), sum(float(arg) for arg in 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 attributes(name, **kwargs): '''Prints a name, and all keyword attributes''' print('%s has attributes:' % name) for key, value in kwargs.items(): print('\t%s => %s' % (key, value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, name, value, attrs=None, multi=False, renderer=None): """ Django <= 1.10 variant. """
DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or ( VERSION[0] >= 2 ) if DJANGO_111_OR_UP: return super(DynamicRawIDWidget, self).render( name, value, attrs, renderer=renderer ) if attrs is None: attrs = {} ...
<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_context(self, name, value, attrs): """ Django >= 1.11 variant. """
context = super(DynamicRawIDWidget, self).get_context( name, value, attrs ) model = self.rel.model if VERSION[0] == 2 else self.rel.to related_url = reverse( 'admin:{0}_{1}_changelist'.format( model._meta.app_label, model._meta.object_name.lower()...
<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_form(self, request, rel, admin_site): """Return filter form."""
return DynamicRawIDFilterForm( admin_site=admin_site, rel=rel, field_name=self.field_path, data=self.used_parameters, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queryset(self, request, queryset): """Filter queryset using params from the form."""
if self.form.is_valid(): # get no null params filter_params = dict( filter(lambda x: bool(x[1]), self.form.cleaned_data.items()) ) return queryset.filter(**filter_params) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decorator(cls, candidate, *exp_args, **exp_kwargs): ''' Decorate a control function in order to conduct an experiment when called. :param callable candidate: your candidate function :param iterable exp_args: positional arguments passed to :class:`Experiment` :param dict exp_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def candidate(self, cand_func, args=None, kwargs=None, name='Candidate', context=None): ''' Adds a candidate function to an experiment. Can be used multiple times for multiple candidates. :param callable cand_func: your control function :param iterable args: positional arguments...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def encode(data): ''' bytes -> str ''' if riemann.network.CASHADDR_PREFIX is None: raise ValueError('Network {} does not support cashaddresses.' .format(riemann.get_current_network_name())) data = convertbits(data, 8, 5) checksum = calculate_checksum(riemann.net...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decode(data): ''' str -> bytes ''' if riemann.network.CASHADDR_PREFIX is None: raise ValueError('Network {} does not support cashaddresses.' .format(riemann.get_current_network_name())) if data.find(riemann.network.CASHADDR_PREFIX) != 0: raise ValueError(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy(self, outpoint=None, stack_script=None, redeem_script=None, sequence=None): ''' TxIn -> TxIn ''' return TxIn( outpoint=outpoint if outpoint is not None else self.outpoint, stack_script=(stack_script if stack_script is not 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 from_bytes(TxIn, byte_string): ''' byte_string -> TxIn parses a TxIn from a byte-like object ''' outpoint = Outpoint.from_bytes(byte_string[:36]) script_sig_len = VarInt.from_bytes(byte_string[36:45]) script_start = 36 + len(script_sig_len) script_end...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def no_witness(self): ''' Tx -> bytes ''' tx = bytes() tx += self.version tx += VarInt(len(self.tx_ins)).to_bytes() for tx_in in self.tx_ins: tx += tx_in.to_bytes() tx += VarInt(len(self.tx_outs)).to_bytes() for tx_out in self.tx_outs: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _hash_sequence(self, sighash_type, anyone_can_pay): '''BIP143 hashSequence implementation Args: sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL anyone_can_pay (bool): true if ANYONECANPAY should be set Returns: (bytes): the hashSequence, a 32 byte ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _adjusted_script_code(self, script): ''' Checks if the script code pased in to the sighash function is already length-prepended This will break if there's a redeem script that's just a pushdata That won't happen in practice Args: script (bytes): the spend...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _hash_outputs(self, index, sighash_type): '''BIP143 hashOutputs implementation Args: index (int): index of input being signed sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL Returns: (bytes): the hashOutputs, a 32 byte hash ''' if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def deserialize(serialized_script): ''' bytearray -> str ''' deserialized = [] i = 0 while i < len(serialized_script): current_byte = serialized_script[i] if current_byte == 0xab: raise NotImplementedError('OP_CODESEPARATOR is a bad idea.') if current_byte <= ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _hsig_input(self, index): ''' inputs for the hsig hash ''' hsig_input = z.ZcashByteData() hsig_input += self.tx_joinsplits[index].random_seed hsig_input += self.tx_joinsplits[index].nullifiers hsig_input += self.joinsplit_pubkey return hsig_input.to_by...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _primary_input(self, index): ''' Primary input for the zkproof ''' primary_input = z.ZcashByteData() primary_input += self.tx_joinsplits[index].anchor primary_input += self.tx_joinsplits[index].nullifiers primary_input += self.tx_joinsplits[index].commitments ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_bytes(SproutTx, byte_string): ''' byte-like -> SproutTx ''' version = byte_string[0:4] tx_ins = [] tx_ins_num = shared.VarInt.from_bytes(byte_string[4:]) current = 4 + len(tx_ins_num) for _ in range(tx_ins_num.number): tx_in = TxIn.fr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy(self, version=None, tx_ins=None, tx_outs=None, lock_time=None, tx_joinsplits=None, joinsplit_pubkey=None, joinsplit_sig=None): ''' SproutTx, ... -> Tx Makes a copy. Allows over-writing specific pieces. ''' return SproutTx( version=version if ver...