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 main(): """Entry point for command line usage."""
import colorama import argparse import logging import sys import os parser = argparse.ArgumentParser(prog="gulpless", description="Simple build system.") parser.add_argument("-v", "--version", action="version", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_kwnkb(mapper, connection, target): """Remove taxonomy file."""
if(target.kbtype == KnwKB.KNWKB_TYPES['taxonomy']): # Delete taxonomy file if os.path.isfile(target.get_filename()): os.remove(target.get_filename())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self, value): """Set name and generate the slug."""
self._name = value # generate slug if not self.slug: self.slug = KnwKB.generate_slug(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 kbtype(self, value): """Set kbtype."""
if value is None: # set the default value return # or set one of the available values kbtype = value[0] if len(value) > 0 else 'w' if kbtype not in ['t', 'd', 'w']: raise ValueError('unknown type "{value}", please use one 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 to_dict(self): """Return a dict representation of KnwKB."""
mydict = {'id': self.id, 'name': self.name, 'description': self.description, 'kbtype': self.kbtype} if self.kbtype == 'd': mydict.update((self.kbdefs.to_dict() if self.kbdefs else {}) or {}) return mydict
<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_dyn_config(self, field, expression, collection=None): """Set dynamic configuration."""
if self.kbdefs: # update self.kbdefs.output_tag = field self.kbdefs.search_expression = expression self.kbdefs.collection = collection db.session.merge(self.kbdefs) else: # insert self.kbdefs = KnwKBDDEF(output_tag=fiel...
<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_slug(name): """Generate a slug for the knowledge. :param name: text to slugify :return: slugified text """
slug = slugify(name) i = KnwKB.query.filter(db.or_( KnwKB.slug.like(slug), KnwKB.slug.like(slug + '-%'), )).count() return slug + ('-{0}'.format(i) if i > 0 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 query_exists(filters): """Return True if a kb with the given filters exists. E.g: KnwKB.query_exists(KnwKB.name.like('FAQ')) :param filters: filter for sqlal...
return db.session.query( KnwKB.query.filter( filters).exists()).scalar()
<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_dict(self): """Return a dict representation of KnwKBDDEF."""
return {'field': self.output_tag, 'expression': self.search_expression, 'coll_id': self.id_collection, 'collection': self.collection.name if self.collection 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 to_dict(self): """Return a dict representation of KnwKBRVAL."""
# FIXME remove 'id' dependency from invenio modules return {'id': self.m_key + "_" + str(self.id_knwKB), 'key': self.m_key, 'value': self.m_value, 'kbid': self.kb.id if self.kb else None, 'kbname': self.kb.name if self.kb 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 social_links(context, object, user=None, authed=False, downable=False, vote_down_msg=None): """ Outputs social links. At minimum, this will be Facebook and T...
# check if voting available voting = False if hasattr(object, 'votes'): voting = True return { 'object': object, 'url': object.get_absolute_url(), 'site': get_current_site(context.request), 'ctype': ContentType.objects.get_for_model(object), 'user'...
<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(obj): """Convienently render strings with the fabric context"""
def get_v(v): return v % env if isinstance(v, basestring) else v if isinstance(obj, types.StringType): return obj % env elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType): rv = [] for v in obj: rv.append(get_v(v)) elif isinstance(obj, t...
<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_wwln(file): """Read WWLN file"""
tmp = pd.read_csv(file, parse_dates=True, header=None, names=['date', 'time', 'lat', 'lon', 'err', '#sta']) # Generate a list of datetime objects with time to miliseconds list_dts = [] for dvals, tvals, in zip(tmp['date'], tmp['time']): list_dts.append(gen_datetime(dvals, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wwln_to_geopandas(file): """Read data from Blitzorg first using pandas.read_csv for convienence, and then convert lat, lon points to a shaleply geometry POIN...
tmp = pd.read_csv(file, parse_dates=True, header=None, names=['date', 'time', 'lat', 'lon', 'err', '#sta']) list_dts = [gen_datetime(dvals, tvals) for dvals, tvals in zip(tmp['date'], tmp['time'])] points = [[Point(tmp.lat[row], tmp.lon[row]), dt] for row...
<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_time_intervals(start, end, delta): """Create time intervals with timedelta periods using datetime for start and end """
curr = start while curr < end: yield curr curr += delta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_date(value): """ Convert timestamp to datetime and set everything to zero except a date """
dtime = value.to_datetime() dtime = (dtime - timedelta(hours=dtime.hour) - timedelta(minutes=dtime.minute) - timedelta(seconds=dtime.second) - timedelta(microseconds=dtime.microsecond)) return dtime
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_request(self, request): """Check if user is logged in"""
assert hasattr(request, 'user') if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(reverse(settings.LOGIN_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 prt_js(js, sort_keys=True, indent=4): """Print Json in pretty format. There's a standard module pprint, can pretty print python dict and list. But it doesn't...
print(js2str(js, sort_keys, indent))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string_SizeInBytes(size_in_bytes): """Make ``size in bytes`` human readable. Doesn"t support size greater than 1000PB. Usage:: 100 B 97.66 KB 95.37 MB 93.13 ...
res, by = divmod(size_in_bytes, 1024) res, kb = divmod(res, 1024) res, mb = divmod(res, 1024) res, gb = divmod(res, 1024) pb, tb = divmod(res, 1024) if pb != 0: human_readable_size = "%.2f PB" % (pb + tb / float(1024)) elif tb != 0: human_readable_size = "%.2f TB" % (tb + gb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True): """A simple url binary content download function with progress info. Warning: ...
msg = Messenger() if enable_verbose: msg.on() else: msg.off() msg.show("Downloading %s from %s..." % (save_as, url)) with open(save_as, "wb") as f: response = requests.get(url, stream=True) if not response.ok: print("http get error!") retur...
<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(hashcode, delta=False): """ decode a hashcode and get center coordinate, and distance between center and outer border """
lat, lon, lat_length, lon_length = _decode_c2i(hashcode) if hasattr(float, "fromhex"): latitude_delta = 90.0/(1 << lat_length) longitude_delta = 180.0/(1 << lon_length) latitude = _int_to_float_hex(lat, lat_length) * 90.0 + latitude_delta longitude = _int_to_float_hex(lon, lon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bbox(hashcode): """ decode a hashcode and get north, south, east and west border. """
lat, lon, lat_length, lon_length = _decode_c2i(hashcode) if hasattr(float, "fromhex"): latitude_delta = 180.0/(1 << lat_length) longitude_delta = 360.0/(1 << lon_length) latitude = _int_to_float_hex(lat, lat_length) * 90.0 longitude = _int_to_float_hex(lon, lon_length) * 180.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 save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """
formset.save() for form in formset.forms: if hasattr(form, 'nested_formsets') and form not in formset.deleted_forms: for nested_formset in form.nested_formsets: self.save_formset(request, form, nested_formset, change)
<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_valid_with_nesting(self, formsets): "Recursively validate all nested formsets" if not all_valid(formsets): return False for formset in formsets: if not formset.is_bound: pass for form in formset: if hasattr(form, 'neste...
<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(method, add_args, version=None, docstring=None, error_stream=sys.stderr): """Run the method as a script Add a '--version' argument Call add_args(parser)...
if version: _versions.append(version) try: args = parse_args( add_args, docstring and docstring or '%s()' % method.__name__) return _exit_ok if method(args) else _exit_fail except KeyboardInterrupt as e: ctrl_c = 3 return ctrl_c except Sys...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ingest(self, corpus_file): ''' load and parse a pre-formatted and cleaned text file. Garbage in, garbage out ''' corpus = open(corpus_file) total_letters = 0 total_words = 0 shortest_word = 100 for word in corpus.readlines(): # clean word word ...
<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_word(self, word=None): ''' creates a new word ''' word = word if not word == None else self.initial if not self.terminal in word: if len(word) > self.average_word_length and \ self.terminal in self.links[word[-self.chunk_size:]] \ and 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 existing_path(string): '''"Convert" a string to a string that is a path to an existing file.''' if not os.path.exists(string): msg = 'path {0!r} does not exist'.format(string) raise argparse.ArgumentTypeError(msg) return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def absolute_path(string): '''"Convert" a string to a string that is an absolute existing path.''' if not os.path.isabs(string): msg = '{0!r} is not an absolute path'.format(string) raise argparse.ArgumentTypeError(msg) if not os.path.exists(os.path.dirname(string)): msg = 'path {0!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 task_master(self): """A `TaskMaster` object for manipulating work"""
if self._task_master is None: self._task_master = build_task_master(self.config) return self._task_master
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_work_spec(self, args): '''Get the contents of the work spec from the arguments.''' with open(args.work_spec_path) as f: return yaml.load(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_work_spec_name(self, args): '''Get the name of the work spec from the arguments. This assumes :meth:`_add_work_spec_name_args` has been called, but will also work if just :meth:`_add_work_spec_args` was called instead. ''' if getattr(args, 'work_spec_name', Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_load(self, args): '''loads work_units into a namespace for a given work_spec --work-units file is JSON, one work unit per line, each line a JSON dict with the one key being the work unit key and the value being a data dict for the work unit. ''' work_spec = 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 do_delete(self, args): '''delete the entire contents of the current namespace''' namespace = self.config['namespace'] if not args.assume_yes: response = raw_input('Delete everything in {0!r}? Enter namespace: ' .format(namespace)) if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_work_specs(self, args): '''print the names of all of the work specs''' work_spec_names = [x['name'] for x in self.task_master.iter_work_specs()] work_spec_names.sort() for name in work_spec_names: self.stdout.write('{0}\n'.format(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 do_work_spec(self, args): '''dump the contents of an existing work spec''' work_spec_name = self._get_work_spec_name(args) spec = self.task_master.get_work_spec(work_spec_name) if args.json: self.stdout.write(json.dumps(spec, indent=4, sort_keys=True) + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_status(self, args): '''print the number of work units in an existing work spec''' work_spec_name = self._get_work_spec_name(args) status = self.task_master.status(work_spec_name) self.stdout.write(json.dumps(status, indent=4, sort_keys=True) + '\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_summary(self, args): '''print a summary of running rejester work''' assert args.json or args.text or (args.text is None) do_text = args.text xd = {} for ws in self.task_master.iter_work_specs(): name = ws['name'] status = self.task_master.status(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 do_work_units(self, args): '''list work units that have not yet completed''' work_spec_name = self._get_work_spec_name(args) if args.status: status = args.status.upper() statusi = getattr(self.task_master, status, None) if statusi is 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 do_work_unit(self, args): '''print basic details about work units''' work_spec_name = self._get_work_spec_name(args) for work_unit_name in args.unit: status = self.task_master.get_work_unit_status(work_spec_name, work_uni...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_retry(self, args): '''retry a specific failed job''' work_spec_name = self._get_work_spec_name(args) retried = 0 complained = False try: if args.all: while True: units = self.task_master.get_work_units( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_clear(self, args): '''remove work units from a work spec''' # Which units? work_spec_name = self._get_work_spec_name(args) units = args.unit or None # What to do? count = 0 if args.status is None: all = units is None count += self.ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_mode(self, args): '''get or set the global rejester worker mode''' if args.mode: mode = { 'idle': self.task_master.IDLE, 'run': self.task_master.RUN, 'terminate': self.task_master.TERMINATE }[args.mode] self.task_master.set_mode(mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_workers(self, args): '''list all known workers''' workers = self.task_master.workers(alive=not args.all) for k in sorted(workers.iterkeys()): self.stdout.write('{0} ({1})\n'.format(k, workers[k])) if args.details: heartbeat = self.task_master.get_he...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_run_one(self, args): '''run a single job''' work_spec_names = args.from_work_spec or None worker = SingleWorker(self.config, task_master=self.task_master, work_spec_names=work_spec_names, max_jobs=args.max_jobs) worker.register() rc = False starttime = time.time() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_number_of_particles(): """ Queries the ``dynac.short`` file for the number of particles used in the simulation. """
with open('dynac.short') as f: data_str = ''.join(line for line in f.readlines()) num_of_parts = int(data_str.split('Simulation with')[1].strip().split()[0]) return num_of_parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_process_pynac(file_list, pynac_func, num_iters=100, max_workers=8): """ Use a ProcessPool from the ``concurrent.futures`` module to execute ``num_iters...
with ProcessPoolExecutor(max_workers=max_workers) as executor: tasks = [executor.submit(do_single_dynac_process, num, file_list, pynac_func) for num in range(num_iters)] exc = [task.exception() for task in tasks if task.exception()] if exc: return exc else: return "No errors enc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pynac_in_sub_directory(num, file_list): """ A context manager to create a new directory, move the files listed in ``file_list`` to that directory, and change...
print('Running %d' % num) new_dir = 'dynacProc_%04d' % num if os.path.isdir(new_dir): shutil.rmtree(new_dir) os.mkdir(new_dir) for f in file_list: shutil.copy(f, new_dir) os.chdir(new_dir) yield os.chdir('..')
<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 simulation in the current directory. """
self._start_dynac_proc(stdin=subp.PIPE, stdout=subp.PIPE) str2write = self.name + '\r\n' if self._DEBUG: with open('pynacrun.log', 'a') as f: f.write(str2write) self.dynacProc.stdin.write(str2write.encode()) # The name field for pynEle in self.lattic...
<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(self, format_target, remove_obsolete=True): """ Changes the internal self.format_string_object format target based on input. Also checks to see if inp...
original_format, original_format_order = (self.format, self.format_order) try: format_target = self.CFG.get(format_target, return_type=str, throw_null_return_error=True) except (errors.ResourceNotFoundError, KeyError): pass self.format_string_object.swap_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 initialize_format_options(self, format_target=''): """ First attempts to use format_target as a config path or gets the default format if it's invalid or is ...
try: if format_target: self.format = format_target else: raise errors.FormatError except errors.FormatError: self.format_string_object.swap_format(self.CFG.get(self.DEFAULT_FORMAT_PATH, return_type=str))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_options(cls): """ Stores options from the config file """
cls.CONFIG_OPTIONS = cls.CFG.get(cls.CONFIG_PATH, return_type=dict)
<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_dict(self, *args, **kwargs): """ Takes variable inputs, compiles them into a dictionary then merges it to the current nomenclate's state :param args: (...
input_dict = self._convert_input(*args, **kwargs) if input_dict: self._sift_and_init_configs(input_dict) self.token_dict.merge_serialization(input_dict)
<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_token_settings(cls, token, default=None): """ Get the value for a specific token as a dictionary or replace with default :param token: str, token to quer...
setting_dict = {} for key, value in iteritems(cls.__dict__): if '%s_' % token in key and not callable(key) and not isinstance(value, tokens.TokenAttr): setting_dict[key] = cls.__dict__.get(key, default) return setting_dict
<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_tokens_from_swap_format(self, original_format, original_format_order, remove_obsolete=True): """ Updates tokens based on a swap format call that will...
old_format_order = [_.lower() for _ in original_format_order] new_format_order = [_.lower() for _ in self.format_order] if hasattr(self, 'token_dict') and self.format != original_format: old_tokens = [token for token in list(set(old_format_order) - set(new_format_order)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_input(self, *args, **kwargs): """ Takes variable inputs :param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be conver...
args = [arg.state if isinstance(arg, Nomenclate) else arg for arg in args] input_dict = combine_dicts(*args, **kwargs) return input_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matchiter(r, s, flags=0): """ Yields contiguous MatchObjects of r in s. Raises ValueError if r eventually doesn't match contiguously. """
if isinstance(r, basestring): r = re.compile(r, flags) i = 0 while s: m = r.match(s) g = m and m.group(0) if not m or not g: raise ValueError("{}: {!r}".format(i, s[:50])) i += len(g) s = s[len(g):] yield 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 matchall(r, s, flags=0): """ Returns the list of contiguous string matches of r in s, or None if r does not successively match the entire s. """
try: return [m.group(0) for m in matchiter(r, s, flags)] except ValueError: 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 check_subconfig(config, name, sub): """Validate the configuration of an object within this. This calls :meth:`Configurable.check_config` or equivalent on `su...
subname = sub.config_name subconfig = config.setdefault(subname, {}) if not isinstance(subconfig, collections.Mapping): raise ProgrammerError('configuration for {0} in {1} must be a mapping' .format(subname, name)) checker = getattr(sub, 'check_config', None) i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cmor_fp_meta(fp): """Processes a CMOR style file path. Section 3.1 of the `Data Reference Syntax`_ details: The standard CMIP5 output tool CMOR optionall...
# Copy metadata list then reverse to start at end of path directory_meta = list(CMIP5_FP_ATTS) # Prefer meta extracted from filename meta = get_dir_meta(fp, directory_meta) meta.update(get_cmor_fname_meta(fp)) return meta
<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_datanode_fp_meta(fp): """Processes a datanode style file path. Section 3.2 of the `Data Reference Syntax`_ details: It is recommended that ESGF data node...
# Copy metadata list then reverse to start at end of path directory_meta = list(CMIP5_DATANODE_FP_ATTS) # Prefer meta extracted from filename meta = get_dir_meta(fp, directory_meta) meta.update(get_cmor_fname_meta(fp)) return meta
<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_cmor_fname_meta(fname): """Processes a CMOR style file name. Section 3.3 of the `Data Reference Syntax`_ details: filename = <variable name>_<mip_table>_...
if '/' in fname: fname = os.path.split(fname)[1] fname = os.path.splitext(fname)[0] meta = fname.split('_') res = {} try: for key in CMIP5_FNAME_REQUIRED_ATTS: res[key] = meta.pop(0) except IndexError: raise PathError(fname) # Determine presence and or...
<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, once=False): """Runs the reactor in the main thread."""
self._once = once self.start() while self.running: try: time.sleep(1.0) except KeyboardInterrupt: self.stop() self.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_to_enc_filename(fname): """ Converts the filename of a cleartext file and convert it to an encrypted filename :param fname: :return: filename of encryp...
if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') if fname.lower().endswith('.enc.json'): raise CredkeepException('File already encrypted') enc_fname = fname[:-4] + 'enc.json' return enc_fname if exists(enc_fname) 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 enc_to_clear_filename(fname): """ Converts the filename of an encrypted file to cleartext :param fname: :return: filename of clear secret file if found, else...
if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') if not fname.lower().endswith('.enc.json'): raise CredkeepException('Not filename of encrypted file') clear_fname = fname.replace('.enc.json', '.json') print clear_fname return clear_fname if exis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap='Blues', alpha=1, grid=False, colorbar=True, vmax='auto', vmin='auto', crop=True): """ convenience func...
plt.figure(fig.number) ax = fig.gca() # set vmax and vmin vma = np.amax(hist_matrix) if vmax == 'auto' else vmax vmi = np.amin(hist_matrix) if vmin == 'auto' else vmin # an error check if vma <= vmi: vma = vmi + 1 # grid the space for pcolormesh x_grid, y_grid = np.meshgr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def heatmap(x, y, step=None, min_pt=None, max_pt=None, colormap='Blues', alpha=1, grid=False, colorbar=True, scale='lin', vmax='auto', vmin='auto', crop=True): "...
(x_vec, y_vec, hist_matrix) = calc_2d_hist(x, y, step, min_pt, max_pt) # simple in this case because it is positive counts if scale == 'log': for row in hist_matrix: for i, el in enumerate(row): row[i] = 0 if row[i] == 0 else log10(row[i]) # plot fig = plt.figu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ext_language(ext, exts=None): """Language of the extension in those extensions If exts is supplied, then restrict recognition to those exts only If exts is n...
languages = { '.py': 'python', '.py2': 'python2', '.py3': 'python3', '.sh': 'bash', '.bash': 'bash', '.pl': 'perl', '.js': 'javascript', '.txt': 'english', } ext_languages = {_: languages[_] for _ in exts} if exts else languages return ext...
<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_language(script, exts=None): """Determine the script's language extension True If exts are given they restrict which extensions are allowed True If ther...
if not script.isfile(): return None if script.ext: return ext_language(script.ext, exts) shebang = script.shebang() return shebang and str(shebang.name) or 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 makepath(s, as_file=False): """Make a path from a string Expand out any variables, home squiggles, and normalise it See also http://stackoverflow.com/questio...
if s is None: return None result = FilePath(s) if (os.path.isfile(s) or as_file) else DirectPath(s) return result.expandall()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cd(path_to): # pylint: disable=invalid-name """cd to the given path If the path is a file, then cd to its parent directory Remember current directory before ...
if path_to == '-': if not cd.previous: raise PathError('No previous directory to return to') return cd(cd.previous) if not hasattr(path_to, 'cd'): path_to = makepath(path_to) try: previous = os.getcwd() except OSError as e: if 'No such file or directo...
<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_needed(pattern, path_to_directory, wanted): """Make a method to check if an item matches the pattern, and is wanted If wanted is None just check the pat...
if wanted: def needed(name): return fnmatch(name, pattern) and wanted( os.path.join(path_to_directory, name)) return needed else: return lambda name: fnmatch(name, pattern)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_items(path_to_directory, pattern, wanted): """All items in the given path which match the given glob and are wanted"""
if not path_to_directory: return set() needed = make_needed(pattern, path_to_directory, wanted) return [os.path.join(path_to_directory, name) for name in _names_in_directory(path_to_directory) if needed(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 contains_glob(path_to_directory, pattern, wanted=None): """Whether the given path contains an item matching the given glob"""
if not path_to_directory: return False needed = make_needed(pattern, path_to_directory, wanted) for name in _names_in_directory(path_to_directory): if needed(name): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tab_complete(string): """Finish file names "left short" by tab-completion For example, if an argument is "fred." and no file called "fred." exists but "fred....
if is_option(string): return string if not missing_extension(string): return string if os.path.isfile(string): return string extended_files = [f for f in extend(string) if os.path.isfile(f)] try: return extended_files[0] except IndexError: return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyc_to_py(path_to_file): """Change some file extensions to those which are more likely to be text True """
stem, ext = os.path.splitext(path_to_file) if ext == '.pyc': return '%s.py' % stem return path_to_file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_existing_file(self, filepath): """Return the file class for existing files only"""
if os.path.isfile(filepath) and hasattr(self, '__file_class__'): return self.__file_class__(filepath) # pylint: disable=no-member return self.__class__(filepath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirpaths(self): """Split the dirname into individual directory names An absolute path starts with an empty string, a relative path does not True """
parts = self.parts() result = [DotPath(parts[0] or '/')] for name in parts[1:]: result.append(result[-1] / name) 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 parts(self): """Split the path into parts like Pathlib """
parts = self.split(os.path.sep) parts[0] = parts[0] and parts[0] or '/' return parts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def short_relative_path_to(self, destination): """The shorter of either the absolute path of the destination, or the relative path to it ../build/python.tar /mnt...
relative = self.relpathto(destination) absolute = self.__class__(destination).abspath() if len(relative) < len(absolute): return relative return absolute
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend_by(self, extension): """The path to the file changed to use the given extension <FilePath '/path/to/fred.txt'> <FilePath '/path/to/fred.tmp'> <FilePat...
copy = self[:] filename, _ = os.path.splitext(copy) return self.__class__('%s.%s' % (filename, extension.lstrip('.')))
<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_file_exist(self): """Make sure the parent directory exists, then touch the file"""
self.parent.make_directory_exist() self.parent.touch_file(self.name) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def language(self): """The language of this file"""
try: return self._language except AttributeError: self._language = find_language(self, getattr(self, 'exts', None)) return self._language
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_remove(self): """Try to remove the path If it is a directory, try recursive removal of contents too """
if self.islink(): self.unlink() elif self.isfile(): self.remove() elif self.isdir(): self.empty_directory() if self.isdir(): self.rmdir() else: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def empty_directory(self): """Remove all contents of a directory Including any sub-directories and their contents"""
for child in self.walkfiles(): child.remove() for child in reversed([d for d in self.walkdirs()]): if child == self or not child.isdir(): continue child.rmdir()
<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_file_exist(self, filename=None): """Make the directory exist, then touch the file If the filename is None, then use self.name as filename """
if filename is None: path_to_file = FilePath(self) path_to_file.make_file_exist() return path_to_file else: self.make_directory_exist() path_to_file = self.touch_file(filename) return FilePath(path_to_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def touch_file(self, filename): """Touch a file in the directory"""
path_to_file = self.__file_class__(os.path.join(self, filename)) path_to_file.touch() return path_to_file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_sub_paths(self, sub_paths): """Those in the given list of sub_paths which do exist"""
paths_to_subs = [self / _ for _ in sub_paths] return [_ for _ in paths_to_subs if _.exists()]
<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_preset(self): """ Loads preset if it is specified in the .frigg.yml """
if 'preset' in self.settings.preview: with open(os.path.join(os.path.dirname(__file__), 'presets.yaml')) as f: presets = yaml.load(f.read()) if self.settings.preview['preset'] in presets: self.preset = presets[self.settings.preview['preset']] ...
<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_command(self, cmd, *argv): """ Runs a command. :param cmd: command to run (key at the registry) :param argv: arguments that would be passed to the comma...
parser = self.get_parser() args = [cmd] + list(argv) namespace = parser.parse_args(args) self.run_command(namespace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, argv=None): """ Executes command based on given arguments. """
if self.completion: self.autocomplete() parser = self.get_parser() namespace = parser.parse_args(argv) if hasattr(namespace, 'func'): self.run_command(namespace)
<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_commands_to_register(self): """ Returns dictionary with commands given during construction. If value is a string, it would be converted into proper class...
return dict((key, get_class(value)) for key, value in self.simple_commands.items())
<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_path_directories(): """Return a list of all the directories on the path. """
pth = os.environ['PATH'] if sys.platform == 'win32' and os.environ.get("BASH"): # winbash has a bug.. if pth[1] == ';': # pragma: nocover pth = pth.replace(';', ':', 1) return [p.strip() for p in pth.split(os.pathsep) if p.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 _listdir(pth, extensions): """Non-raising listdir."""
try: return [fname for fname in os.listdir(pth) if os.path.splitext(fname)[1] in extensions] except OSError: # pragma: nocover pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def which(filename, interactive=False, verbose=False): """Yield all executable files on path that matches `filename`. """
exe = [e.lower() for e in os.environ.get('PATHEXT', '').split(';')] if sys.platform != 'win32': # pragma: nocover exe.append('') name, ext = os.path.splitext(filename) has_extension = bool(ext) if has_extension and ext.lower() not in exe: raise ValueError("which can only search fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enableEffect(self, name, **kwargs): """Enable an effect in the KezMenu."""
if name not in VALID_EFFECTS: raise KeyError("KezMenu doesn't know an effect of type %s" % name) self.__getattribute__( '_effectinit_{}'.format(name.replace("-", "_")) )(name, **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 disableEffect(self, name): """Disable an effect."""
try: del self._effects[name] self.__getattribute__( '_effectdisable_%s' % name.replace("-", "_") )() except KeyError: pass except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateEffects(self, time_passed): """Update method for the effects handle"""
for name in self._effects: update_func = getattr( self, '_effectupdate_{}'.format(name.replace("-", "_")), ) update_func(time_passed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _effectinit_enlarge_font_on_focus(self, name, **kwargs): """Init the effect that enlarge the focused menu entry. Keyword arguments can contain enlarge_time a...
self._effects[name] = kwargs if "font" not in kwargs: raise TypeError( "enlarge_font_on_focus: font parameter is required" ) if "size" not in kwargs: raise TypeError( "enlarge_font_on_focus: size parameter is required" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _effectupdate_enlarge_font_on_focus(self, time_passed): """Gradually enlarge the font size of the focused line."""
data = self._effects['enlarge-font-on-focus'] fps = data['raise_font_ps'] final_size = data['size'] * data['enlarge_factor'] for i, option in enumerate(self.options): if i == self.option: # Raise me if option['font_current_size'] < final_size...