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 update_req(name, old_req, config={}): """ Takes a requirement and updates it based on a specific attribute key args: name: the name of the attribute old_req:...
if not name: return old_req new_req = copy.deepcopy(old_req) del_idxs = [] if "req_items" in old_req: req_key = get_req_key(old_req['req_items']) for i, item in enumerate(old_req['req_items']): if name == item[req_key] and item.get("dict_params"): for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_options_from_str(obj_str, **kwargs): """ Returns a list of options from a python object string args: obj_str: python list of options or a python object p...
if isinstance(obj_str, list): return obj_str try: obj = get_obj_frm_str(obj_str, **kwargs) if obj: return list(obj) except AttributeError: pass 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 strip_errors(obj): """ Reads through and error object and replaces the error dict with the value args: obj: the error object/dictionary """
rtn_obj = copy.deepcopy(obj) try: del rtn_obj["__error_keys__"] except KeyError: pass for key in obj.get('__error_keys__', []): rtn_obj[key] = rtn_obj[key]['value'] return rtn_obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _peek(self, *types): """Returns the token type for lookahead; if there are any args then the list of args is the set of token types to allow"""
tok = self._scanner.token(self._pos, types) return tok[2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last_midnight(): """ return a datetime of last mid-night """
now = datetime.now() return datetime(now.year, now.month, now.day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(self, *args, **options): """ With no arguments, find the first user in the system with the is_superuser or is_staff flag set to true, or just the firs...
user_model = get_user_model() if len(args) == 0: # find the first superuser, or staff member or user filters = [{"is_superuser": True}, {"is_staff": True}, {}] user = None for f in filters: try: user = user_model._defa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config(configfile): """ Return a dict with configuration from the supplied yaml file """
try: with open(configfile, 'r') as ymlfile: try: config = yaml.load(ymlfile) return config except yaml.parser.ParserError: raise PyYAMLConfigError( 'Could not parse config file: {}'.format(configfile), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_config(configfile, content): """ Write dict to a file in yaml format """
with open(configfile, 'w+') as ymlfile: yaml.dump( content, ymlfile, default_flow_style=False, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_record(): """ Install an httplib wrapper that records but does not modify calls. """
global record, playback, current if record: raise StateError("Already recording.") if playback: raise StateError("Currently playing back.") record = True current = ReplayData() install(RecordingHTTPConnection, RecordingHTTPSConnection)
<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_types(func): """ Check if annotated function arguments are of the correct type """
call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, expected_type in func.__annotations__.items(): if not isinstance(parameters[arg_name], expected_type): raise TypeError("{} must be a {}".forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_absolute_uri(self, uri): """ Return a fully qualified absolute url for the given uri. """
request = self.context.get('request', None) return ( request.build_absolute_uri(uri) if request is not None else uri )
<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_resource_uri(self, obj): """ Return the uri of the given object. """
url = 'api:%s:%s-detail' % ( self.api_version, getattr( self, 'resource_view_name', self.Meta.model._meta.model_name ) ) return reverse(url, request=self.context.get('request', None), kwargs={ self.lookup_field: ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, template: str, **vars) -> str: """ Render the named template. The current context will be available to the template as the ``ctx`` variable. :par...
vars.setdefault('ctx', self._ctx) return self._renderer.render(template, **vars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_string(self, source: str, **vars) -> str: """ Render the template contained in the given string. The current context will be available to the template ...
vars.setdefault('ctx', self._ctx) return self._renderer.render_string(source, **vars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_header(name, header, required, stream, encoder, strict=False): """ Write AMF message header. @param name: Name of the header. @param header: Header va...
stream.write_ushort(len(name)) stream.write_utf8_string(name) stream.write_uchar(required) write_pos = stream.tell() stream.write_ulong(0) old_pos = stream.tell() encoder.writeElement(header) new_pos = stream.tell() if strict: stream.seek(write_pos) stream.write_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_body(stream, decoder, strict=False, logger=None): """ Read an AMF message body from the stream. @type stream: L{BufferedByteStream<pyamf.util.BufferedB...
def _read_args(): # we have to go through this insanity because it seems that amf0 # does not keep the array of args in the object references lookup type_byte = stream.peek(1) if type_byte == '\x11': if not decoder.use_amf3: raise pyamf.DecodeError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_body(name, message, stream, encoder, strict=False): """ Write AMF message body. @param name: The name of the request. @param message: The AMF L{Messag...
def _encode_body(message): if isinstance(message, Response): encoder.writeElement(message.body) return stream.write('\x0a') stream.write_ulong(len(message.body)) for x in message.body: encoder.writeElement(x) if not isinstance(message, (Req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(stream, strict=False, logger=None, timezone_offset=None): """ Decodes the incoming stream as a remoting message. @type stream: L{BufferedByteStream<py...
if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) if logger: logger.debug('remoting.decode start') msg = Envelope() msg.amfVersion = stream.read_ushort() # see http://osflash.org/documentation/amf/envelopes/remoting#preamble # why we...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def txtpack(fn, **kwargs): """Return a ChannelPack instance loaded with text data file fn. Attempt to read out custom channel names from the file and call instan...
loadfunc = pulltxt.loadtxt_asdict cp = ChannelPack(loadfunc) cp.load(fn, **kwargs) names = pulltxt.PP.channel_names(kwargs.get('usecols', None)) cp.set_channel_names(names) cp._patpull = pulltxt.PP # Give a reference to the patternpull. # cp.set_basefilemtime() return cp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dbfpack(fn, usecols=None): """Return a ChannelPack instance loaded with dbf data file fn. This is a lazy function to get a loaded instance, using pulldbf mod...
loadfunc = pulldbf.dbf_asdict cp = ChannelPack(loadfunc) cp.load(fn, usecols) names = pulldbf.channel_names(fn, usecols) cp.set_channel_names(names) # cp.set_basefilemtime() return cp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, *args, **kwargs): """Load data using loadfunc. args, kwargs: forward to the loadfunc. args[0] must be the filename, so it means that loadfunc must...
D = self.loadfunc(*args, **kwargs) if self.chnames is not None: if set(D) - set(self.chnames): raise ValueError('New data set have different keys') self.D = D self.keys = sorted(self.D.keys()) # If not all the same, there should have been an error a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_load(self, *args, **kwargs): """Append data using loadfunc. args, kwargs: forward to the loadfunc. args[0] must be the filename, so it means that load...
if not self.D: self.load(*args, **kwargs) return newD = self.loadfunc(*args, **kwargs) s1, s2 = set(self.D.keys()), set(newD.keys()) offenders = s1 ^ s2 if offenders: mess = ('Those keys (respectively) were in one of the dicts ' + ...
<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_samplerate(self, rate): """Set sample rate to rate. rate: int or float rate is given as samples / timeunit. If sample rate is set, it will have an impact...
# Test and set value: float(rate) self.conconf.set_condition('samplerate', rate) if not self.no_auto: self.make_mask()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_condition(self, conkey, cond): """Add a condition, one of the addable ones. conkey: str One of 'cond', startcond' or 'stopcond'. 'start' or 'stop' is acc...
# Audit: if conkey == 'start' or conkey == 'stop': conkey += 'cond' if not any(conkey.startswith(addable) for addable in _ADDABLES): raise KeyError(conkey) if not self.conconf.valid_conkey(conkey): raise KeyError(conkey) self._parse_cond(con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spit_config(self, conf_file=None, firstwordonly=False): """Write a config_file based on this instance. conf_file: str (or Falseish) If conf_file is Falseish,...
chroot = os.path.dirname(self.filename) chroot = os.path.abspath(chroot) # Figure out file name of conf_file: if hasattr(self, 'conf_file') and not conf_file: cfgfn = self.conf_file elif conf_file: cfgfn = conf_file else: cfgfn = os....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eat_config(self, conf_file=None): """ Read the the conf_file and update this instance accordingly. conf_file: str or Falseish If conf_file is Falseish, look ...
chroot = os.path.dirname(self.filename) # "channels root dir" chroot = os.path.abspath(chroot) # Figure out file name of conf_file: if hasattr(self, 'conf_file') and not conf_file: cfgfn = self.conf_file elif conf_file: cfgfn = conf_file else: ...
<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_stopextend(self, n): """Extend the True elements by n when setting the conditions based on a 'stopcond' condition. n is an integer >= 0. .. note:: Update...
self.conconf.set_condition('stopextend', n) if not self.no_auto: self.make_mask()
<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_duration(self, rule): """Set the duration according to rule. rule: str The rule operating on the variable ``dur``. rule is an expression like:: setting a...
self.conconf.set_condition('duration', rule) if not self.no_auto: self.make_mask()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_conditions(self, *conkeys, **noclear): """Clear conditions. Clear only the conditions conkeys if specified. Clear only the conditions not specified by ...
offenders = set(conkeys) - set(self.conconf.conditions.keys()) if offenders: raise KeyError(', '.join([off for off in offenders])) # Valid keywords subtracted offenders = set(noclear) - set({'noclear'}) if offenders: raise KeyError(', '.join([off for of...
<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_mask(self, clean=True, dry=False): """Set the attribute self.mask to a mask based on the conditions. clean: bool If not True, let the current mask be a ...
cc = self.conconf # All True initially. mask = np.ones(self.rec_cnt) == True # NOQA for cond in cc.conditions_list('cond'): try: mask = mask & self._mask_array(cond) except Exception: print cond print 'produced an...
<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_channel_names(self, names): """ Set self.chnames. Custom channel names that can be used in calls on this object and in condition strings. names: list or ...
if not names: self.chnames = None return if len(names) != len(self.keys): raise ValueError('len(names) != len(self.D.keys())') self.chnames = dict(zip(self.keys, names))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def counter(self, ch, part=None): """Return a counter on the channel ch. ch: string or integer. The channel index number or channel name. part: int or None The 0...
return Counter(self(self._key(ch), part=part))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def records(self, part=None, fallback=True): """Return an iterator over the records in the pack. Each record is supplied as a namedtuple with the channel names a...
names_0 = [self.chnames_0[k] for k in sorted(self.chnames_0.keys())] if self.chnames is not None: names = [self.chnames[k] for k in sorted(self.chnames.keys())] try: Record = namedtuple('Record', names) except NameError: # no names Record = na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _key(self, ch): """Return the integer key for ch. It is the key for the first value found in chnames and chnames_0, that matches ch. Or if ch is an int, ch i...
if ch in self.D: return ch if isinstance(ch, int): raise KeyError(ch) # dont accept integers as custom names if self.chnames: for item in self.chnames.items(): if item[1] == ch: return item[0] for item in self.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self, ch, firstwordonly=False): """Return channel name for ch. ch is the channel name or the index number for the channel name, 0-based. ch: str or int....
names = self.chnames or self.chnames_0 i = self._key(ch) if not firstwordonly: return names[i] elif firstwordonly is True or firstwordonly == 1: return names[i].split()[0].strip() # According to user pattern return re.findall(firstwordonly, nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_names(self, pat): """pat a shell pattern. See fnmatch.fnmatchcase. Print the results to stdout."""
for item in self.chnames.items(): if fnmatch.fnmatchcase(item[1], pat): print item
<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_condition(self, conkey, val): """Set condition conkey to value val. Convert val to str if not None. conkey: str A valid condition key. val: str, int, flo...
if not any([conkey.startswith(c) for c in _COND_PREFIXES]): raise KeyError(conkey) if val in NONES: self.conditions[conkey] = None else: self.conditions[conkey] = str(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 spit_config(self, conf_file, firstwordonly=False): """conf_file a file opened for writing."""
cfg = ConfigParser.RawConfigParser() for sec in _CONFIG_SECS: cfg.add_section(sec) sec = 'channels' for i in sorted(self.pack.D): cfg.set(sec, str(i), self.pack.name(i, firstwordonly=firstwordonly)) sec = 'conditions' for k ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eat_config(self, conf_file): """conf_file a file opened for reading. Update the packs channel names and the conditions, accordingly. """
# Read the file: cfg = ConfigParser.RawConfigParser() cfg.readfp(conf_file) # Update channel names: sec = 'channels' mess = 'missmatch of channel keys' assert(set(self.pack.D.keys()) == set([int(i) for i in cfg.options(sec)])), mess # NOQA if not 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 cond_int(self, conkey): """Return the trailing number from cond if any, as an int. If no trailing number, return the string conkey as is. This is used for so...
m = re.match(self.numrx, conkey) if not m: return conkey return int(m.group(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 valid_conkey(self, conkey): """Check that the conkey is a valid one. Return True if valid. A condition key is valid if it is one in the _COND_PREFIXES list. ...
for prefix in _COND_PREFIXES: trailing = conkey.lstrip(prefix) if trailing == '' and conkey: # conkey is not empty return True try: int(trailing) return True except ValueError: pass 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 sorted_conkeys(self, prefix=None): """Return all condition keys in self.conditions as a list sorted suitable for print or write to a file. If prefix is given...
# Make for defined and sorted output: conkeys = [] for cond in _COND_PREFIXES: conkeys += sorted([key for key in self.conditions if key.startswith(cond)], key=self.cond_int) if not prefix: return conkeys return [key for 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 isordinal(x): """Checks if a list or array contains ordinal data. Warning: -------- This is not a reliable check for a variable being ordinal. The following ...
import numpy as np if len(x) == len(np.unique(x)): return False, ("number of observations equals the " "number of unique values.") if not isinstance(x[0], str): if not np.all(np.equal(np.mod(x, 1), 0)): return False, "elements are not integer or strings....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, default=NoDefault): """Retrieve a value from its key. Retrieval steps are: 1) Normalize the key 2) For each option group: a) Retrieve the valu...
key = normalize_key(key) if default is NoDefault: defaults = [] else: defaults = [default] for options in self.options: try: value = options[key] except KeyError: continue if isinstance(value, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_children(self, include_self=False): """ Return all subsidiaries of this company. """
ownership = Ownership.objects.filter(parent=self) subsidiaries = Company.objects.filter(child__in=ownership) for sub in subsidiaries: subsidiaries = subsidiaries | sub.get_all_children() if include_self is True: self_company = Company.objects.filter(id=self.id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_parents(self): """ Return all parents of this company. """
ownership = Ownership.objects.filter(child=self) parents = Company.objects.filter(parent__in=ownership) for parent in parents: parents = parents | parent.get_all_parents() return parents
<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_all_related_companies(self, include_self=False): """ Return all parents and subsidiaries of the company Include the company if include_self = True """
parents = self.get_all_parents() subsidiaries = self.get_all_children() related_companies = parents | subsidiaries if include_self is True: company_qs = Company.objects.filter(id=self.id) related_companies = related_companies | company_qs related_compan...
<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_immediate_children(self): """ Return all direct subsidiaries of this company. Excludes subsidiaries of subsidiaries """
ownership = Ownership.objects.filter(parent=self) subsidiaries = Company.objects.filter(child__in=ownership).distinct() return subsidiaries
<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_immediate_children_ownership(self): """ Return all direct subsidiaries of this company AS OWNERSHIP OBJECTS. Excludes subsidiaries of subsidiaries. """
ownership = Ownership.objects.filter(parent=self).select_related('child', 'child__country') return ownership
<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_immediate_parents(self): """ Return all direct parents of this company. Excludes parents of parents """
ownership = Ownership.objects.filter(child=self) parents = Company.objects.filter(parent__in=ownership).distinct() return parents
<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_directors(self): """ Return all directors for this company """
directors = Director.objects.filter(company=self, is_current=True).select_related('person') return directors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_data(self): """ Cache some basic data such as financial statement metrics """
# Set Slug if not set if not self.slug_name: self.slug_name = slugify(self.name).strip() if len(self.slug_name) > 255: self.slug_name = self.slug_name[0:254]
<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_name_on_date(self, date): """ Get the name of a company on a given date. This takes into accounts and name changes that may have occurred. """
if date is None: return self.name post_name_changes = CompanyNameChange.objects.filter(company=self, date__gte=date).order_by('date') if post_name_changes.count() == 0: return self.name else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """ This method autogenerates the auto_generated_description field """
# Cache basic data self.cache_data() # Ensure slug doesn't change if self.id is not None: db_company = Company.objects.get(id=self.id) if self.slug_name != db_company.slug_name: raise ValueError("Cannot reset slug_name") if str(self.tra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """ Generate a name, and ensure amount is less than or equal to 100 """
self.name = str(self.parent.name) + " - " + str(self.child.name) + " - " + str(self.ownership_type) if self.amount > 100: raise ValueError("Ownership amount cannot be more than 100%") elif self.amount < 0: raise ValueError("Ownership amount cannot be less than 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 tenure(self): """ Calculates board tenure in years """
if self.end_date: return round((date.end_date - self.start_date).days / 365., 2) else: return round((date.today() - self.start_date).days / 365., 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_toc_tree(title, input, output, content_directory): """ Builds Sphinx documentation table of content tree file. :param title: Package title. :type title...
LOGGER.info("{0} | Building Sphinx documentation index '{1}' file!".format(build_toc_tree.__name__, output)) file = File(input) file.cache() existing_files = [foundations.strings.get_splitext_basename(item) ...
<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_command_line_arguments(): """ Retrieves command line arguments. :return: Namespace. :rtype: Namespace """
parser = argparse.ArgumentParser(add_help=False) parser.add_argument("-h", "--help", action="help", help="'Displays this help message and exit.'") parser.add_argument("-t", "--title", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initCTR(self, iv=0): """Initializes CTR mode of the cypher"""
assert struct.calcsize("Q") == self.blocksize() self.ctr_iv = iv self._calcCTRBUF()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calcCTRBUF(self): """Calculates one block of CTR keystream"""
self.ctr_cks = self.encrypt(struct.pack("Q", self.ctr_iv)) # keystream block self.ctr_iv += 1 self.ctr_pos = 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 _nextCTRByte(self): """Returns one byte of CTR keystream"""
b = ord(self.ctr_cks[self.ctr_pos]) self.ctr_pos += 1 if self.ctr_pos >= len(self.ctr_cks): self._calcCTRBUF() return b
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _call(self, method, path, data=None): """ Do the actual HTTP request """
if is_python3(): conn = http.client.HTTPConnection(API_HOST) else: conn = httplib.HTTPConnection(API_HOST) headers = {'User-Agent' : USER_AGENT} if data: headers.update( {'Content-type': 'application/x-www-form-urlencoded'} ) conn.request(method, path, self._urlencode(data), h...
<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_body(self, body): """ For just call a deserializer for FORMAT"""
if is_python3(): return json.loads(body.decode('UTF-8')) else: return json.loads(body)
<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_urls(self): """ Extend the admin urls for the CompetitionEntryAdmin model to be able to invoke a CSV export view on the admin model """
urls = super(CompetitionEntryAdmin, self).get_urls() csv_urls = patterns('', url( r'^exportcsv/$', self.admin_site.admin_view(self.csv_export), name='competition-csv-export' ) ) return csv_urls + urls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csv_export(self, request): """ Return a CSV document of the competition entry and its user details """
response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=competitionentries.csv' # create the csv writer with the response as the output file writer = UnicodeWriter(response) writer.writerow([ 'Competition ID', 'Compet...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filelist(folderpath, ext=None): ''' Returns a list of all the files contained in the folder specified by `folderpath`. To filter the files by extension simply add a list containing all the extension with `.` as the second argument. If `flat` is False, then the Path objects are returned. ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def particles(category=None): ''' Returns a dict containing old greek particles grouped by category. ''' filepath = os.path.join(os.path.dirname(__file__), './particles.json') with open(filepath) as f: try: particles = json.load(f) except ValueError as e: log....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parts(): ''' Returns the dictionary with the part as key and the contained book as indices. ''' parts = { 'Canon': [ _ for _ in range(1, 5) ], 'Apostle': [ 5 ], 'Paul': [ _ for _ in range(6, 19) ], 'General': [ _ for _ in range(19, 26) ], 'Apocalypse': [ 27 ]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def component_activated(self, component): """Initialize additional member variables for components. Every component activated through the `Environment` object ge...
component.env = self super(Environment, self).component_activated(component)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret(self, msg): """ Create a slide show """
self.captions = msg.get('captions', '.') for item in msg['slides']: self.add(item)
<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_duration(self, duration): """ Calculate how long each slide should show """
fixed = sum(int(x.get('time', 0)) for x in self.slides) nfixed = len([x for x in self.slides if x.get('time', 0) > 0]) unfixed = len(self.slides) - nfixed self.wait = max(1, int(duration / unfixed))
<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): """ Run the show """
self.show() if not self.wait: return for image in self.slides: wait = image.get('time', 0) wait = max(self.wait, wait) print('waiting %d seconds %s' % ( wait, image.get('image', ''))) yield image ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fastaIterator(fn, useMutableString=False, verbose=False): """ A generator function which yields fastaSequence objects from a fasta-format file or stream. :pa...
fh = fn if type(fh).__name__ == "str": fh = open(fh) if verbose: try: pind = __build_progress_indicator(fh) except ProgressIndicatorError as e: sys.stderr.write("Warning: unable to show progress for stream. " + "Reason: " + str(e)) verbose = False prev_lin...
<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_default(self): """ Returns the default value for this field. The default implementation on models.Field calls force_unicode on the default, which means y...
if self.has_default(): if callable(self.default): return self.default() return self.default # If the field doesn't have a default, then we punt to models.Field. return super(PickledObjectField, self).get_default()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_python(self, value): """ B64decode and unpickle the object, optionally decompressing it. If an error is raised in de-pickling and we're sure the value is ...
if value is not None: try: value = dbsafe_decode(value, self.compress) except: # If the value is a definite pickle; and an error is raised in # de-pickling it should be allowed to propogate. if isinstance(value, PickledObje...
<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_db_prep_value(self, value): """ Pickle and b64encode the object, optionally compressing it. The pickling protocol is specified explicitly (by default 2),...
if value is not None and not isinstance(value, PickledObject): # We call force_unicode here explicitly, so that the encoded string # isn't rejected by the postgresql_psycopg2 backend. Alternatively, # we could have just registered PickledObject with the psycopg #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nextComment(self, text, start=0): """Return the next comment found in text starting at start. """
m = min([self.lineComment(text, start), self.blockComment(text, start), self._emptylineregex.search(text, start)], key=lambda m: m.start(0) if m else len(text)) return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isLineComment(self, text): """Return true if the text is a line comment. """
m = self.lineComment(text, 0) return m and m.start(0) == 0 and m.end(0) == len(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 nextValidComment(self, text, start=0): """Return the next actual comment. """
m = min([self.lineComment(text, start), self.blockComment(text, start)], key=lambda m: m.start(0) if m else len(text)) return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractContent(self, text): """Extract the content of comment text. """
m = self.nextValidComment(text) return '' if m is None else m.group(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 chunkComment(self, text, start=0): """Return a list of chunks of comments. """
# Build a list of comments comm, out = self.nextComment(text, start), [] while comm: out.append(comm.group(0)) comm = self.nextComment(text, comm.start(0) + 1) # Collect the comments according to whether they are line # comments or block comments. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def code(self, text): """Return the code instead of the comments. """
comm = self.nextValidComment(text) while comm: text = text[:comm.start()] + text[comm.end():] comm = self.nextValidComment(text, comm.end(0)) return 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 get_object(self, *args, **kwargs): """ Should memoize the object to avoid multiple query if get_object is used many times in the view """
self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug']) return get_object_or_404(Post, thread__id=self.kwargs['thread_id'], thread__category=self.category_instance, pk=self.kwargs['post_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 each_cons(sequence, size): """Iterates lazily through a sequence looking at a sliding window with given size, for each time. each_cons([1, 2, 3, 4], 2) --> [...
return zip(*(islice(it, start, None) for start, it in enumerate(tee(sequence, size))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __filter(self, name): '''Filter out problematic characters. This should become a separate module allowing the user to define filter rules from a bootstrap file and most likely become a separate module. ''' name = name.replace("'", '') name = name.replace('"', '') ...
<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(self): """ Check if pkg has a later version Returns true if later version exists """
current = self._get_current() highest = self._get_highest_version() return highest > current
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bugzscout_app(environ, start_response): """Simple WSGI application that returns 200 OK response with 'Hellow world!' in the body. If an uncaught exception is...
try: start_response('200 OK', [('content-type', 'text/html')]) return ['Hellow world!'] except Exception as ex: # Set the description to a familiar string with the exception # message. Add the stack trace to extra. b.submit_error('An error occurred in MyApp: {0}'.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 _request(self, base_url, client_id, client_secret, parameters, **kwargs): """Make an API request to get the token"""
logging.debug('Getting an OAuth token for client "%s" with scope "%s"', client_id, parameters.get('scope')) headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'} api = API(base_url, auth_username...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cached_request(self, base_url, client_id, client_secret, parameters, **kwargs): """Cache the token request and use cached responses if available"""
key = (base_url, client_id, tuple(parameters.items())) cached = self._cache.get(key, {}) if not cached.get('access_token') or self._expired(cached): cached = yield self._request(base_url, client_id, client_secret, parameters, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purge_cache(self): """ Purge expired cached tokens and oldest tokens if more than cache_size """
if len(self._cache) > self.max_cache_size: items = sorted(self._cache.items(), key=lambda (k, v): v['expiry']) self._cache = {k: v for k, v in items[self.max_cache_size:] if not self._expired(v)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_user_agent(self): """ Create the user agent and return it as a string. """
user_agent = '{}/{} {}'.format(pyspacegdn.__title__, pyspacegdn.__version__, default_user_agent()) if self.client_name: user_agent = '{}/{} {}'.format(self.client_name, 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 load_configuration(app_name): ''' creates a new configuration and loads the appropriate files. ''' if sys.prefix == '/usr': conf_dir = '/etc' share_dir = '/usr/share' else: conf_dir = os.path.join(sys.prefix, 'etc') share_dir = os.path.join(sys.prefix, 'share'...
<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_base_wrappers(method='get', template_name='', predicates=(), wrappers=()): """ basic View Wrappers used by view_config. """
wrappers += (preserve_view(MethodPredicate(method), *predicates),) if template_name: wrappers += (render_template(template_name),) return wrappers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_config( method='get', template_name='', predicates=(), wrappers=(), base_wrappers_getter=get_base_wrappers, ): """ Creating Views applied some configura...
wrappers = base_wrappers_getter(method, template_name, predicates, wrappers) def wrapper(view_callable): def _wrapped(*args, **kwargs): return reduce( lambda a, b: b(a), reversed(wrappers + (view_callable,)) )(*args, **kwargs) view_callab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preserve_view(*predicates): """ Raising ViewNotMatched when applied request was not apposite. preserve_view calls all Predicates and when return values of th...
def wrapper(view_callable): def _wrapped(self, request, context, *args, **kwargs): if all([predicate(request, context) for predicate in predicates]): return view_callable(self, request, context, *args, **kwargs) else: raise ViewNotMatched retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_template(template_name, template_getter=get_app_template): """ Decorator to specify which template to use for Wrapped Views. It will return string ren...
def wrapper(func): template = template_getter(template_name) def _wraped(self, request, context, *args, **kwargs): res = func(self, request, context, *args, **kwargs) if isinstance(res, dict): return template.render(**res) else: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt(self, prompt_msg=None, newline=False): """ Writes prompt message to output stream and reads line from standard input stream. `prompt_msg` Message to w...
if prompt_msg is not None: self.write(prompt_msg, newline) return self._input.readline().rstrip(os.linesep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, buf, newline=True): """ Writes buffer to output stream. `buf` Data buffer to write. `newline` Append newline character to buffer before writing. ...
buf = buf or '' if newline: buf += os.linesep try: self._output.write(buf) if hasattr(self._output, 'flush'): self._output.flush() except IOError as exc: if exc.errno != errno.EPIPE: # silence EPIPE errors ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def success(self, buf, newline=True): """ Same as `write`, but adds success coloring if enabled. `buf` Data buffer to write. `newline` Append newline character t...
if self._colored: buf = self.ESCAPE_GREEN + buf + self.ESCAPE_CLEAR self.write(buf, newline)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, buf, newline=True): """ Similar to `write`, except it writes buffer to error stream. If coloring enabled, adds error coloring. `buf` Data buffer ...
buf = buf or '' if self._colored: buf = self.ESCAPE_RED + buf + self.ESCAPE_CLEAR if newline: buf += os.linesep try: self._error.write(buf) if hasattr(self._error, 'flush'): self._error.flush() except IOError a...