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 listdir(directory): """Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local directory :return: list nested of file or directory names """
file_names = list() for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isdir(file_path): filename = f'{filename}{os.path.sep}' file_names.append(filename) return file_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 get_options(option_type, from_options): """Extract options for specified option type from all options :param option_type: the object of specified type of options :param from_options: all options dictionary :return: the dictionary of options for specified type, each option can be filled by value from all options dictionary or blank in case the option for specified type is not exist in all options dictionary """
_options = dict() for key in option_type.keys: key_with_prefix = f'{option_type.prefix}{key}' if key not in from_options and key_with_prefix not in from_options: _options[key] = '' elif key in from_options: _options[key] = from_options.get(key) else: _options[key] = from_options.get(key_with_prefix) return _options
<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_headers(self, action, headers_ext=None): """Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for the specified action. :return: the dictionary of headers for specified action. """
if action in Client.http_header: try: headers = Client.http_header[action].copy() except AttributeError: headers = Client.http_header[action][:] else: headers = list() if headers_ext: headers.extend(headers_ext) if self.webdav.token: webdav_token = f'Authorization: OAuth {self.webdav.token}' headers.append(webdav_token) return dict([map(lambda s: s.strip(), i.split(':')) for i in 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 execute_request(self, action, path, data=None, headers_ext=None): """Generate request to WebDAV server for specified action and path and execute it. :param action: the action for WebDAV server which should be executed. :param path: the path to resource for action :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`. :param headers_ext: (optional) the addition headers list witch should be added to basic HTTP headers for the specified action. :return: HTTP response of request. """
response = self.session.request( method=Client.requests[action], url=self.get_url(path), auth=self.webdav.auth, headers=self.get_headers(action, headers_ext), timeout=self.timeout, data=data ) if response.status_code == 507: raise NotEnoughSpace() if 499 < response.status_code < 600: raise ServerException(url=self.get_url(path), code=response.status_code, message=response.content) if response.status_code >= 400: raise ResponseErrorCode(url=self.get_url(path), code=response.status_code, message=response.content) return 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 valid(self): """Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise. """
return True if self.webdav.valid() and self.proxy.valid() else 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 download_from(self, buff, remote_path): """Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server. """
urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) response = self.execute_request(action='download', path=urn.quote()) buff.write(response.content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_directory(self, remote_path, local_path, progress=None): """Downloads directory and downloads all nested files and directories from remote WebDAV to local. If there is something on local path it deletes directories and files then creates new. :param remote_path: the path to directory for downloading form WebDAV server. :param local_path: the path to local directory for saving downloaded files and directories. :param progress: Progress function. Not supported now. """
urn = Urn(remote_path, directory=True) if not self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.exists(local_path): shutil.rmtree(local_path) os.makedirs(local_path) for resource_name in self.list(urn.path()): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.download(local_path=_local_path, remote_path=_remote_path, progress=progress)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_sync(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """
self.download(local_path=local_path, remote_path=remote_path) if callback: 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 download_async(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """
target = (lambda: self.download_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_directory(self, remote_path, local_path, progress=None): """Uploads directory to remote path on WebDAV server. In case directory is exist on remote server it will delete it and then upload directory with nested files and directories. :param remote_path: the path to directory for uploading on WebDAV server. :param local_path: the path to local directory for uploading. :param progress: Progress function. Not supported now. """
urn = Urn(remote_path, directory=True) if not urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) if self.check(urn.path()): self.clean(urn.path()) self.mkdir(remote_path) for resource_name in listdir(local_path): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.upload(local_path=_local_path, remote_path=_remote_path, progress=progress)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_sync(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """
self.upload(local_path=local_path, remote_path=remote_path) if callback: 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 upload_async(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """
target = (lambda: self.upload_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
<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_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. """
try: tree = etree.fromstring(content) hrees = [Urn.separate + unquote(urlsplit(hree.text).path) for hree in tree.findall('.//{DAV:}href')] return [Urn(hree) for hree in hrees] except etree.XMLSyntaxError: return 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 create_free_space_request_content(): """Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content. """
root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, 'quota-available-bytes') etree.SubElement(prop, 'quota-used-bytes') tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
<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_free_space_response(content, hostname): """Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the XML content of HTTP response from WebDAV server for getting free space. :param hostname: the server hostname. :return: an amount of free space in bytes. """
try: tree = etree.fromstring(content) node = tree.find('.//{DAV:}quota-available-bytes') if node is not None: return int(node.text) else: raise MethodNotSupported(name='free', server=hostname) except TypeError: raise MethodNotSupported(name='free', server=hostname) except etree.XMLSyntaxError: return 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 create_get_property_request_content(option): """Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be get, `name`: the name of property which will be get. :return: the XML string of request content. """
root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, option.get('name', ''), xmlns=option.get('namespace', '')) tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
<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_get_property_response(content, name): """Parses of response content XML from WebDAV server for getting metadata property value for some resource. :param content: the XML content of response as string. :param name: the name of property for finding a value in response :return: the value of property if it has been found or None otherwise. """
tree = etree.fromstring(content) return tree.xpath('//*[local-name() = $name]', name=name)[0].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 create_set_property_batch_request_content(options): """Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param options: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. :return: the XML string of request content. """
root_node = etree.Element('propertyupdate', xmlns='DAV:') set_node = etree.SubElement(root_node, 'set') prop_node = etree.SubElement(set_node, 'prop') for option in options: opt_node = etree.SubElement(prop_node, option['name'], xmlns=option.get('namespace', '')) opt_node.text = option.get('value', '') tree = etree.ElementTree(root_node) return WebDavXmlUtils.etree_to_string(tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def etree_to_string(tree): """Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :return: the string of XML. """
buff = BytesIO() tree.write(buff, xml_declaration=True, encoding='UTF-8') return buff.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_response_for_path(content, path, hostname): """Extracts single response for specified remote resource. :param content: raw content of response as string. :param path: the path to needed remote resource. :param hostname: the server hostname. :return: XML object of response for the remote resource defined by path. """
try: tree = etree.fromstring(content) responses = tree.findall('{DAV:}response') n_path = Urn.normalize_path(path) for resp in responses: href = resp.findtext('{DAV:}href') if Urn.compare_path(n_path, href) is True: return resp raise RemoteResourceNotFound(path) except etree.XMLSyntaxError: raise MethodNotSupported(name='is_dir', server=hostname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup(config_dir): """Remove temporary stderr and stdout files as well as the daemon socket."""
stdout_path = os.path.join(config_dir, 'pueue.stdout') stderr_path = os.path.join(config_dir, 'pueue.stderr') if os._exists(stdout_path): os.remove(stdout_path) if os._exists(stderr_path): os.remove(stderr_path) socketPath = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socketPath): os.remove(socketPath)
<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_descriptor_output(descriptor, key, handler=None): """Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve the valid and remove the invalid ones. To do this we need to get each line and check for an UnicodeDecodeError. """
line = 'stub' lines = '' while line != '': try: line = descriptor.readline() lines += line except UnicodeDecodeError: error_msg = "Error while decoding output of process {}".format(key) if handler: handler.logger.error("{} with command {}".format( error_msg, handler.queue[key]['command'])) lines += error_msg + '\n' return lines.replace('\n', '\n ')
<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, hash_, quickkey, doc_type, page=None, output=None, size_id=None, metadata=None, request_conversion_only=None): """Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img", or "swf" (document) size_id: 0,1,2 (document) 0-9, a-f, z (image) metadata: Set to 1 to get metadata dict request_conversion_only: Request conversion w/o content """
if len(hash_) > 4: hash_ = hash_[:4] query = QueryParams({ 'quickkey': quickkey, 'doc_type': doc_type, 'page': page, 'output': output, 'size_id': size_id, 'metadata': metadata, 'request_conversion_only': request_conversion_only }) url = API_ENDPOINT + '?' + hash_ + '&' + urlencode(query) response = self.http.get(url, stream=True) if response.status_code == 204: raise ConversionServerError("Unable to fulfill request. " "The document will not be converted.", response.status_code) response.raise_for_status() if response.headers['content-type'] == 'application/json': return response.json() return 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 bp_commands(self, frame, breakpoint_hits): """Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise."""
# Handle multiple breakpoints on the same line (issue 14789) effective_bp_list, temporaries = breakpoint_hits silent = True doprompt = False atleast_one_cmd = False for bp in effective_bp_list: if bp in self.commands: if not atleast_one_cmd: atleast_one_cmd = True self.setup(frame, None) lastcmd_back = self.lastcmd for line in self.commands[bp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[bp]: silent = False if self.commands_doprompt[bp]: doprompt = True # Delete the temporary breakpoints. tmp_to_delete = ' '.join(str(bp) for bp in temporaries) if tmp_to_delete: self.do_clear(tmp_to_delete) if atleast_one_cmd: return doprompt, silent 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 precmd(self, line): """Handle alias expansion and ';;' separator."""
if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace("%" + str(ii), tmpArg) ii += 1 line = line.replace("%*", ' '.join(args[1:])) args = line.split() # split into ';;' separated commands # unless it's an alias command if args[0] != 'alias': marker = line.find(';;') if marker >= 0: # queue up everything after marker next = line[marker+2:].lstrip() self.cmdqueue.append(next) line = line[:marker].rstrip() return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """
if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_command_def(self, line): """Handles one command line during command list definition."""
cmd, arg, line = self.parseline(line) if not cmd: return if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return 1 # end of cmd list cmdlist = self.commands[self.commands_bnum] if arg: cmdlist.append(cmd+' '+arg) else: cmdlist.append(cmd) # Determine if we must stop try: func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default # one of the resuming commands if func.__name__ in self.commands_resuming: self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defaultFile(self): """Produce a reasonable default."""
filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return 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 do_retval(self, arg): """retval Print the return value for the last return of a function. """
locals = self.get_locals(self.curframe) if '__return__' in locals: self.message(bdb.safe_repr(locals['__return__'])) else: self.error('Not yet returned!')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_p(self, arg): """p expression Print the value of the expression. """
try: self.message(bdb.safe_repr(self._getval(arg))) except Exception: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_pp(self, arg): """pp expression Pretty-print the value of the expression. """
obj = self._getval(arg) try: repr(obj) except Exception: self.message(bdb.safe_repr(obj)) else: self.message(pprint.pformat(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 do_longlist(self, arg): """longlist | ll List the whole source code for the current function or frame. """
filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: lines, lineno = getsourcelines(self.curframe, self.get_locals(self.curframe)) except IOError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_source(self, arg): """source expression Try to get source code for the given object and display it. """
try: obj = self._getval(arg) except Exception: return try: lines, lineno = getsourcelines(obj, self.get_locals(self.curframe)) except (IOError, TypeError) as err: self.error(err) return self._print_lines(lines, lineno)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_lines(self, lines, start, breaks=(), frame=None): """Print a range of lines."""
if frame: current_lineno = frame.f_lineno exc_lineno = self.tb_lineno.get(frame, -1) else: current_lineno = exc_lineno = -1 for lineno, line in enumerate(lines, start): s = str(lineno).rjust(3) if len(s) < 4: s += ' ' if lineno in breaks: s += 'B' else: s += ' ' if lineno == current_lineno: s += '->' elif lineno == exc_lineno: s += '>>' self.message(s + '\t' + line.rstrip())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_whatis(self, arg): """whatis arg Print the type of the argument. """
try: value = self._getval(arg) except Exception: # _getval() already printed the error return code = None # Is it a function? try: code = value.__code__ except Exception: pass if code: self.message('Function %s' % code.co_name) return # Is it an instance method? try: code = value.__func__.__code__ except Exception: pass if code: self.message('Method %s' % code.co_name) return # Is it a class? if value.__class__ is type: self.message('Class %s.%s' % (value.__module__, value.__name__)) return # None of the above... self.message(type(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 do_unalias(self, arg): """unalias name Delete the specified alias. """
args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[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 read(self, limit=-1): """Read content. See file.read"""
remaining = self.len - self.parent_fd.tell() + self.offset if limit > remaining or limit == -1: limit = remaining return self.parent_fd.read(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 seek(self, offset, whence=os.SEEK_SET): """Seek to position in stream, see file.seek"""
pos = None if whence == os.SEEK_SET: pos = self.offset + offset elif whence == os.SEEK_CUR: pos = self.tell() + offset elif whence == os.SEEK_END: pos = self.offset + self.len + offset else: raise ValueError("invalid whence {}".format(whence)) if pos > self.offset + self.len or pos < self.offset: raise ValueError("seek position beyond chunk area") self.parent_fd.seek(pos, os.SEEK_SET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close file, see file.close"""
try: self.parent_fd.fileno() except io.UnsupportedOperation: logger.debug("Not closing parent_fd - reusing existing") else: self.parent_fd.close()
<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_query(self, uri, params=None, action_token_type=None): """Prepare query string"""
if params is None: params = QueryParams() params['response_format'] = 'json' session_token = None if action_token_type in self._action_tokens: # Favor action token using_action_token = True session_token = self._action_tokens[action_token_type] else: using_action_token = False if self._session: session_token = self._session['session_token'] if session_token: params['session_token'] = session_token # make order of parameters predictable for testing keys = list(params.keys()) keys.sort() query = urlencode([tuple([key, params[key]]) for key in keys]) if not using_action_token and self._session: secret_key_mod = int(self._session['secret_key']) % 256 signature_base = (str(secret_key_mod) + self._session['time'] + uri + '?' + query).encode('ascii') query += '&signature=' + hashlib.md5(signature_base).hexdigest() return query
<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, action, params=None, action_token_type=None, upload_info=None, headers=None): """Perform request to MediaFire API action -- "category/name" of method to call params -- dict of parameters or query string action_token_type -- action token to use: None, "upload", "image" upload_info -- in case of upload, dict of "fd" and "filename" headers -- additional headers to send (used for upload) session_token and signature generation/update is handled automatically """
uri = self._build_uri(action) if isinstance(params, six.text_type): query = params else: query = self._build_query(uri, params, action_token_type) if headers is None: headers = {} if upload_info is None: # Use request body for query data = query headers['Content-Type'] = FORM_MIMETYPE else: # Use query string for query since payload is file uri += '?' + query if "filename" in upload_info: data = MultipartEncoder( fields={'file': ( upload_info["filename"], upload_info["fd"], UPLOAD_MIMETYPE )} ) headers["Content-Type"] = data.content_type else: data = upload_info["fd"] headers["Content-Type"] = UPLOAD_MIMETYPE logger.debug("uri=%s query=%s", uri, query if not upload_info else None) try: # bytes from now on url = (API_BASE + uri).encode('utf-8') if isinstance(data, six.text_type): # request's data is bytes, dict, or filehandle data = data.encode('utf-8') response = self.http.post(url, data=data, headers=headers, stream=True) except RequestException as ex: logger.exception("HTTP request failed") raise MediaFireConnectionError( "RequestException: {}".format(ex)) return self._process_response(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 _regenerate_secret_key(self): """Regenerate secret key http://www.mediafire.com/developers/core_api/1.3/getting_started/#call_signature """
# Don't regenerate the key if we have none if self._session and 'secret_key' in self._session: self._session['secret_key'] = ( int(self._session['secret_key']) * 16807) % 2147483647
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def session(self, value): """Set session token value -- dict returned by user/get_session_token"""
# unset session token if value is None: self._session = None return if not isinstance(value, dict): raise ValueError("session info is required") session_parsed = {} for key in ["session_token", "time", "secret_key"]: if key not in value: raise ValueError("Missing parameter: {}".format(key)) session_parsed[key] = value[key] for key in ["ekey", "pkey"]: # nice to have, but not mandatory if key in value: session_parsed[key] = value[key] self._session = session_parsed
<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_action_token(self, type_=None, action_token=None): """Set action tokens type_ -- either "upload" or "image" action_token -- string obtained from user/get_action_token, set None to remove the token """
if action_token is None: del self._action_tokens[type_] else: self._action_tokens[type_] = action_token
<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): '''Reset all of our stateful variables''' self._socket = None # The pending messages we have to send, and the current buffer we're # sending self._pending = deque() self._out_buffer = '' # Our read buffer self._buffer = '' # The identify response we last received from the server self._identify_response = {} # Our ready state self.last_ready_sent = 0 self.ready = 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 connect(self, force=False): '''Establish a connection''' # Don't re-establish existing connections if not force and self.alive(): return True self._reset() # Otherwise, try to connect with self._socket_lock: try: logger.info('Creating socket...') self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.settimeout(self._timeout) logger.info('Connecting to %s, %s', self.host, self.port) self._socket.connect((self.host, self.port)) # Set our socket's blocking state to whatever ours is self._socket.setblocking(self._blocking) # Safely write our magic self._pending.append(constants.MAGIC_V2) while self.pending(): self.flush() # And send our identify command self.identify(self._identify_options) while self.pending(): self.flush() self._reconnnection_counter.success() # Wait until we've gotten a response to IDENTIFY, try to read # one. Also, only spend up to the provided timeout waiting to # establish the connection. limit = time.time() + self._timeout responses = self._read(1) while (not responses) and (time.time() < limit): responses = self._read(1) if not responses: raise ConnectionTimeoutException( 'Read identify response timed out (%ss)' % self._timeout) self.identified(responses[0]) return True except: logger.exception('Failed to connect') if self._socket: self._socket.close() self._reconnnection_counter.failed() self._reset() 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 close(self): '''Close our connection''' # Flush any unsent message try: while self.pending(): self.flush() except socket.error: pass with self._socket_lock: try: if self._socket: self._socket.close() finally: self._reset()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def socket(self, blocking=True): '''Blockingly yield the socket''' # If the socket is available, then yield it. Otherwise, yield nothing if self._socket_lock.acquire(blocking): try: yield self._socket finally: self._socket_lock.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def identified(self, res): '''Handle a response to our 'identify' command. Returns response''' # If they support it, they should give us a JSON blob which we should # inspect. try: res.data = json.loads(res.data) self._identify_response = res.data logger.info('Got identify response: %s', res.data) except: logger.warn('Server does not support feature negotiation') self._identify_response = {} # Save our max ready count unless it's not provided self.max_rdy_count = self._identify_response.get( 'max_rdy_count', self.max_rdy_count) if self._identify_options.get('tls_v1', False): if not self._identify_response.get('tls_v1', False): raise UnsupportedException( 'NSQd instance does not support TLS') else: self._socket = TLSSocket.wrap_socket(self._socket) # Now is the appropriate time to send auth if self._identify_response.get('auth_required', False): if not self._auth_secret: raise UnsupportedException( 'Auth required but not provided') else: self.auth(self._auth_secret) # If we're not talking over TLS, warn the user if not self._identify_response.get('tls_v1', False): logger.warn('Using AUTH without TLS') elif self._auth_secret: logger.warn('Authentication secret provided but not required') return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setblocking(self, blocking): '''Set whether or not this message is blocking''' for sock in self.socket(): sock.setblocking(blocking) self._blocking = blocking
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def flush(self): '''Flush some of the waiting messages, returns count written''' # When profiling, we found that while there was some efficiency to be # gained elsewhere, the big performance hit is sending lots of small # messages at a time. In particular, consumers send many 'FIN' messages # which are very small indeed and the cost of dispatching so many system # calls is very high. Instead, we prefer to glom together many messages # into a single string to send at once. total = 0 for sock in self.socket(blocking=False): # If there's nothing left in the out buffer, take whatever's in the # pending queue. # # When using SSL, if the socket throws 'SSL_WANT_WRITE', then the # subsequent send requests have to send the same buffer. pending = self._pending data = self._out_buffer or ''.join( pending.popleft() for _ in xrange(len(pending))) try: # Try to send as much of the first message as possible total = sock.send(data) except socket.error as exc: # Catch (errno, message)-type socket.errors if exc.args[0] not in self.WOULD_BLOCK_ERRS: raise self._out_buffer = data else: self._out_buffer = None finally: if total < len(data): # Save the rest of the message that could not be sent self._pending.appendleft(data[total:]) return total
<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(self, command, message=None): '''Send a command over the socket with length endcoded''' if message: joined = command + constants.NL + util.pack(message) else: joined = command + constants.NL if self._blocking: for sock in self.socket(): sock.sendall(joined) else: self._pending.append(joined)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def identify(self, data): '''Send an identification message''' return self.send(constants.IDENTIFY, json.dumps(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 pub(self, topic, message): '''Publish to a topic''' return self.send(' '.join((constants.PUB, topic)), message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mpub(self, topic, *messages): '''Publish multiple messages to a topic''' return self.send(constants.MPUB + ' ' + topic, messages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rdy(self, count): '''Indicate that you're ready to receive''' self.ready = count self.last_ready_sent = count return self.send(constants.RDY + ' ' + str(count))
<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, limit=1000): '''Return all the responses read''' # It's important to know that it may return no responses or multiple # responses. It depends on how the buffering works out. First, read from # the socket for sock in self.socket(): if sock is None: # Race condition. Connection has been closed. return [] try: packet = sock.recv(4096) except socket.timeout: # If the socket times out, return nothing return [] except socket.error as exc: # Catch (errno, message)-type socket.errors if exc.args[0] in self.WOULD_BLOCK_ERRS: return [] else: raise # Append our newly-read data to our buffer self._buffer += packet responses = [] total = 0 buf = self._buffer remaining = len(buf) while limit and (remaining >= 4): size = struct.unpack('>l', buf[total:(total + 4)])[0] # Now check to see if there's enough left in the buffer to read # the message. if (remaining - 4) >= size: responses.append(Response.from_raw( self, buf[(total + 4):(total + size + 4)])) total += (size + 4) remaining -= (size + 4) limit -= 1 else: break self._buffer = self._buffer[total:] return responses
<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): '''Responses from an established socket''' responses = self._read() # Determine the number of messages in here and decrement our ready # count appropriately self.ready -= sum( map(int, (r.frame_type == Message.FRAME_TYPE for r in responses))) return responses
<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(self, topic): '''Run the discovery mechanism''' logger.info('Discovering on topic %s', topic) producers = [] for lookupd in self._lookupd: logger.info('Discovering on %s', lookupd) try: # Find all the current producers on this instance for producer in lookupd.lookup(topic)['producers']: logger.info('Found producer %s on %s', producer, lookupd) producers.append( (producer['broadcast_address'], producer['tcp_port'])) except ClientException: logger.exception('Failed to query %s', lookupd) new = [] for host, port in producers: conn = self._connections.get((host, port)) if not conn: logger.info('Discovered %s:%s', host, port) new.append(self.connect(host, port)) elif not conn.alive(): logger.info('Reconnecting to %s:%s', host, port) if conn.connect(): conn.setblocking(0) self.reconnected(conn) else: logger.debug('Connection to %s:%s still alive', host, port) # And return all the new connections return [conn for conn in new if conn]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_connections(self): '''Connect to all the appropriate instances''' logger.info('Checking connections') if self._lookupd: self.discover(self._topic) # Make sure we're connected to all the prescribed hosts for hostspec in self._nsqd_tcp_addresses: logger.debug('Checking nsqd instance %s', hostspec) host, port = hostspec.split(':') port = int(port) conn = self._connections.get((host, port), None) # If there is no connection to it, we have to try to connect if not conn: logger.info('Connecting to %s:%s', host, port) self.connect(host, port) elif not conn.alive(): # If we've connected to it before, but it's no longer alive, # we'll have to make a decision about when to try to reconnect # to it, if we need to reconnect to it at all if conn.ready_to_reconnect(): logger.info('Reconnecting to %s:%s', host, port) if conn.connect(): conn.setblocking(0) self.reconnected(conn) else: logger.debug('Checking freshness') now = time.time() time_check = math.ceil(now - self.last_recv_timestamp) if time_check >= ((self.heartbeat_interval * 2) / 1000.0): if conn.ready_to_reconnect(): logger.info('Reconnecting to %s:%s', host, port) if conn.connect(): conn.setblocking(0) self.reconnected(conn)
<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_checker(self): '''Run periodic reconnection checks''' thread = ConnectionChecker(self) logger.info('Starting connection-checker thread') thread.start() try: yield thread finally: logger.info('Stopping connection-checker') thread.stop() logger.info('Joining connection-checker') thread.join()
<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, host, port): '''Connect to the provided host, port''' conn = connection.Connection(host, port, reconnection_backoff=self._reconnection_backoff, auth_secret=self._auth_secret, timeout=self._connect_timeout, **self._identify_options) if conn.alive(): conn.setblocking(0) self.add(conn) return conn
<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(self, connection): '''Add a connection''' key = (connection.host, connection.port) with self._lock: if key not in self._connections: self._connections[key] = connection self.added(connection) return connection else: 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 remove(self, connection): '''Remove a connection''' key = (connection.host, connection.port) with self._lock: found = self._connections.pop(key, None) try: self.close_connection(found) except Exception as exc: logger.warn('Failed to close %s: %s', connection, exc) 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 read(self): '''Read from any of the connections that need it''' # We'll check all living connections connections = [c for c in self.connections() if c.alive()] if not connections: # If there are no connections, obviously we return no messages, but # we should wait the duration of the timeout time.sleep(self._timeout) return [] # Not all connections need to be written to, so we'll only concern # ourselves with those that require writes writes = [c for c in connections if c.pending()] try: readable, writable, exceptable = select.select( connections, writes, connections, self._timeout) except exceptions.ConnectionClosedException: logger.exception('Tried selecting on closed client') return [] except select.error: logger.exception('Error running select') return [] # If we returned because the timeout interval passed, log it and return if not (readable or writable or exceptable): logger.debug('Timed out...') return [] responses = [] # For each readable socket, we'll try to read some responses for conn in readable: try: for res in conn.read(): # We'll capture heartbeats and respond to them automatically if (isinstance(res, Response) and res.data == HEARTBEAT): logger.info('Sending heartbeat to %s', conn) conn.nop() logger.debug('Setting last_recv_timestamp') self.last_recv_timestamp = time.time() continue elif isinstance(res, Error): nonfatal = ( exceptions.FinFailedException, exceptions.ReqFailedException, exceptions.TouchFailedException ) if not isinstance(res.exception(), nonfatal): # If it's not any of the non-fatal exceptions, then # we have to close this connection logger.error( 'Closing %s: %s', conn, res.exception()) self.close_connection(conn) responses.append(res) logger.debug('Setting last_recv_timestamp') self.last_recv_timestamp = time.time() except exceptions.NSQException: logger.exception('Failed to read from %s', conn) self.close_connection(conn) except socket.error: logger.exception('Failed to read from %s', conn) self.close_connection(conn) # For each writable socket, flush some data out for conn in writable: try: conn.flush() except socket.error: logger.exception('Failed to flush %s', conn) self.close_connection(conn) # For each connection with an exception, try to close it and remove it # from our connections for conn in exceptable: self.close_connection(conn) return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def random_connection(self): '''Pick a random living connection''' # While at the moment there's no need for this to be a context manager # per se, I would like to use that interface since I anticipate # adding some wrapping around it at some point. yield random.choice( [conn for conn in self.connections() if conn.alive()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wait_response(self): '''Wait for a response''' responses = self.read() while not responses: responses = self.read() return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pub(self, topic, message): '''Publish the provided message to the provided topic''' with self.random_connection() as client: client.pub(topic, message) return self.wait_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 mpub(self, topic, *messages): '''Publish messages to a topic''' with self.random_connection() as client: client.mpub(topic, *messages) return self.wait_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 create_socket(self): """Create a socket for the daemon, depending on the directory location. Args: config_dir (str): The absolute path to the config directory used by the daemon. Returns: socket.socket: The daemon socket. Clients connect to this socket. """
socket_path = os.path.join(self.config_dir, 'pueue.sock') # Create Socket and exit with 1, if socket can't be created try: if os.path.exists(socket_path): os.remove(socket_path) self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(socket_path) self.socket.setblocking(0) self.socket.listen(0) # Set file permissions os.chmod(socket_path, stat.S_IRWXU) except Exception: self.logger.error("Daemon couldn't socket. Aborting") self.logger.exception() sys.exit(1) return self.socket
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_directories(self, root_dir): """Create all directories needed for logs and configs."""
if not root_dir: root_dir = os.path.expanduser('~') # Create config directory, if it doesn't exist self.config_dir = os.path.join(root_dir, '.config/pueue') if not os.path.exists(self.config_dir): os.makedirs(self.config_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def respond_client(self, answer, socket): """Send an answer to the client."""
response = pickle.dumps(answer, -1) socket.sendall(response) self.read_list.remove(socket) socket.close()
<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(self): """Read a previous configuration file or create a new with default values."""
config_file = os.path.join(self.config_dir, 'pueue.ini') self.config = configparser.ConfigParser() # Try to get configuration file and return it # If this doesn't work, a new default config file will be created if os.path.exists(config_file): try: self.config.read(config_file) return except Exception: self.logger.error('Error while parsing config file. Deleting old config') self.logger.exception() self.config['default'] = { 'resumeAfterStart': False, 'maxProcesses': 1, 'customShell': 'default', } self.config['log'] = { 'logTime': 60*60*24*14, } self.write_config()
<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_config(self): """Write the current configuration to the config file."""
config_file = os.path.join(self.config_dir, 'pueue.ini') with open(config_file, 'w') as file_descriptor: self.config.write(file_descriptor)
<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_daemon(self, payload=None): """Kill current processes and initiate daemon shutdown. The daemon will shut down after a last check on all killed processes. """
kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.running = False return {'message': 'Pueue daemon shutting down', 'status': 'success'}
<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_config(self, payload): """Update the current config depending on the payload and save it."""
self.config['default'][payload['option']] = str(payload['value']) if payload['option'] == 'maxProcesses': self.process_handler.set_max(payload['value']) if payload['option'] == 'customShell': path = payload['value'] if os.path.isfile(path) and os.access(path, os.X_OK): self.process_handler.set_shell(path) elif path == 'default': self.process_handler.set_shell() else: return {'message': "File in path doesn't exist or is not executable.", 'status': 'error'} self.write_config() return {'message': 'Configuration successfully updated.', 'status': 'success'}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pipe_to_process(self, payload): """Send something to stdin of a specific process."""
message = payload['input'] key = payload['key'] if not self.process_handler.is_running(key): return {'message': 'No running process for this key', 'status': 'error'} self.process_handler.send_to_process(message, key) return {'message': 'Message sent', 'status': 'success'}
<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_status(self, payload): """Send the daemon status and the current queue for displaying."""
answer = {} data = [] # Get daemon status if self.paused: answer['status'] = 'paused' else: answer['status'] = 'running' # Add current queue or a message, that queue is empty if len(self.queue) > 0: data = deepcopy(self.queue.queue) # Remove stderr and stdout output for transfer # Some outputs are way to big for the socket buffer # and this is not needed by the client for key, item in data.items(): if 'stderr' in item: del item['stderr'] if 'stdout' in item: del item['stdout'] else: data = 'Queue is empty' answer['data'] = data return answer
<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_everything(self, payload): """Kill all processes, delete the queue and clean everything up."""
kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.process_handler.wait_for_finish() self.reset = True answer = {'message': 'Resetting current queue', 'status': 'success'} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, payload): """Clear queue from any `done` or `failed` entries. The log will be rotated once. Otherwise we would loose all logs from thoes finished processes. """
self.logger.rotate(self.queue) self.queue.clear() self.logger.write(self.queue) answer = {'message': 'Finished entries have been removed.', 'status': 'success'} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_command(self, payload): """Edit the command of a specific entry."""
key = payload['key'] command = payload['command'] if self.queue[key]: if self.queue[key]['status'] in ['queued', 'stashed']: self.queue[key]['command'] = command answer = {'message': 'Command updated', 'status': 'error'} else: answer = {'message': "Entry is not 'queued' or 'stashed'", 'status': 'error'} else: answer = {'message': 'No entry with this key', 'status': 'error'} # Pause all processes and the daemon return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stash(self, payload): """Stash the specified processes."""
succeeded = [] failed = [] for key in payload['keys']: if self.queue.get(key) is not None: if self.queue[key]['status'] == 'queued': self.queue[key]['status'] = 'stashed' succeeded.append(str(key)) else: failed.append(str(key)) else: failed.append(str(key)) message = '' if len(succeeded) > 0: message += 'Stashed entries: {}.'.format(', '.join(succeeded)) status = 'success' if len(failed) > 0: message += '\nNo queued entry for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} return answer
<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_process(self, payload): """Pause the daemon and kill all processes or kill a specific process."""
# Kill specific processes, if `keys` is given in the payload kill_signal = signals[payload['signal'].lower()] kill_shell = payload.get('all', False) if payload.get('keys'): succeeded = [] failed = [] for key in payload.get('keys'): success = self.process_handler.kill_process(key, kill_signal, kill_shell) if success: succeeded.append(str(key)) else: failed.append(str(key)) message = '' if len(succeeded) > 0: message += "Signal '{}' sent to processes: {}.".format(payload['signal'], ', '.join(succeeded)) status = 'success' if len(failed) > 0: message += '\nNo running process for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} # Kill all processes and the daemon else: self.process_handler.kill_all(kill_signal, kill_shell) if kill_signal == signal.SIGINT or \ kill_signal == signal.SIGTERM or \ kill_signal == signal.SIGKILL: self.paused = True answer = {'message': 'Signal send to all processes.', 'status': 'success'} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, payload): """Remove specified entries from the queue."""
succeeded = [] failed = [] for key in payload['keys']: running = self.process_handler.is_running(key) if not running: removed = self.queue.remove(key) if removed: succeeded.append(str(key)) else: failed.append(str(key)) else: failed.append(str(key)) message = '' if len(succeeded) > 0: message += 'Removed entries: {}.'.format(', '.join(succeeded)) status = 'success' if len(failed) > 0: message += '\nRunning or non-existing entry for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} return answer
<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(self, payload): """Switch the two specified entry positions in the queue."""
first = payload['first'] second = payload['second'] running = self.process_handler.is_running(first) or self.process_handler.is_running(second) if running: answer = { 'message': "Can't switch running processes, " "please stop the processes before switching them.", 'status': 'error' } else: switched = self.queue.switch(first, second) if switched: answer = { 'message': 'Entries #{} and #{} switched'.format(first, second), 'status': 'success' } else: answer = {'message': "One or both entries do not exist or are not queued/stashed.", 'status': 'error'} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(self, payload): """Restart the specified entries."""
succeeded = [] failed = [] for key in payload['keys']: restarted = self.queue.restart(key) if restarted: succeeded.append(str(key)) else: failed.append(str(key)) message = '' if len(succeeded) > 0: message += 'Restarted entries: {}.'.format(', '.join(succeeded)) status = 'success' if len(failed) > 0: message += '\nNo finished entry for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} return answer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sendall(self, data, flags=0): '''Same as socket.sendall''' count = len(data) while count: sent = self.send(data, flags) # This could probably be a buffer object data = data[sent:] count -= sent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_file_show(client, args): """Output file contents to stdout"""
for src_uri in args.uris: client.download_file(src_uri, sys.stdout.buffer) 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 pub(self, topic, message): '''Publish a message to a topic''' return self.post('pub', params={'topic': topic}, data=message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mpub(self, topic, messages, binary=True): '''Send multiple messages to a topic. Optionally pack the messages''' if binary: # Pack and ship the data return self.post('mpub', data=pack(messages)[4:], params={'topic': topic, 'binary': True}) elif any('\n' in m for m in messages): # If any of the messages has a newline, then you must use the binary # calling format raise ClientException( 'Use `binary` flag in mpub for messages with newlines') else: return self.post( '/mpub', params={'topic': topic}, data='\n'.join(messages))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clean_stats(self): '''Stats with topics and channels keyed on topic and channel names''' stats = self.stats() if 'topics' in stats: # pragma: no branch topics = stats['topics'] topics = dict((t.pop('topic_name'), t) for t in topics) for topic, data in topics.items(): if 'channels' in data: # pragma: no branch channels = data['channels'] channels = dict( (c.pop('channel_name'), c) for c in channels) data['channels'] = channels stats['topics'] = topics return stats
<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_add(args, root_dir=None): """Add a new command to the daemon queue. Args: args['command'] (list(str)): The actual programm call. Something like ['ls', '-a'] or ['ls -al'] root_dir (string): The path to the root directory the daemon is running in. """
# We accept a list of strings. # This is done to create a better commandline experience with argparse. command = ' '.join(args['command']) # Send new instruction to daemon instruction = { 'command': command, 'path': os.getcwd() } print_command_factory('add')(instruction, root_dir)
<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_edit(args, root_dir=None): """Edit a existing queue command in the daemon. Args: args['key'] int: The key of the queue entry to be edited root_dir (string): The path to the root directory the daemon is running in. """
# Get editor EDITOR = os.environ.get('EDITOR', 'vim') # Get command from server key = args['key'] status = command_factory('status')({}, root_dir=root_dir) # Check if queue is not empty, the entry exists and is queued or stashed if not isinstance(status['data'], str) and key in status['data']: if status['data'][key]['status'] in ['queued', 'stashed']: command = status['data'][key]['command'] else: print("Entry is not 'queued' or 'stashed'") sys.exit(1) else: print('No entry with this key') sys.exit(1) with tempfile.NamedTemporaryFile(suffix=".tmp") as tf: tf.write(command.encode('utf-8')) tf.flush() call([EDITOR, tf.name]) # do the parsing with `tf` using regular File operations. # for instance: tf.seek(0) edited_command = tf.read().decode('utf-8') print_command_factory('edit')({ 'key': key, 'command': edited_command, }, root_dir=root_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_factory(command): """A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to the daemon and returns the unpickled object which is returned by the daemon. Args: command (string): The type of payload this should be. This determines as what kind of instruction this will be interpreted by the daemon. Returns: function: The created function. """
def communicate(body={}, root_dir=None): """Communicate with the daemon. This function sends a payload to the daemon and returns the unpickled object sent by the daemon. Args: body (dir): Any other arguments that should be put into the payload. root_dir (str): The root directory in which we expect the daemon. We need this to connect to the daemons socket. Returns: function: The returned payload. """ client = connect_socket(root_dir) body['mode'] = command # Delete the func entry we use to call the correct function with argparse # as functions can't be pickled and this shouldn't be send to the daemon. if 'func' in body: del body['func'] data_string = pickle.dumps(body, -1) client.send(data_string) # Receive message, unpickle and return it response = receive_data(client) return response return communicate
<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_descriptor(self, number): """Create file descriptors for process output."""
# Create stdout file and get file descriptor stdout_path = os.path.join(self.config_dir, 'pueue_process_{}.stdout'.format(number)) if os.path.exists(stdout_path): os.remove(stdout_path) out_descriptor = open(stdout_path, 'w+') # Create stderr file and get file descriptor stderr_path = os.path.join(self.config_dir, 'pueue_process_{}.stderr'.format(number)) if os.path.exists(stderr_path): os.remove(stderr_path) err_descriptor = open(stderr_path, 'w+') self.descriptors[number] = {} self.descriptors[number]['stdout'] = out_descriptor self.descriptors[number]['stdout_path'] = stdout_path self.descriptors[number]['stderr'] = err_descriptor self.descriptors[number]['stderr_path'] = stderr_path return out_descriptor, err_descriptor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_descriptor(self, number): """Close file descriptor and remove underlying files."""
self.descriptors[number]['stdout'].close() self.descriptors[number]['stderr'].close() if os.path.exists(self.descriptors[number]['stdout_path']): os.remove(self.descriptors[number]['stdout_path']) if os.path.exists(self.descriptors[number]['stderr_path']): os.remove(self.descriptors[number]['stderr_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 check_finished(self): """Poll all processes and handle any finished processes."""
changed = False for key in list(self.processes.keys()): # Poll process and check if it finshed process = self.processes[key] process.poll() if process.returncode is not None: # If a process is terminated by `stop` or `kill` # we want to queue it again instead closing it as failed. if key not in self.stopping: # Get std_out and err_out output, error_output = process.communicate() descriptor = self.descriptors[key] descriptor['stdout'].seek(0) descriptor['stderr'].seek(0) output = get_descriptor_output(descriptor['stdout'], key, handler=self) error_output = get_descriptor_output(descriptor['stderr'], key, handler=self) # Mark queue entry as finished and save returncode self.queue[key]['returncode'] = process.returncode if process.returncode != 0: self.queue[key]['status'] = 'failed' else: self.queue[key]['status'] = 'done' # Add outputs to queue self.queue[key]['stdout'] = output self.queue[key]['stderr'] = error_output self.queue[key]['end'] = str(datetime.now().strftime("%H:%M")) self.queue.write() changed = True else: self.stopping.remove(key) if key in self.to_remove: self.to_remove.remove(key) del self.queue[key] else: if key in self.to_stash: self.to_stash.remove(key) self.queue[key]['status'] = 'stashed' else: self.queue[key]['status'] = 'queued' self.queue[key]['start'] = '' self.queue[key]['end'] = '' self.queue.write() self.clean_descriptor(key) del self.processes[key] # If anything should be logged we return True return changed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_new(self): """Check if we can start a new process."""
free_slots = self.max_processes - len(self.processes) for item in range(free_slots): key = self.queue.next() if key is not None: self.spawn_new(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 spawn_new(self, key): """Spawn a new task and save it to the queue."""
# Check if path exists if not os.path.exists(self.queue[key]['path']): self.queue[key]['status'] = 'failed' error_msg = "The directory for this command doesn't exist anymore: {}".format(self.queue[key]['path']) self.logger.error(error_msg) self.queue[key]['stdout'] = '' self.queue[key]['stderr'] = error_msg else: # Get file descriptors stdout, stderr = self.get_descriptor(key) if self.custom_shell != 'default': # Create subprocess self.processes[key] = subprocess.Popen( [ self.custom_shell, '-i', '-c', self.queue[key]['command'], ], stdout=stdout, stderr=stderr, stdin=subprocess.PIPE, universal_newlines=True, preexec_fn=os.setsid, cwd=self.queue[key]['path'] ) else: # Create subprocess self.processes[key] = subprocess.Popen( self.queue[key]['command'], shell=True, stdout=stdout, stderr=stderr, stdin=subprocess.PIPE, universal_newlines=True, preexec_fn=os.setsid, cwd=self.queue[key]['path'] ) self.queue[key]['status'] = 'running' self.queue[key]['start'] = str(datetime.now().strftime("%H:%M")) self.queue.write()
<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_all(self, kill_signal, kill_shell=False): """Kill all running processes."""
for key in self.processes.keys(): self.kill_process(key, kill_signal, kill_shell)