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 datetime_value_renderer(value, **options): """Render datetime value with django formats, default is SHORT_DATETIME_FORMAT"""
datetime_format = options.get('datetime_format', 'SHORT_DATETIME_FORMAT') return formats.date_format(timezone.localtime(value), datetime_format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def price_value_renderer(value, currency=None, **options): """Format price value, with current locale and CURRENCY in settings"""
if not currency: currency = getattr(settings, 'CURRENCY', 'USD') return format_currency(value, currency, locale=utils.get_current_locale())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce(self, show_noisy=False): """ Yield the reduced log lines :param show_noisy: If this is true, shows the reduced log file. If this is false, it shows the logs that were deleted. """
if not show_noisy: for log in self.quiet_logs: yield log['raw'].strip() else: for log in self.noisy_logs: yield log['raw'].strip()
<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_filter(self, features): """ Gets the filter for the features in the object :param features: The features of the syslog file """
# This chops the features up into smaller lists so the api can handle them for ip_batch in (features['ips'][pos:pos + self.ip_query_batch_size] for pos in six.moves.range(0, len(features['ips']), self.ip_query_batch_size)): # Query for each chunk and add it to the filter list query = {'ips': ip_batch, 'ports': features['ports']} self.filter['ips'] += self._send_features(query)['ips']
<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_features(self, features): """ Send a query to the backend api with a list of observed features in this log file :param features: Features found in the log file :return: Response text from ThreshingFloor API """
# Hit the auth endpoint with a list of features try: r = requests.post(self.base_uri + self.api_endpoint, json=features, headers={'x-api-key': self.api_key}) except requests.exceptions.ConnectionError: raise TFAPIUnavailable("The ThreshingFloor API appears to be unavailable.") if r.status_code != 200: sys.stderr.write("%s\n" % r.text) raise TFAPIUnavailable("Request failed and returned a status of: {STATUS_CODE}" .format(STATUS_CODE=r.status_code)) return json.loads(r.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 clean_out_dir(directory): """ Delete all the files and subdirectories in a directory. """
if not isinstance(directory, path): directory = path(directory) for file_path in directory.files(): file_path.remove() for dir_path in directory.dirs(): dir_path.rmtree()
<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_zip(archive, dest=None, members=None): """Extract the ZipInfo object to a real file on the path targetpath."""
# Python 2.5 compatibility. dest = dest or os.getcwd() members = members or archive.infolist() for member in members: if isinstance(member, basestring): member = archive.getinfo(member) _extract_zip_member(archive, member, dest)
<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_parser(): """Returns a new option parser."""
p = optparse.OptionParser() p.add_option('--prefix', metavar='DIR', help='install SDK in DIR') p.add_option('--bindir', metavar='DIR', help='install tools in DIR') p.add_option('--force', action='store_true', default=False, help='over-write existing installation') p.add_option('--no-bindir', action='store_true', default=False, help='do not install tools on DIR') return p
<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_version(url=VERSION_URL): """Returns the version string for the latest SDK."""
for line in get(url): if 'release:' in line: return line.split(':')[-1].strip(' \'"\r\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 parse_sdk_name(name): """Returns a filename or URL for the SDK name. The name can be a version string, a remote URL or a local path. """
# Version like x.y.z, return as-is. if all(part.isdigit() for part in name.split('.', 2)): return DOWNLOAD_URL % name # A network location. url = urlparse.urlparse(name) if url.scheme: return name # Else must be a filename. return os.path.abspath(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 open_sdk(url): """Open the SDK from the URL, which can be either a network location or a filename path. Returns a file-like object open for reading. """
if urlparse.urlparse(url).scheme: return _download(url) else: return open(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reset(self): '''Reset stream.''' self._text = None self._markdown = False self._channel = Incoming.DEFAULT_CHANNEL self._attachments = [] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def with_text(self, text, markdown=None): '''Set text content. :param text: text content. :param markdown: is markdown? Defaults to ``False``. ''' self._text = text self._markdown = markdown or False return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def push(self): '''Deliver the message.''' message = self.build_message() return requests.post(self.hook, json=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 create(self, key, *args, **kwargs): """ Creates and inserts an identified object with the passed params using the specified class. """
instance = self._class(key, *args, **kwargs) self._events.create.trigger(list=self, instance=instance, key=key, args=args, kwargs=kwargs) return self.insert(instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, identified): """ Inserts an already-created identified object of the expected class. """
if not isinstance(identified, self._class): raise self.Error("Passed instance is not of the needed class", self.Error.INVALID_INSTANCE_CLASS, instance=identified) try: if self._objects[identified.key] != identified: raise self.Error("Passes instance's key '%s' is already occupied" % identified.key, self.Error.KEY_EXISTS, key=identified.key, instance=identified) except KeyError: self._objects[identified.key] = identified self._events.insert.trigger(list=self, instance=identified) return identified
<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, identified): """ Removes an already-created identified object. A key may be passed instead of an identified object. If an object is passed, and its key is held by another object inside the record, an error is triggered. Returns the removed object. """
by_val = isinstance(identified, Identified) if by_val: key = identified.key if not isinstance(identified, self._class): raise self.Error("Such instance could never exist here", self.Error.INVALID_INSTANCE_CLASS, instance=identified) else: key = identified try: popped = self._objects.pop(key) if by_val and popped != identified: raise self.Error("Trying to pop a different object which also has key '%s'" % popped.key, self.Error.NOT_SAME_OBJECT, instance=identified, current=popped) self._events.remove.trigger(list=self, instance=identified, by_val=by_val) except KeyError: raise self.Error("No object with key '%s' exists here", self.Error.KEY_NOT_EXISTS, key=key, instance=identified if by_val else 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 timeout_deferred(deferred, timeout, error_message="Timeout occured"): """ Waits a given time, if the given deferred hasn't called back by then we cancel it. If the deferred was cancelled by the timeout, a `TimeoutError` error is produced. Returns `deferred`. """
timeout_occured = [False] def got_result(result): if not timeout_occured[0]: # Deferred called back before the timeout. delayedCall.cancel() return result else: if isinstance(result, failure.Failure) and result.check(defer.CancelledError): # Got a `CancelledError` after we called `cancel()`. # Replace it with a `TimeoutError`. raise TimeoutError(error_message) else: # Apparently the given deferred has something else to tell us. # It might be that it completed before the `cancel()` had an effect # (or as a result thereof). It might also be that it triggered an # error. In either case, we want this to be visible down-stream. return result def time_is_up(): timeout_occured[0] = True deferred.cancel() delayedCall = reactor.callLater(timeout, time_is_up) deferred.addBoth(got_result) return deferred
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def http_auth(self): """ Returns ``True`` if valid http auth credentials are found in the request header. """
if 'HTTP_AUTHORIZATION' in self.request.META.keys(): authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split( ' ', 1) if authmeth.lower() == 'basic': auth = auth.strip().decode('base64') identifier, password = auth.split(':', 1) username = get_username(identifier) user = authenticate(username=username, password=password) if user: login(self.request, user) 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 init(self, db=RDB_DB, host=RDB_HOST, port=RDB_PORT): """Create the Frink object to store the connection credentials."""
self.RDB_HOST = host self.RDB_PORT = port self.RDB_DB = db from .connection import RethinkDB self.rdb = RethinkDB() self.rdb.init()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_value(text): """ This removes newlines and multiple spaces from a string. """
result = text.replace('\n', ' ') result = re.subn('[ ]{2,}', ' ', result)[0] return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """
name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, 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 parse_entry(source, loc, tokens): """ Converts the tokens of an entry into an Entry instance. If no applicable type is available, an UnsupportedEntryType exception is raised. """
type_ = tokens[1].lower() entry_type = structures.TypeRegistry.get_type(type_) if entry_type is None or not issubclass(entry_type, structures.Entry): raise exceptions.UnsupportedEntryType( "%s is not a supported entry type" % type_ ) new_entry = entry_type() new_entry.name = tokens[3] for key, value in [t for t in tokens[4:-1] if t != ',']: new_entry[key] = value return new_entry
<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_bibliography(source, loc, tokens): """ Combines the parsed entries into a Bibliography instance. """
bib = structures.Bibliography() for entry in tokens: bib.add(entry) return bib
<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_string(str_, validate=False): """ Tries to parse a given string into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules. """
result = pattern.parseString(str_)[0] if validate: result.validate() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_file(file_or_path, encoding='utf-8', validate=False): """ Tries to parse a given filepath or fileobj into a Bibliography instance. If ``validate`` is passed as keyword argument and set to ``True``, the Bibliography will be validated using the standard rules. """
try: is_string = isinstance(file_or_path, basestring) except NameError: is_string = isinstance(file_or_path, str) if is_string: with codecs.open(file_or_path, 'r', encoding) as file_: result = pattern.parseFile(file_)[0] else: result = pattern.parseFile(file_or_path)[0] if validate: result.validate() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def track_end(self): """ Ends tracking of attributes changes. Returns the changes that occurred to the attributes. Only the final state of each attribute is obtained """
self.__tracking = False changes = self.__changes self.__changes = {} return changes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def creationTime(item): """ Returns the creation time of the given item. """
forThisItem = _CreationTime.createdItem == item return item.store.findUnique(_CreationTime, forThisItem).timestamp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def access_key(root, key, sep='.', default=None): ''' Look up a key in a potentially nested object `root` by its `sep`-separated path. Returns `default` if the key is not found. Example: access_key({'foo': {'bar': 1}}, 'foo.bar') -> 1 ''' props = key.split('.') props.reverse() while props and root: prop = props.pop() root = access(root, prop, default=default) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dispatch(argdict): '''Call the command-specific function, depending on the command.''' cmd = argdict['command'] ftc = getattr(THIS_MODULE, 'do_'+cmd) ftc(argdict)
<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_init(argdict): '''Create the structure of a s2site.''' site = make_site_obj(argdict) try: site.init_structure() print "Initialized directory." if argdict['randomsite']: #all_tags = ['tag1','tag2','tag3','tag4'] for i in range(1,argdict['numpages']+1): #ptags = random.sample(all_tags,random.randint(1,len(all_tags))) p = site.random_page() p.set_published() p.write() print "added page ",p.slug except ValueError: # pragma: no cover print "Cannot create structure. You're already within an s2 \ tree, or the directory is not empty or it is not writeable. "
<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_add(argdict): '''Add a new page to the site.''' site = make_site_obj(argdict) if not site.tree_ready: print "Cannot add page. You are not within a simplystatic \ tree and you didn't specify a directory." sys.exit() title = argdict['title'] try: new_page = site.add_page(title) new_page.write() print "Added page '"+ title + "'" except ValueError as e: # pragma: no cover print "Attempted to create a page which already exists." sys.exit()
<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_rename(argdict): '''Rename a page.''' site = make_site_obj(argdict) slug = argdict['slug'] newtitle = argdict['newtitle'] try: site.rename_page(slug, newtitle) print "Renamed page." except ValueError: # pragma: no cover print "Cannot rename. A page with the given slug does not exist." sys.exit()
<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_gen(argdict): '''Generate the whole site.''' site = make_site_obj(argdict) try: st = time.time() site.generate() et = time.time() print "Generated Site in %f seconds."% (et-st) except ValueError as e: # pragma: no cover print "Cannot generate. You are not within a simplystatic \ tree and you didn't specify a directory."
<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_ls(argdict): '''List pages.''' site = make_site_obj(argdict) if not site.tree_ready: print "Cannot list pages. You are not within a simplystatic \ tree and you didn't specify a directory." sys.exit() drafts = argdict['drafts'] recent = argdict['recent'] dir = site.dirs['source'] r = site.get_page_names() if drafts: fr = [os.path.join(dir,pn , pn+".md") for pn in r] cpat = re.compile('status:\s+draft') #compiled pattern i=0 print '' for f in fr: fcontent = open(f,'r').read().lower() res = cpat.search(fcontent) if res: print r[i] i += 1 print '' else: if recent: fr = [os.path.join(dir,pn , pn+".md") for pn in r] bmt = 0 i = 0 for f in fr: mt = os.path.getmtime(f) if mt > bmt: bmt = mt fname = r[i] i += 1 print '\n' + fname + '\n' else: print '\n' + '\n'.join(r) + '\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 register(self, schema): """Register input schema class. When registering a schema, all inner schemas are registered as well. :param Schema schema: schema to register. :return: old registered schema. :rtype: type """
result = None uuid = schema.uuid if uuid in self._schbyuuid: result = self._schbyuuid[uuid] if result != schema: self._schbyuuid[uuid] = schema name = schema.name schemas = self._schbyname.setdefault(name, set()) schemas.add(schema) for innername, innerschema in iteritems(schema.getschemas()): if innerschema.uuid not in self._schbyuuid: register(innerschema) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def registercls(self, data_types, schemacls=None): """Register schema class with associated data_types. Can be used such as a decorator. :param list data_types: data types to associate with schema class. :param type schemacls: schema class to register. :return: schemacls. :rtype: type """
if schemacls is None: return lambda schemacls: self.registercls( data_types=data_types, schemacls=schemacls ) for data_type in data_types: self._schbytype[data_type] = schemacls return schemacls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, uuid): """Unregister a schema registered with input uuid. :raises: KeyError if uuid is not already registered. """
schema = self._schbyuuid.pop(uuid) # clean schemas by name self._schbyname[schema.name].remove(schema) if not self._schbyname[schema.name]: del self._schbyname[schema.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 getbyuuid(self, uuid): """Get a schema by given uuid. :param str uuid: schema uuid to retrieve. :rtype: Schema :raises: KeyError if uuid is not registered already. """
if uuid not in self._schbyuuid: raise KeyError('uuid {0} not registered'.format(uuid)) return self._schbyuuid[uuid]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getbyname(self, name): """Get schemas by given name. :param str name: schema names to retrieve. :rtype: list :raises: KeyError if name is not registered already. """
if name not in self._schbyname: raise KeyError('name {0} not registered'.format(name)) return self._schbyname[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 truncate_table(self, tablename): """ SQLite3 doesn't support direct truncate, so we just use delete here """
self.get(tablename).remove() self.db.commit()
<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, level="WARN"): """ Start logging with this logger. Until the logger is started, no messages will be emitted. This applies to all loggers with the same name and any child loggers. Messages less than the given priority level will be ignored. The default level is 'WARN', which conforms to the *nix convention that a successful run should produce no diagnostic output. Available levels and their suggested meanings: DEBUG - output useful for developers INFO - trace normal program flow, especially external interactions WARN - an abnormal condition was detected that might need attention ERROR - an error was detected but execution continued CRITICAL - an error was detected and execution was halted """
if self.active: return handler = StreamHandler() # stderr handler.setFormatter(Formatter(self.LOGFMT)) self.addHandler(handler) self.setLevel(level.upper()) self.active = True 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 stop(self): """ Stop logging with this logger. """
if not self.active: return self.removeHandler(self.handlers[-1]) self.active = False 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 parse_line(string): """Parse a single string as traceback line"""
match = line_regexp().match(string) if match: matches = match.groupdict() line_number = matches['line_number'] path_to_python = matches['path_to_python'] spaceless_path_to_python = matches['spaceless_path_to_python'] if path_to_python: return path_to_python, line_number elif spaceless_path_to_python: return spaceless_path_to_python, line_number
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sftp_upload_window_size_set(srv,file, method_to_call='put'): ''' sets config for uploading files with pysftp ''' channel = srv.sftp_client.get_channel() channel.lock.acquire() channel.out_window_size += os.stat(file).st_size * 1.1 # bit more bytes incase packet loss channel.out_buffer_cv.notifyAll() channel.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 plotit(self): ''' Produce the plots requested in the Dynac input file. This makes the same plots as produced by the Dynac ``plotit`` command. ''' [self._plot(i) for i in range(len(self.plots))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def multiplypub(pub,priv,outcompressed=True): ''' Input pubkey must be hex string and valid pubkey. Input privkey must be 64-char hex string. Pubkey input can be compressed or uncompressed, as long as it's a valid key and a hex string. Use the validatepubkey() function to validate the public key first. The compression of the input public key does not do anything or matter in any way. ''' if len(pub) == 66: pub = uncompress(pub) x, y = ecmultiply(int(pub[2:66],16),int(pub[66:],16),int(priv,16)) x = dechex(x,32) y = dechex(y,32) o = '04' + x + y if outcompressed: return compress(o) else: return o
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def validatepubkey(pub): ''' Returns input key if it's a valid hex public key, or False otherwise. Input must be hex string, not bytes or integer/long or anything else. ''' try: pub = hexstrlify(unhexlify(pub)) except: return False if len(pub) == 130: if pub[:2] != '04': return False if uncompress(compress(pub)) != pub: return False elif len(pub) == 66: if pub[:2] != '02' and pub[:2] != '03': return False else: return False return pub
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def privtohex(key): ''' Used for getting unknown input type into a private key. For example, if you ask a user to input a private key, and they may input hex, WIF, integer, etc. Run it through this function to get a standardized format. Function either outputs private key hex string or raises an exception. It's really going to try to make any input into a private key, so make sure that whatever you import is indeed supposed to be a private key. For example, if you put an int in, it will turn that into a key. Make sure you want a key when you use this function!!! ''' if isitint(key): key = dechex(key,32) else: try: key, z, zz = wiftohex(key) assert len(key) == 64 except: try: key = unhexlify(key) except: try: key1 = hexstrlify(key) assert len(key1) == 64 or len(key1) == 66 or len(key1) == 68 if len(key1) == 68: assert key1[-2:] == '01' key = key1 except: raise Exception("Cannot interpret input key.") else: key = hexstrlify(key) if len(key) == 68: assert key[-2:] == '01' key = key[:-2] if len(key) == 66: key = key[2:] assert len(key) == 64 return 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 conjugate_quat(quat): """Negate the vector part of the quaternion."""
return Quat(-quat.x, -quat.y, -quat.z, quat.w)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lerp_quat(from_quat, to_quat, percent): """Return linear interpolation of two quaternions."""
# Check if signs need to be reversed. if dot_quat(from_quat, to_quat) < 0.0: to_sign = -1 else: to_sign = 1 # Simple linear interpolation percent_from = 1.0 - percent percent_to = percent result = Quat( percent_from * from_quat.x + to_sign * percent_to * to_quat.x, percent_from * from_quat.y + to_sign * percent_to * to_quat.y, percent_from * from_quat.z + to_sign * percent_to * to_quat.z, percent_from * from_quat.w + to_sign * percent_to * to_quat.w) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nlerp_quat(from_quat, to_quat, percent): """Return normalized linear interpolation of two quaternions. Less computationally expensive than slerp (which not implemented in this lib yet), but does not maintain a constant velocity like slerp. """
result = lerp_quat(from_quat, to_quat, percent) result.normalize() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repeat_func(func: Callable[[], Union[T, Awaitable[T]]], times: int=None, *, interval: float=0) -> AsyncIterator[T]: """ Repeats the result of a 0-ary function either indefinitely, or for a defined number of times. `times` and `interval` behave exactly like with `aiostream.create.repeat`. A useful idiom is to combine an indefinite `repeat_func` stream with `aiostream.select.takewhile` to terminate the stream at some point. """
base = stream.repeat.raw((), times, interval=interval) return cast(AsyncIterator[T], stream.starmap.raw(base, func, task_limit=1))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repeat_func_eof(func: Callable[[], Union[T, Awaitable[T]]], eof: Any, *, interval: float=0, use_is: bool=False) -> AsyncIterator[T]: """ Repeats the result of a 0-ary function until an `eof` item is reached. The `eof` item itself is not part of the resulting stream; by setting `use_is` to true, eof is checked by identity rather than equality. `times` and `interval` behave exactly like with `aiostream.create.repeat`. """
pred = (lambda item: item != eof) if not use_is else (lambda item: (item is not eof)) base = repeat_func.raw(func, interval=interval) return cast(AsyncIterator[T], stream.takewhile.raw(base, pred))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stringlist(*args): """ Take a lists of strings or strings and flatten these into a list of strings. Arguments: Exceptions: None """
return list(itertools.chain.from_iterable(itertools.repeat(x,1) if stringy(x) else x for x in args if x))
<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_outgoing_mail(sender, to, msgstring): """ Parse an outgoing mail and put it into the OUTBOX. Arguments: - `sender`: str - `to`: str - `msgstring`: str Return: None Exceptions: None """
global OUTBOX OUTBOX.append(email.message_from_string(msgstring)) 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 as_msg(self): """ Convert ourself to be a message part of the appropriate MIME type. Return: MIMEBase Exceptions: None """
# Based upon http://docs.python.org/2/library/email-examples.html # with minimal tweaking # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(str(self.path)) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(self.path.read(), _subtype=subtype) elif maintype == 'image': fp = self.path.open('rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = self.path.open('rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = self.path.open('rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) filename = str(self.path[-1]) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tolist(self, to): """ Make sure that our addressees are a unicoded list Arguments: - `to`: str or list Exceptions: None """
return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None): """ Sanity check the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError Arguments: - `sender`: str - `to`: list - `subject`: str - `plain`: str - `html`: str Return: None Exceptions: NoContentError """
if not plain and not html: raise NoContentError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_tpl(self, name, extension='.jinja2'): """ Return a Path object representing the Template we're after, searching SELF.tpls or None Arguments: - `name`: str Return: Path or None Exceptions: None """
found = None for loc in self.tpls: if not loc: continue contents = [f for f in loc.ls() if f.find(name) != -1 and f.endswith(extension)] if contents: found = contents[0] break exact = loc + (name + extension) if exact.is_file: found = exact 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 _find_tpls(self, name): """ Return plain, html templates for NAME Arguments: - `name`: str Return: tuple Exceptions: None """
return self._find_tpl(name, extension='.txt'), self._find_tpl(name, extension='.html')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sendtpl(self, sender, to, subject, cc=None, bcc=None, attach=None, replyto=None, **kwargs): """ Send a Letter from SENDER to TO, with the subject SUBJECT. Use the current template, with KWARGS as the context. Arguments: - `sender`: unicode - `to`: unicode - `subject`: unicode - `cc`: str or [str] - `bcc`: str or [str] - `replyto`: str - `**kwargs`: objects Return: None Exceptions: None """
plain, html = self.body(**kwargs) self.mailer.send(sender, to, subject, plain=plain, html=html, cc=cc, bcc=bcc, replyto=replyto, attach=attach) 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 body(self, **kwargs): """ Return the plain and html versions of our contents. Return: tuple Exceptions: None """
text_content, html_content = None, None if self.plain: text_content = mold.cast(self.plain, **kwargs) if self.html: html_content = mold.cast(self.html, **kwargs) return text_content, html_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 template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """
self.plain, self.html = self._find_tpls(name) if not self.plain: self.plain = self._find_tpl(name) try: self.send = self._sendtpl yield finally: self.plain, self.html = None, None self.send = self._send
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def environment(self): '''Get raw data about this worker. This is recorded in the :meth:`heartbeat` info, and can be retrieved by :meth:`TaskMaster.get_heartbeat`. The dictionary includes keys ``worker_id``, ``host``, ``fqdn``, ``version``, ``working_set``, and ``memory``. ''' hostname = socket.gethostname() aliases = () ipaddrs = () # This sequence isn't 100% reliable. We might try a socket() # sequence like RedisBase._ipaddress(), or just decide that # socket.fqdn() and/or socket.gethostname() is good enough. try: ip = socket.gethostbyname(hostname) except socket.herror: # If you're here, then $(hostname) doesn't resolve. ip = None try: if ip is not None: hostname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.herror: # If you're here, then $(hostname) resolves, but the IP # address that results in doesn't reverse-resolve. This # has been observed on OSX at least. ipaddrs = (ip,) env = dict( worker_id=self.worker_id, parent=self.parent, hostname=hostname, aliases=tuple(aliases), ipaddrs=tuple(ipaddrs), fqdn=socket.getfqdn(), version=pkg_resources.get_distribution("rejester").version, # pylint: disable=E1103 working_set=[(dist.key, dist.version) for dist in pkg_resources.WorkingSet()], # pylint: disable=E1103 # config_hash=self.config['config_hash'], # config_json = self.config['config_json'], memory=psutil.virtual_memory(), pid=os.getpid(), ) return env
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def register(self, parent=None): '''Record the availability of this worker and get a unique identifer. This sets :attr:`worker_id` and calls :meth:`heartbeat`. This cannot be called multiple times without calling :meth:`unregister` in between. ''' if self.worker_id: raise ProgrammerError('Worker.register cannot be called again without first calling unregister; it is not idempotent') self.parent = parent self.worker_id = nice_identifier() self.task_master.worker_id = self.worker_id self.heartbeat() return self.worker_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unregister(self): '''Remove this worker from the list of available workers. This requires the worker to already have been :meth:`register()`. ''' self.task_master.worker_unregister(self.worker_id) self.task_master.worker_id = None self.worker_id = 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 heartbeat(self): '''Record the current worker state in the registry. This records the worker's current mode, plus the contents of :meth:`environment`, in the data store for inspection by others. :returns mode: Current mode, as :meth:`TaskMaster.get_mode` ''' mode = self.task_master.get_mode() self.task_master.worker_heartbeat(self.worker_id, mode, self.lifetime, self.environment(), parent=self.parent) return mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def spec(self): '''Actual work spec. This is retrieved from the database on first use, and in some cases a worker can be mildly more efficient if it avoids using this. ''' if self._spec_cache is None: self._spec_cache = self.registry.get( WORK_SPECS, self.work_spec_name) return self._spec_cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def module(self): '''Python module to run the job. This is used by :func:`run` and the standard worker system. If the work spec contains keys ``module``, ``run_function``, and ``terminate_function``, then this contains the Python module object named as ``module``; otherwise this contains :const:`None`. ''' if self._module_cache is None: funclist = filter(None, (self.spec.get('run_function'), self.spec.get('terminate_function'))) if funclist: try: self._module_cache = __import__( self.spec['module'], globals(), (), funclist, -1) except Exception: logger.error('failed to load spec["module"] = %r', self.spec['module'], exc_info=True) raise return self._module_cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self): '''Actually runs the work unit. This is called by the standard worker system, generally once per work unit. It requires the work spec to contain keys ``module``, ``run_function``, and ``terminate_function``. It looks up ``run_function`` in :attr:`module` and calls that function with :const:`self` as its only parameter. ''' try: logger.info('running work unit {0}'.format(self.key)) run_function = getattr(self.module, self.spec['run_function']) ret_val = run_function(self) self.update() logger.info('completed work unit {0}'.format(self.key)) return ret_val except LostLease: logger.warning('work unit {0} timed out'.format(self.key)) raise except Exception: logger.error('work unit {0} failed'.format(self.key), exc_info=True) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def terminate(self): '''Kills the work unit. This is called by the standard worker system, but only in response to an operating system signal. If the job does setup such as creating a child process, its terminate function should kill that child process. More specifically, this function requires the work spec to contain the keys ``module``, ``run_function``, and ``terminate_function``, and calls ``terminate_function`` in :attr:`module` containing :const:`self` as its only parameter. ''' terminate_function_name = self.spec.get('terminate_function') if not terminate_function_name: logger.error('tried to terminate WorkUnit(%r) but no ' 'function name', self.key) return None terminate_function = getattr(self.module, self.spec['terminate_function']) if not terminate_function: logger.error('tried to terminate WorkUnit(%r) but no ' 'function %s in module %r', self.key, terminate_function_name, self.module.__name__) return None logger.info('calling terminate function for work unit {0}' .format(self.key)) ret_val = terminate_function(self) self.update(lease_time=-10) return ret_val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _refresh(self, session, stopping=False): '''Get this task's current state. This must be called under the registry's lock. It updates the :attr:`finished` and :attr:`failed` flags and the :attr:`data` dictionary based on the current state in the registry. In the normal case, nothing will change and this function will return normally. If it turns out that the work unit is already finished, the state of this object will change before :exc:`rejester.exceptions.LostLease` is raised. :param session: locked registry session :param stopping: don't raise if the work unit is finished :raises rejester.exceptions.LostLease: if this worker is no longer doing this work unit ''' data = session.get( WORK_UNITS_ + self.work_spec_name + _FINISHED, self.key) if data is not None: self.finished = True self.data = data if not stopping: raise LostLease('work unit is already finished') return self.finished = False data = session.get( WORK_UNITS_ + self.work_spec_name + _FAILED, self.key) if data is not None: self.failed = True self.data = data if not stopping: raise LostLease('work unit has already failed') return self.failed = False # (You need a pretty specific sequence of events to get here) data = session.get( WORK_UNITS_ + self.work_spec_name + _BLOCKED, self.key) if data is not None: self.data = data raise LostLease('work unit now blocked by others') worker_id = session.get( WORK_UNITS_ + self.work_spec_name + '_locks', self.key) if worker_id != self.worker_id: raise LostLease('work unit claimed by %r', worker_id) # NB: We could check the priority here, but don't. # If at this point we're technically overtime but nobody # else has started doing work yet, since we're under the # global lock, we can get away with finishing whatever # transition we were going to try to do. data = session.get( WORK_UNITS_ + self.work_spec_name, self.key) if data is None: raise NoSuchWorkUnitError('work unit is gone') # Since we should still own the work unit, any changes # in data should be on our end; do not touch it 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 update(self, lease_time=None): '''Refresh this task's expiration time. This tries to set the task's expiration time to the current time, plus `lease_time` seconds. It requires the job to not already be complete. If `lease_time` is negative, makes the job immediately be available for other workers to run. :param int lease_time: time to extend job lease beyond now :raises rejester.exceptions.LostLease: if the lease has already expired ''' if lease_time is None: lease_time = self.default_lifetime with self.registry.lock(identifier=self.worker_id) as session: self._refresh(session) try: self.expires = time.time() + lease_time session.update( WORK_UNITS_ + self.work_spec_name, {self.key: self.data}, priorities={self.key: self.expires}, locks={self.key: self.worker_id}) except EnvironmentError, exc: raise LostLease(exc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def finish(self): '''Move this work unit to a finished state. In the standard worker system, the worker calls this on the job's behalf when :meth:`run_function` returns successfully. :raises rejester.exceptions.LostLease: if the lease has already expired ''' with self.registry.lock(identifier=self.worker_id) as session: self._refresh(session, stopping=True) if self.finished or self.failed: return session.move( WORK_UNITS_ + self.work_spec_name, WORK_UNITS_ + self.work_spec_name + _FINISHED, {self.key: self.data}) session.popmany( WORK_UNITS_ + self.work_spec_name + '_locks', self.key, self.worker_id) blocks = session.get( WORK_UNITS_ + self.work_spec_name + _BLOCKS, self.key) if blocks is not None: for block in blocks: spec = block[0] unit = block[1] # hard = block[2] depends = session.get(WORK_UNITS_ + spec + _DEPENDS, unit) if depends is None: continue depends.remove([self.work_spec_name, self.key]) if len(depends) == 0: session.popmany(WORK_UNITS_ + spec + _DEPENDS, unit) unitdef = session.get(WORK_UNITS_ + spec + _BLOCKED, unit) session.move(WORK_UNITS_ + spec + _BLOCKED, WORK_UNITS_ + spec, {unit: unitdef}) else: session.set(WORK_UNITS_ + spec + _DEPENDS, unit, depends) self.finished = 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 fail(self, exc=None): '''Move this work unit to a failed state. In the standard worker system, the worker calls this on the job's behalf when :meth:`run_function` ends with any exception: .. code-block:: python try: work_unit.run() work_unit.finish() except Exception, e: work_unit.fail(e) A ``traceback`` property is recorded with a formatted version of `exc`, if any. :param exc: Exception that caused the failure, or :const:`None` :raises rejester.exceptions.LostLease: if the lease has already expired ''' with self.registry.lock(identifier=self.worker_id) as session: self._refresh(session, stopping=True) if self.finished or self.failed: return if exc: self.data['traceback'] = traceback.format_exc(exc) else: self.data['traceback'] = None session.move( WORK_UNITS_ + self.work_spec_name, WORK_UNITS_ + self.work_spec_name + _FAILED, {self.key: self.data}) session.popmany( WORK_UNITS_ + self.work_spec_name + '_locks', self.key, self.worker_id) blocks = session.get(WORK_UNITS_ + self.work_spec_name + _BLOCKS, self.key) if blocks is not None: for block in blocks: spec = block[0] unit = block[1] hard = block[2] if hard: session.popmany(WORK_UNITS_ + spec + _DEPENDS, unit) unitdef = session.get(WORK_UNITS_ + spec + _BLOCKED, unit) if unitdef is not None: session.move(WORK_UNITS_ + spec + _BLOCKED, WORK_UNITS_ + spec + _FAILED, {unit: unitdef}) else: depends = session.get(WORK_UNITS_ + spec + _DEPENDS, unit) if depends is None: continue depends.remove([self.work_spec_name, self.key]) if len(depends) == 0: session.popmany(WORK_UNITS_ + spec + _DEPENDS, unit) unitdef = session.get(WORK_UNITS_ + spec + _BLOCKED, unit) if unitdef is not None: session.move(WORK_UNITS_ + spec + _BLOCKED, WORK_UNITS_ + spec, {unit: unitdef}) else: session.set(WORK_UNITS_ + spec + _DEPENDS, unit, depends) self.failed = 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_mode(self, mode): '''Set the global mode of the rejester system. This must be one of the constants :attr:`TERMINATE`, :attr:`RUN`, or :attr:`IDLE`. :attr:`TERMINATE` instructs any running workers to do an orderly shutdown, completing current jobs then exiting. :attr:`IDLE` instructs workers to stay running but not start new jobs. :attr:`RUN` tells workers to do actual work. :param str mode: new rejester mode :raise rejester.exceptions.ProgrammerError: on invalid `mode` ''' if mode not in [self.TERMINATE, self.RUN, self.IDLE]: raise ProgrammerError('mode=%r is not recognized' % mode) with self.registry.lock(identifier=self.worker_id) as session: session.set('modes', 'mode', mode) logger.info('set mode to %s', mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mode_counts(self): '''Get the number of workers in each mode. This returns a dictionary where the keys are mode constants and the values are a simple integer count of the number of workers in that mode. ''' modes = {self.RUN: 0, self.IDLE: 0, self.TERMINATE: 0} for worker_id, mode in self.workers().items(): modes[mode] += 1 return modes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def workers(self, alive=True): '''Get a listing of all workers. This returns a dictionary mapping worker ID to the mode constant for their last observed mode. :param bool alive: if true (default), only include workers that have called :meth:`Worker.heartbeat` sufficiently recently ''' return self.registry.filter( WORKER_OBSERVED_MODE, priority_min=alive and time.time() or '-inf')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dump(self): '''Print the entire contents of this to debug log messages. This is really only intended for debugging. It could produce a lot of data. ''' with self.registry.lock(identifier=self.worker_id) as session: for work_spec_name in self.registry.pull(NICE_LEVELS).iterkeys(): def scan(sfx): v = self.registry.pull(WORK_UNITS_ + work_spec_name + sfx) if v is None: return [] return v.keys() for key in scan(''): logger.debug('spec {0} unit {1} available or pending' .format(work_spec_name, key)) for key in scan(_BLOCKED): blocked_on = session.get( WORK_UNITS_ + work_spec_name + _DEPENDS, key) logger.debug('spec {0} unit {1} blocked on {2!r}' .format(work_spec_name, key, blocked_on)) for key in scan(_FINISHED): logger.debug('spec {0} unit {1} finished' .format(work_spec_name, key)) for key in scan(_FAILED): logger.debug('spec {0} unit {1} failed' .format(work_spec_name, 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 validate_work_spec(cls, work_spec): '''Check that `work_spec` is valid. It must at the very minimum contain a ``name`` and ``min_gb``. :raise rejester.exceptions.ProgrammerError: if it isn't valid ''' if 'name' not in work_spec: raise ProgrammerError('work_spec lacks "name"') if 'min_gb' not in work_spec or \ not isinstance(work_spec['min_gb'], (float, int, long)): raise ProgrammerError('work_spec["min_gb"] must be a number')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def num_available(self, work_spec_name): '''Get the number of available work units for some work spec. These are work units that could be returned by :meth:`get_work`: they are not complete, not currently executing, and not blocked on some other work unit. ''' return self.registry.len(WORK_UNITS_ + work_spec_name, priority_max=time.time())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def num_pending(self, work_spec_name): '''Get the number of pending work units for some work spec. These are work units that some worker is currently working on (hopefully; it could include work units assigned to workers that died and that have not yet expired). ''' return self.registry.len(WORK_UNITS_ + work_spec_name, priority_min=time.time())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def num_tasks(self, work_spec_name): '''Get the total number of work units for some work spec.''' return self.num_finished(work_spec_name) + \ self.num_failed(work_spec_name) + \ self.registry.len(WORK_UNITS_ + work_spec_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 status(self, work_spec_name): '''Get a summary dictionary for some work spec. The keys are the strings :meth:`num_available`, :meth:`num_pending`, :meth:`num_blocked`, :meth:`num_finished`, :meth:`num_failed`, and :meth:`num_tasks`, and the values are the values returned from those functions. ''' return dict( num_available=self.num_available(work_spec_name), num_pending=self.num_pending(work_spec_name), num_blocked=self.num_blocked(work_spec_name), num_finished=self.num_finished(work_spec_name), num_failed=self.num_failed(work_spec_name), num_tasks=self.num_tasks(work_spec_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 iter_work_specs(self, limit=None, start=None): ''' yield work spec dicts ''' count = 0 ws_list, start = self.list_work_specs(limit, start) while True: for name_spec in ws_list: yield name_spec[1] count += 1 if (limit is not None) and (count >= limit): break if not start: break if limit is not None: limit -= count ws_list, start = self.list_work_specs(limit, 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 get_work_spec(self, work_spec_name): '''Get the dictionary defining some work spec.''' with self.registry.lock(identifier=self.worker_id) as session: return session.get(WORK_SPECS, work_spec_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 list_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have not been completed ("available" or "pending" work units) are included. """
return self.registry.filter(WORK_UNITS_ + work_spec_name, start=start, limit=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 list_available_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of available work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have not been started, or units that were started but did not complete in a timely fashion, are included. """
return self.registry.filter(WORK_UNITS_ + work_spec_name, priority_max=time.time(), start=start, limit=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 list_pending_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of in-progress work units for some work spec. The dictionary is from work unit name to work unit definiton. Units listed here should be worked on by some worker. """
return self.registry.filter(WORK_UNITS_ + work_spec_name, priority_min=time.time(), start=start, limit=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 list_blocked_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of blocked work units for some work spec. The dictionary is from work unit name to work unit definiton. Work units included in this list are blocked because they were listed as the first work unit in :func:`add_dependent_work_units`, and the work unit(s) they depend on have not completed yet. This function does not tell why work units are blocked, it merely returns the fact that they are. """
return self.registry.filter(WORK_UNITS_ + work_spec_name + _BLOCKED, start=start, limit=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 list_finished_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of finished work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have been successfully completed are included. """
return self.registry.filter(WORK_UNITS_ + work_spec_name + _FINISHED, start=start, limit=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 list_failed_work_units(self, work_spec_name, start=0, limit=None): """Get a dictionary of failed work units for some work spec. The dictionary is from work unit name to work unit definiton. Only work units that have completed unsuccessfully are included. """
return self.registry.filter(WORK_UNITS_ + work_spec_name + _FAILED, start=start, limit=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 _remove_some_work_units(self, work_spec_name, work_unit_names, suffix='', priority_min='-inf', priority_max='+inf'): '''Remove some units from somewhere.''' now = time.time() if work_unit_names is None: count = 0 while True: with self.registry.lock(identifier=self.worker_id) as session: names = session.filter( WORK_UNITS_ + work_spec_name + suffix, priority_min=priority_min, priority_max=priority_max, limit=1000) if not names: break count += session.popmany( WORK_UNITS_ + work_spec_name + suffix, *names) else: # TODO: This needs to honor priority_min/priority_max, # otherwise it gets the wrong answer for "available"/ # "pending" (it will get both states). with self.registry.lock(identifier=self.worker_id) as session: count = session.popmany(WORK_UNITS_ + work_spec_name + suffix, *work_unit_names) return 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 del_work_units(self, work_spec_name, work_unit_keys=None, state=None, all=False): '''Delete work units from a work spec. The parameters are considered in order as follows: * If `all` is :const:`True`, then all work units in `work_spec_name` are deleted; otherwise * If `state` is not :const:`None`, then all work units in the named state are deleted; otherwise * If `work_unit_keys` are specified, then those specific work units are deleted; otherwise * Nothing is deleted. :param str work_spec_name: name of the work spec :param list work_unit_keys: if not :const:`None`, only delete these specific keys :param str state: only delete work units in this state :param bool all: if true, delete all work units :return: number of work units deleted ''' count = 0 if (state is None) or (state == AVAILABLE): count += self.remove_available_work_units(work_spec_name, work_unit_keys) if (state is None) or (state == PENDING): count += self.remove_pending_work_units(work_spec_name, work_unit_keys) if (state is None) or (state == BLOCKED): count += self.remove_blocked_work_units(work_spec_name, work_unit_keys) if (state is None) or (state == FAILED): count += self.remove_failed_work_units(work_spec_name, work_unit_keys) if (state is None) or (state == FINISHED): count += self.remove_finished_work_units(work_spec_name, work_unit_keys) return 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 remove_available_work_units(self, work_spec_name, work_unit_names): '''Remove some work units in the available queue. If `work_unit_names` is :const:`None` (which must be passed explicitly), all available work units in `work_spec_name` are removed; otherwise only the specific named work units will be. :param str work_spec_name: name of the work spec :param list work_unit_names: names of the work units, or :const:`None` for all in `work_spec_name` :return: number of work units removed ''' return self._remove_some_work_units( work_spec_name, work_unit_names, priority_max=time.time())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remove_pending_work_units(self, work_spec_name, work_unit_names): '''Remove some work units in the pending list. If `work_unit_names` is :const:`None` (which must be passed explicitly), all pending work units in `work_spec_name` are removed; otherwise only the specific named work units will be. Note that this function has the potential to confuse workers if they are actually working on the work units in question. If you have ensured that the workers are dead and you would be otherwise waiting for the leases to expire before calling :meth:`remove_available_work_units`, then this is a useful shortcut. :param str work_spec_name: name of the work spec :param list work_unit_names: names of the work units, or :const:`None` for all in `work_spec_name` :return: number of work units removed ''' return self._remove_some_work_units( work_spec_name, work_unit_names, priority_min=time.time())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remove_blocked_work_units(self, work_spec_name, work_unit_names): '''Remove some work units in the blocked list. If `work_unit_names` is :const:`None` (which must be passed explicitly), all pending work units in `work_spec_name` are removed; otherwise only the specific named work units will be. Note that none of the "remove" functions will restart blocked work units, so if you have called e.g. :meth:`remove_available_work_units` for a predecessor job, you may need to also call this method for its successor. :param str work_spec_name: name of the work spec :param list work_unit_names: names of the work units, or :const:`None` for all in `work_spec_name` :return: number of work units removed ''' return self._remove_some_work_units( work_spec_name, work_unit_names, suffix=_BLOCKED)
<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_failed_work_units(self, work_spec_name, work_unit_names): '''Remove some failed work units. If `work_unit_names` is :const:`None` (which must be passed explicitly), all failed work units in `work_spec_name` are removed; otherwise only the specific named work units will be. Also consider :meth:`retry` to move failed work units back into the available queue. :param str work_spec_name: name of the work spec :param list work_unit_names: names of the work units, or :const:`None` for all in `work_spec_name` :return: number of work units removed ''' return self._remove_some_work_units( work_spec_name, work_unit_names, suffix=_FAILED)
<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_finished_work_units(self, work_spec_name, work_unit_names): '''Remove some finished work units. If `work_unit_names` is :const:`None` (which must be passed explicitly), all finished work units in `work_spec_name` are removed; otherwise only the specific named work units will be. :param str work_spec_name: name of the work spec :param list work_unit_names: names of the work units, or :const:`None` for all in `work_spec_name` :return: number of work units removed ''' return self._remove_some_work_units( work_spec_name, work_unit_names, suffix=_FINISHED)