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 th...
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 ...
<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 ...
# 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 unavail...
<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'...
<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...
<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 ...
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=identifi...
<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. ...
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...
<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) ...
<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 exc...
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_...
<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 ...
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 p...
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_...
<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 obta...
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() 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 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): ...
<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_pag...
<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 s...
<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 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 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['so...
<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 ...
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...
<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: ...
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 al...
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 alre...
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...
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, ...
<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_...
<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 ke...
<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...
<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 ...
<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...
<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 i...
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...
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...
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...
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 =...
<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 m...
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`: ...
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...
<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. U...
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 Exce...
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``. ...
<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: ...
<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 =...
<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( WOR...
<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...
<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 call...
<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...
<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 nor...
<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 ava...
<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 ''' ...
<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_...
<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:`I...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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} ...
<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 rec...
<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_...
<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...
<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 se...
<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). ''' ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 fro...
<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 i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 wo...
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 ...
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 ...
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...
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 wo...
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 u...
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 ...
<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; oth...
<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 ...
<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 un...
<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 un...
<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. ...
<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 ...