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 save_to_file(self, filename: str) -> ConfigFile: """ This converts the NetworkedConfigFile into a normal ConfigFile object. This requires the normal class hoo...
newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0], dump_hook=self.normal_class_hook[1], safe_load=self.safe_load) return newclass
<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_args(s): """ parse a string into args and kwargs the input is a blank-delimited set of tokens, which may be grouped as strings (tick or double tick delimi...
args = [] kwargs = {} state = 'arg' for token in to_tokens(s): if state == 'arg': if token.is_key: key = token.value state = 'value' else: args.append(token.value) elif state == 'key': if not token.is_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 dispatch(self, req): """ Called by the Routes middleware to dispatch the request to the appropriate controller. If a webob exception is raised, it is returne...
# Grab the request parameters params = req.environ['wsgiorg.routing_args'][1] # What controller is authoritative? controller = params.pop('controller') # Determine its name cont_class = controller.__class__ cont_name = "%s:%s" % (cont_class.__module__, cont_cl...
<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(self, ns, selector='*'): """ Query the label store for labels :param ns: Label namespace (`bind_pwd` for example) :type ns: str :param selector: Target...
q, r = HicaLabelStore.PREFIX + '.' + ns, [] for (key, value) in self.items: if not selector and key == q: r.append((key, value)) if key.startswith(q) and key != q: sub = key[len(q):] m = re.match('.' + selector, sub) if m: r.append((key, value)) 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 get_value(self, label): """ Get value from a single fully-qualified name """
for (key, value) in self.items: if key == label: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initPatterns(ptc): """ Helper function to take the different localized bits from ptc and create the regex strings. """
# TODO add code to parse the date formats and build the regexes up from sub-parts # TODO find all hard-coded uses of date/time seperators ptc.RE_DATE4 = r'''(?P<date>(((?P<day>\d\d?)(?P<suffix>%(daysuffix)s)?(,)?(\s)?) (?P<mthname>(%(months)s|%(shortmonths)s))\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 _initConstants(ptc): """ Create localized versions of the units, week and month names """
# build weekday offsets - yes, it assumes the Weekday and shortWeekday # lists are in the same order and Mon..Sun (Python style) ptc.WeekdayOffsets = {} o = 0 for key in ptc.Weekdays: ptc.WeekdayOffsets[key] = o o += 1 o = 0 for key in ptc.shortWeekdays: ptc.Wee...
<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_to_file(self, file_path: str) -> None: """ Serialize and write the data into a JSON file. """
data = self.encode() with open(file_path, "w") as f: json.dump(data, f, indent=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 load_from_file(cls, file_path: str): """ Read and reconstruct the data from a JSON file. """
with open(file_path, "r") as f: data = json.load(f) item = cls.decode(data=data) return 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 gen_component_name(self, basename, postfix_length=13): """ Creates a resource identifier with a random postfix. This is an attempt to minimize name collision...
def newcname(): postfix = ''.join( random.choice(_AWS_NAME_CHARS) for i in xrange(postfix_length) ) return '%s-%s' % (basename, postfix) cname = newcname() while cname in self.component_names: cname ...
<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_slugs(apps, schema_editor): """ Include birthdate in slugs """
# Get model managers Representative = apps.get_model("representatives", "Representative") for rep in Representative.objects.all(): rep.slug = '%s-%s' % (rep.slug, rep.birth_date) rep.save()
<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_parl_websites(apps, schema_editor): """ Prepare for remote_id removal by creating WebSite entities from it. """
# Get model managers Representative = apps.get_model("representatives", "Representative") WebSite = apps.get_model("representatives", "WebSite") today = datetime.date.today() # EP ep_url = 'http://www.europarl.europa.eu/meps/en/%s/_home.html' qs = Representative.objects.filter( 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 determine_file_extension_based_on_format(format_specifier): """ returns file extension string """
if format_specifier == FMT_INI: return 'ini' if format_specifier == FMT_DELIMITED: return '' if format_specifier == FMT_XML: return 'xml' if format_specifier == FMT_JSON: return 'json' if format_specifier == FMT_YAML: return 'yml' raise ValueError('invalid format specifier: {}'.format(format_specifier)...
<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_element_using_argtuple(self, argtuple): """ takes a tuple of keys returns node found in cfg_dict found by traversing cfg_dict by successive ap...
# doesn't support DELIMITED, only dict-based formats if self.format == FMT_DELIMITED: return None node = self.cfg_dict for key in argtuple: node = node[key] return node
<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_arc(self, mace_type, name): ''' Creates the story arc and initial tree for that arc for the current outline. Returns the resulting Arc instance. ''' arc = Arc(mace_type=mace_type, outline=self, name=name) arc.save() milestone_count = arc.generat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_template_arc_tree(self): ''' Generate a seven point template in this arc. Arc must be empty. ''' arc_root = self.arc_root_node if not arc_root: arc_root = ArcElementNode.add_root( arc_element_type='root', description='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 fetch_arc_errors(self): ''' Evaluates the current tree of the arc and provides a list of errors that the user should correct. ''' error_list = [] hnode = self.validate_first_element() if hnode: error_list.append({'hook_error': hnode}) rnode...
<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_generations(self): ''' Make sure that the descendent depth is valid. ''' nodes = self.arc_root_node.get_descendants() for node in nodes: logger.debug("Checking parent for node of type %s" % node.arc_element_type) parent = ArcElementNode.object...
<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_milestones(self): ''' Reviews the arc element tree to ensure that milestones appear in the right order. ''' milestones = self.arc_root_node.get_children().filter(arc_element_type__contains='mile') current_cursor = 0 for mile in milestones: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def all_characters(self): ''' Returns a queryset of all characters associated with this node and its descendants, excluding any duplicates. ''' qs = self.assoc_characters.all() for node in self.get_descendants(): qs2 = node.assoc_characters.all() q...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def impact_rating(self): ''' Returns the impact rating for this node. Impact rating is a measure of how powerful this moment in the story is by evaluting how many simultaneous arc elements are associated with it. There is also a generational bleed element, where the impact score ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def all_locations(self): ''' Returns a queryset of all locations associated with this node and its descendants, excluding any duplicates. ''' qs = self.assoc_locations.all() for node in self.get_descendants(): qs2 = node.assoc_locations.all() qs = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def move(self, target, pos=None): ''' An override of the treebeard api in order to send a signal in advance. ''' if self.outline != target.outline: raise IntegrityError('Elements must be from the same outline!') tree_manipulation.send( sender=self.__class_...
<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_by_enclosures(self, enclosure_urls): """ Get bitlove data for a list of enclosure URLs """
# prepare URLs enclosure_urls = map(str.strip, enclosure_urls) enclosure_urls = filter(None, enclosure_urls) return BitloveResponse(self.opener, enclosure_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 get(self, url): """ Get the response for the given enclosure URL """
self._query() return Enclosure(self._resp.get(url), 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 _query(self): """ perform a request to the API, only when necessary """
if not self.urls: self._resp = {} elif self._resp is None: params = [ ('url', url) for url in self.urls] query = urllib.urlencode(params) # query API r = self.opener.open(BITLOVE_ENCLOSURE_API + query) self._resp = json.loads(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 _build_parser(): """ Return a command-line arguments parser. """
parser = argparse.ArgumentParser(description='Search you Azure AD contacts from mutt or the command-line.') parser.add_argument('-c', '--config', help='Specify alternative configuration file.', metavar="FILE") parser.add_argument('-v', '--verbose', dest="log_level", action='store_const', ...
<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_packages_under(path): """ Recursive list all of the packages under a specific package."""
all_packages = setuptools.find_packages() packages = [] for package in all_packages: package_split = package.split(".") if package_split[0] == path: packages.append(package) return packages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_version_to_package(path): """ Copy the single source of truth version number into the package as well. """
init_file = os.path.join(path, "__init__.py") with open(init_file, "r") as original_file: lines = original_file.readlines() with open(init_file, "w") as new_file: for line in lines: if "__version__" not in line: new_file.write(line) 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 validate(self): """Validation of configuration to check for required values"""
if not self.server.enabled: if self.security.signature_certificate_file is self.security.defaults['signature_certificate_file']: print("ISSUE: If you are not configuring a server, you need to set 'signature_certificate_file'") if self.security.signature_private_key_fi...
<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_admin(app, admin): """Called on app initialization to register administration interface."""
category = 'Knowledge' admin.category_icon_classes[category] = "fa fa-mortar-board" admin.add_view( KnowledgeAdmin(app, KnwKB, db.session, name='Knowledge Base', category=category, endpoint="kb") ) admin.add_view( KnwKBRVALAdmin(app, Knw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def after_model_change(self, form, model, is_created): """Save model."""
super(KnowledgeAdmin, self).after_model_change(form, model, is_created) from invenio_collections.models import Collection if form.kbtype.data == KnwKB.KNWKB_TYPES['dynamic']: id_collection = form.id_collection.data or None collection = Collection.query.filter_by( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_form(self, obj=None): """Edit form."""
kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w' if kbtype == KnwKB.KNWKB_TYPES['written_as']: self.form = WrittenAsKnowledgeForm elif kbtype == KnwKB.KNWKB_TYPES['dynamic']: self.form = DynamicKnowledgeForm else: self.form = Taxo...
<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_form(self, obj=None): """Create form."""
kbtype = request.args['kbtype'] if 'kbtype' in request.args else 'w' if kbtype == KnwKB.KNWKB_TYPES['written_as']: self.form = WrittenAsKnowledgeForm elif kbtype == KnwKB.KNWKB_TYPES['dynamic']: self.form = DynamicKnowledgeForm else: self.form = Taxo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """
node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
<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_pk(abspath, compress=False, enable_verbose=True): """Load Python Object from Pickle file. :param abspath: File path. Use absolute path as much as you ca...
abspath = str(abspath) # try stringlize msg = Messenger(enable_verbose=enable_verbose) if compress: # check extension name if os.path.splitext(abspath)[1] != ".gz": raise Exception("compressed pickle has to use extension '.gz'!") else: if os.path.splitext(abspath)[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 dump_pk(obj, abspath, pk_protocol=pk_protocol, replace=False, compress=False, enable_verbose=True): """Dump Picklable Python Object to file. Provides multipl...
abspath = str(abspath) # try stringlize msg = Messenger(enable_verbose=enable_verbose) if compress: # check extension name root, ext = os.path.splitext(abspath) if ext != ".gz": if ext != ".tmp": raise Exception( "compressed pickle has 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 safe_dump_pk(obj, abspath, pk_protocol=pk_protocol, compress=False, enable_verbose=True): """A stable version of dump_pk, silently overwrite existing file. W...
abspath = str(abspath) # try stringlize temp_abspath = "%s.tmp" % abspath dump_pk(obj, temp_abspath, pk_protocol=pk_protocol, replace=True, compress=compress, enable_verbose=enable_verbose) shutil.move(temp_abspath, abspath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSw...
return base64.b64encode(pickle.dumps( obj, protocol=pk_protocol)).decode("utf-8")
<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 analysis. The basic idea is to recursively find all script files in specific programming language, and analyze each file then sum it up. ""...
n_target_file, n_other_file = 0, 0 code, comment, docstr, purecode = 0, 0, 0, 0 fc = FileCollection.from_path_except(self.workspace, self.ignore) fc_yes, fc_no = fc.select(self.filter, keepboth=True) n_other_file += len(fc_no) for abspath in fc_yes: try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyzePython(code_text): """Count how many line of code, comment, dosstr, purecode in one Python script file. """
code, comment, docstr = 0, 0, 0 p1 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ('"""', '"""') p2 = r"""(?<=%s)[\s\S]*?(?=%s)""" % ("'''", "'''") # count docstr for pattern in [p1, p2]: for res in re.findall(pattern, code_text)[::2]: lines = [i.strip() for i in...
<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(__func: Callable, __arg: str) -> str: """Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract ...
return signature(__func).parameters[__arg].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 config_(name: str, local: bool, package: str, section: str, key: Optional[str]): """Extract or list values from config."""
cfg = config.read_configs(package, name, local=local) if key: with suppress(NoOptionError, NoSectionError): echo(cfg.get(section, key)) else: with suppress(NoSectionError): for opt in cfg.options(section): colourise.pinfo(opt) echo(' ...
<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_tag(match: str, strict: bool, directory: str): """Find tag for git repository."""
with suppress(CalledProcessError): echo(git.find_tag(match, strict=strict, git_dir=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 pretty_time(timestamp: str): """Format timestamp for human consumption."""
try: parsed = iso_8601.parse_datetime(timestamp) except ValueError: now = datetime.utcnow().replace(tzinfo=timezone.utc) try: delta = iso_8601.parse_delta(timestamp) except ValueError: delta = human_time.parse_timedelta(timestamp) parsed = now - d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_text(env: TextIOBase, package: str, tmpl: str): """Create output from Jinja template."""
if env: env_args = json_datetime.load(env) else: env_args = {} jinja_env = template.setup(package) echo(jinja_env.get_template(tmpl).render(**env_args))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time(ctx: Context, command: str): """Time the output of a command."""
with timer.Timing(verbose=True): proc = run(command, shell=True) ctx.exit(proc.returncode)
<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(cls, name, type_): """ Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry. """
if not issubclass(type_, Entry): raise exceptions.InvalidEntryType("%s is not a subclass of Entry" % str(type_)) cls._registry[name.lower()] = type_
<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(self, **kwargs): """ Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the en...
self.check_crossrefs() for value in self.values(): value.validate(**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 validate(self, raise_unsupported=False): """ Checks if the Entry instance includes all the required fields of its type. If ``raise_unsupported`` is set to ``...
fields = set(self.keys()) flattened_required_fields = set() required_errors = [] for field in self.required_fields: found = False if isinstance(field, (list, tuple)): # Check all alternatives for real_f in field: ...
<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(file_name, key): """ Print a value for the specified key. If key is not found xon_db exists with code 1. """
db = XonoticDB.load_path(file_name) value = db.get(key) if value is None: sys.exit(1) else: click.echo(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 set(file_name, key, value, new): """ Set a new value for the specified key. """
db = XonoticDB.load_path(file_name) if key not in db and not new: click.echo('Key %s is not found in the database' % key, file=sys.stderr) sys.exit(1) else: db[key] = value db.save(file_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 remove_cts_record(file_name, map, position): """ Remove cts record on MAP and POSITION """
db = XonoticDB.load_path(file_name) db.remove_cts_record(map, position) db.save(file_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 remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """
db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_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 merge_cts_records(file_name, crypto_idfp, crypto_idfps): """ Merge cts records made by CRYPTO_IDFPS to CRYPTO_IDFP """
db = XonoticDB.load_path(file_name) db.merge_cts_records(crypto_idfp, crypto_idfps) db.save(file_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 check_rotation(rotation): """checks rotation parameter if illegal value raises exception"""
if rotation not in ALLOWED_ROTATION: allowed_rotation = ', '.join(ALLOWED_ROTATION) raise UnsupportedRotation('Rotation %s is not allwoed. Allowed are %s' % (rotation, allowed_rotation))
<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_resize(resize): """checks resize parameter if illegal value raises exception"""
if resize is None: return resize = resize.lower().strip() if 'x' in resize: tmp = resize.lower().split('x') tmp = [x.strip() for x in resize.split('x')] if len(tmp) == 2 and tmp[0].isdigit() and tmp[1].isdigit(): return elif '%' in resize: tmp = res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_response(response): """ checks the response if the server returned an error raises an exception. """
if response.status_code < 200 or response.status_code > 300: raise ServerError('API requests returned with error: %s' % response.status_code) try: response_text = loads(response.text) except ValueError: raise ServerError('The API did not returned a JSON st...
<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_if_redirect(url): """ checks if server redirects url """
response = head(url, headers={'User-Agent': USER_AGENT}) if response.status_code >= 300 and response.status_code < 400: return response.headers['location'] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_backup(configuration, backup_data): """Celery task. It will extract the backup archive into a unique folder in the temporary directory specified in ...
extract_archive(backup_data['archive_path'], backup_data['workdir']) docker_client = Client(configuration['docker']['url']) container = run_container(docker_client, backup_data) return_code = docker_client.wait(container) print('Container return code: {}'.format(return_code)) ...
<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_files(module, dependencies_dict=None): """ Scan a module and its entire dependency tree to create a dict of all files and their modified time. @param ...
if dependencies_dict is None: dependencies_dict = dict() if hasattr(module, '__file__'): filename = module.__file__ if filename not in dependencies_dict: realname, modified_time = _get_filename_and_modified(filename) if realname and realname not in dependencies_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(): """ Scan all modules in the currently running app to create a dict of all files and their modified time. @note The scan only occurs the first time t...
if not _scanned: if not module_files(sys.modules['__main__'], _process_files): for module in sys.modules.values(): if hasattr(module, '__file__'): filename = module.__file__ if filename not in _process_files: realna...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False): """ Register a signal handler for `signal.SIGHUP` that checks for modified files and only acts if...
#noinspection PyUnusedLocal def handle_hup(signum, frame): changed = modified() if changed: if callable(signal_or_callable): func = signal_or_callable args = (changed,) op = 'Calling' try: name = si...
<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_segment_ended(self): ''' process end of the segment based on template ''' if self._state[1].value.endevent is not None: self.events.append((self._state[1].value.endevent, self._state[0], None)) if self._state[1].value.multiplier is 2: self.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 main(): """ Do the things! Return: 0 Exceptions: """
description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to = raw_input('To address > ') subject = raw_input('Subject > ') 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 send(self, jsonstr): """ Send jsonstr to the UDP collector """
udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.sendto(jsonstr.encode('utf-8'), self.addr)
<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_file(path): """Read a UTF-8 file from the package. Takes a list of strings to join to make the path"""
file_path = os.path.join(here, *path) with open(file_path, encoding="utf-8") as f: return f.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exec_file(path, name): """Extract a constant from a python file by looking for a line defining the constant and executing it."""
result = {} code = read_file(path) lines = [line for line in code.split('\n') if line.startswith(name)] exec("\n".join(lines), result) return result[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 pg_dump(db_name, backup_path): """Dump db_name to backup_path"""
logger.info("Dumping %s to %s", repr(db_name), repr(backup_path)) return shell( 'pg_dump "{db_name}" -U "{USER}" -h "{HOST}" ' "--schema=public --file={backup_path}".format( db_name=db_name, backup_path=backup_path, **DB ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_file_name(source, destination): """Create a filename for the destination zip file."""
number = 1 if os.path.exists(os.path.join(destination, os.path.basename(source) + '.zip')): while True: zip_filename = os.path.join(destination, os.path.basename(source) + '_' + str(number) + '.zip') if not os.path.exists(zip_filename): br...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _backup_compresslevel(self, dirs): """Create a backup file with a compresslevel parameter."""
# Only supported in Python 3.7+ with ZipFile(self.zip_filename, 'w', compresslevel=self.compress_level) as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): backup_zip.write(path, path[len(self.source):len(path)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _backup_pb_gui(self, dirs): """Create a zip backup with a GUI progress bar."""
import PySimpleGUI as sg # Legacy support with ZipFile(self.zip_filename, 'w') as backup_zip: for count, path in enumerate(dirs): backup_zip.write(path, path[len(self.source):len(path)]) if not sg.OneLineProgressMeter('Writing Zip Files', count + 1, l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _backup_pb_tqdm(self, dirs): """Create a backup with a tqdm progress bar."""
with ZipFile(self.zip_filename, 'w') as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): backup_zip.write(path, path[len(self.source):len(path)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backup(self, paths=None): """Backup method driver."""
if not paths: paths = self._get_paths() try: self._backup_compresslevel(paths) except TypeError: try: self._backup_pb_gui(paths) except ImportError: self._backup_pb_tqdm(paths) # Delete source if specified...
<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_uris(config): """ returns a tuple of total file size in bytes, and the list of files """
file_names = [] if config.INPUT_DATA is None: sys.stderr.write("you need to provide INPUT_DATA in config\n") sys.exit(1) if isinstance(config.INPUT_DATA, basestring): config.INPUT_DATA = [config.INPUT_DATA] file_size = 0 for uri in config.INPUT_DATA: for regex, uri_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 buildschema(_cls=None, **kwargs): """Class decorator used to build a schema from the decorate class. :param type _cls: class to decorate. :param kwargs: sche...
if _cls is None: return lambda _cls: buildschema(_cls=_cls, **kwargs) result = build(_cls, **kwargs) 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 funcschema(default=None, *args, **kwargs): """Decorator to use in order to transform a function into a schema."""
if default is None: return lambda default: funcschema(default=default, *args, **kwargs) return FunctionSchema(default=default, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_wiki_json(path='wikipedia_crawler_data.json', model=WikiItem, batch_len=100, db_alias='default', verbosity=2): """Read json file and create the approp...
return djdb.import_json(path=path, model=model, batch_len=batch_len, db_alias=db_alias, verbosity=verbosity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_item(self, item, crawler='wiki', truncate_strings=True, verbosity=0): """Import a single record from a Scrapy Item dict >> WikiItem().import_item({'ur...
item = dict(item) self.crawler = str(crawler) for k, v in self._item_mapping.iteritems(): if verbosity > 2: print('%r: %r' % (k, v)) value = item.get(k, v['default']) if value is None: continue try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """
output = ('%s=%s' % (k, quote(v)) for k, v in self.items()) return '&'.join(output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self): """ Error reporting is triggered when a form is checked for validity """
is_valid = super(GAErrorReportingMixin, self).is_valid() if self.is_bound and not is_valid: try: self.report_errors_to_ga(self.errors) except: # noqa: E722 logger.exception('Failed to report form errors to Google Analytics') return is_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 get_ga_event_category(self): """ Event category, defaults to form class name """
return self.ga_event_category or '%s.%s' % (self.__class__.__module__, self.__class__.__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 format_ga_hit(self, field_name, error_message): """ Format a single hit """
tracking_id = self.get_ga_tracking_id() if not tracking_id: warnings.warn('Google Analytics tracking ID is not set') return None query_dict = self.get_ga_query_dict() query_dict['tid'] = tracking_id query_dict['cid'] = self.get_ga_client_id() quer...
<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_ga_tracking_id(self): """ Retrieve tracking ID from settings """
if hasattr(settings, self.ga_tracking_id_settings_key): return getattr(settings, self.ga_tracking_id_settings_key) return super(GARequestErrorReportingMixin, self).get_ga_tracking_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_ga_client_id(self): """ Retrieve the client ID from the Google Analytics cookie, if available, and save in the current session """
request = self.get_ga_request() if not request or not hasattr(request, 'session'): return super(GARequestErrorReportingMixin, self).get_ga_client_id() if 'ga_client_id' not in request.session: client_id = self.ga_cookie_re.match(request.COOKIES.get('_ga', '')) ...
<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_ga_query_dict(self): """ Adds user agent and IP to the default hit parameters """
query_dict = super(GARequestErrorReportingMixin, self).get_ga_query_dict() request = self.get_ga_request() if not request: return query_dict user_ip = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')) user_ip = user_ip.split(',')[0].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 build_js(ctx, force=False): """Build all javascript files. """
for fname in JSX_FILENAMES: jstools.babel( ctx, '{pkg.source_js}/' + fname, '{pkg.django_static}/{pkg.name}/js/' + fname + '.js', force=force )
<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(ctx, less=False, docs=False, js=False, force=False): """Build everything and collectstatic. """
specified = any([less, docs, js]) buildall = not specified if buildall or less: less_fname = ctx.pkg.source_less / ctx.pkg.name + '.less' if less_fname.exists(): lessc.LessRule( ctx, src='{pkg.source_less}/{pkg.name}.less', dst='{...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch(ctx): """Automatically run build whenever a relevant file changes. """
watcher = Watcher(ctx) watcher.watch_directory( path='{pkg.source_less}', ext='.less', action=lambda e: build(ctx, less=True) ) watcher.watch_directory( path='{pkg.source_js}', ext='.jsx', action=lambda e: build(ctx, js=True) ) watcher.watch_directory( pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _force_float(v): """ Converts given argument to float. On fail logs warning and returns 0.0. Args: v (any): value to convert to float Returns: float: conver...
try: return float(v) except Exception as exc: return float('nan') logger.warning('Failed to convert {} to float with {} error. Using 0 instead.'.format(v, 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 dict(self): """Return a dict that can be passed into the ColumnStats constructor"""
try: skewness = self.skewness kurtosis = self.kurtosis except ZeroDivisionError: skewness = kurtosis = float('nan') base_cols = [ ('name', self.column_name), ('flags', self.flags), ('type', self.type.__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 run(self): """ Run the stats. The source must yield Row proxies. """
self._func, self._func_code = self.build() def process_row(row): try: self._func(self._stats, row) except TypeError as e: raise TypeError("Failed for '{}'; {}".format(self._func_code, e)) except KeyError: raise KeyEr...
<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_labs(format): """Gets Hackerspaces data from hackaday.io."""
hackerspaces_json = data_from_hackaday_io(hackaday_io_labs_map_url) hackerspaces = {} # Load all the Hackerspaces for i in hackerspaces_json: current_lab = Hackerspace() current_lab.id = i["id"] current_lab.url = "https://hackaday.io/hackerspace/" + current_lab.id curr...
<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_ramp_for_errors(ramp_data): """Checks ramp for errors. This is experiment specific checklist."""
error_list = [] keyframe_list = ramps.KeyFrameList(ramp_data['keyframes']) sorted_key_list = keyframe_list.sorted_key_list() channel_list = [ramps.Channel(ch_name, ramp_data['channels'][ch_name], keyframe_list) for ch_name in ramp_data['channels']] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _colourise(text: str, colour: str) -> str: """Colour text, if possible. Args: text: Text to colourise colour: Colour to display text in Returns: Colourised te...
if COLOUR: text = style(text, fg=colour, bold=True) 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 _apply(self, ctx: ExtensionContext) -> AugmentedDict: """ Performs the actual loading of an external resource into the current model. Args: ctx: The processin...
def process(pattern: Pattern[str], _str: str) -> Any: _match = pattern.match(_str) if _match is None: return _str # pragma: no cover # We got a match # Group 0: Whole match; Group 1: Our placeholder; # Group 2: file path to external 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 _apply(self, ctx: ExtensionContext) -> Any: """ Loads a yaml fragment from an external file. Args: ctx: The processing context. Returns: The external resource...
_, external_path = ctx.node return ctx.mentor.load_yaml(self.locator( external_path, cast(str, ctx.document) if Validator.is_file(document=ctx.document) 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 preprocess(self): ''' Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible. ''' self.processed_tables = [] self.flags_by_table = [] self.units_by_table = [] for 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 generate_blocks(self, assume_complete_blocks=None): ''' Identifies and extracts all blocks from the input tables. These blocks are logical identifiers for where related information resides in the original table. Any block can be converted into a row-titled table which can then be sti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def preprocess_worksheet(self, table, worksheet): ''' Performs a preprocess pass of the table to attempt naive conversions of data and to record the initial types of each cell. ''' table_conversion = [] flags = {} units = {} for rind, row in enumerate(tabl...