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 Msg(validator, message): """ Wraps the given validator callable, replacing any error messages raised. """
@wraps(Msg) def built(value): try: return validator(value) except Error as e: e.message = message raise e return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Default(default): """ Creates a validator callable that replaces ``None`` with the specified default value. """
@wraps(Default) def built(value): if value == None: return default return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Eq(value, message="Not equal to {!s}"): """ Creates a validator that compares the equality of the given value to ``value``. A custom message can be specified with ``message``. It will be formatted with ``value``. """
@wraps(Eq) def built(_value): if _value != value: raise Error(message.format(value)) return _value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Instance(expected, message="Not an instance of {}"): """ Creates a validator that checks if the given value is an instance of ``expected``. A custom message can be specified with ``message``. """
@wraps(Instance) def built(value): if not isinstance(value, expected): raise Error(message.format(expected.__name__)) return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Coerce(type, message="Not a valid {} value"): """ Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error if the coercion fails. A custom message can be specified with ``message``. """
@wraps(Coerce) def built(value): try: return type(value) except (TypeError, ValueError) as e: raise Error(message.format(type.__name__)) return built
<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(validator): """ Creates a validator that runs the given validator on every item in a list or other collection. The validator can mutate the values. Any raised errors will be collected into a single ``Invalid`` error. Their paths will be replaced with the index of the item. Will raise an error if the input value is not iterable. """
@wraps(List) def built(value): if not hasattr(value, '__iter__'): raise Error("Must be a list") invalid = Invalid() for i, item in enumerate(value): try: value[i] = validator(item) except Invalid as e: for error in e: error.path.insert(0, i) invalid.append(error) except Error as e: e.path.insert(0, i) invalid.append(e) if len(invalid): raise invalid return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"): """ Creates a validator that checks if the given numeric value is in the specified range, inclusive. Accepts values specified by ``numbers.Number`` only, excluding booleans. The error messages raised can be customized with ``min_message`` and ``max_message``. The ``min`` and ``max`` arguments are formatted. """
@wraps(Range) def built(value): if not isinstance(value, numbers.Number) or isinstance(value, bool): raise Error("Not a number") if min is not None and min > value: raise Error(min_message.format(min=min, max=max)) if max is not None and value > max: raise Error(max_message.format(min=min, max=max)) return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def NotEmpty(): """ Creates a validator that validates the given string is not empty. Will raise an error for non-string types. """
@wraps(NotEmpty) def built(value): if not isinstance(value, six.string_types) or not value: raise Error("Must not be empty") return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Uuid(to_uuid=True): """ Creates a UUID validator. Will raise an error for non-string types and non-UUID values. The given value will be converted to an instance of ``uuid.UUID`` unless ``to_uuid`` is ``False``. """
@wraps(Uuid) def built(value): invalid = Error("Not a valid UUID") if isinstance(value, uuid.UUID): return value elif not isinstance(value, six.string_types): raise invalid try: as_uuid = uuid.UUID(value) except (ValueError, AttributeError) as e: raise invalid if to_uuid: return as_uuid return value return built
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def counterpart_found(string, counterpart, options, rc_so_far): """The sunny-day action is to echo the counterpart to stdout. :param string: The lookup string (UNUSED) :param counterpart: The counterpart that the string mapped to :param options: ArgumentParser or equivalent to provide options.no_newline :param rc_so_far: Stays whatever value it was. """
format = "%s" if options.no_newline else "%s\n" sys.stdout.write(format % (counterpart)) return rc_so_far or 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 no_counterpart_found(string, options, rc_so_far): """Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equivalent to provide options.else_action, options.else_errno, options.no_newline :param rc_so_far: Becomes set to the value set in options. """
logger.debug("options.else_action: %s", options.else_action) if options.else_action == "passthrough": format_list = [string] output_fd = sys.stdout elif options.else_action == "exception": raise KeyError("No counterpart found for: %s" % (string)) elif options.else_action == "error": format_list = ["# No counterpart found for: %s" % (string)] output_fd = sys.stderr if not options.no_newline: format_list.append("\n") output_fd.write("".join(format_list)) return options.else_errno
<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_input(options): """First send strings from any given file, one string per line, sends any strings provided on the command line. :param options: ArgumentParser or equivalent to provide options.input and options.strings. :return: string """
if options.input: fp = open(options.input) if options.input != "-" else sys.stdin for string in fp.readlines(): yield string if options.strings: for string in options.strings: yield 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 register_options(this_class, argparser): """This class method is called so that ConfigFromFile can tell the command-line parser to register the options specific to the class. :param this_class: Not used (required by @classmethod interface) :param argparser: The argparser instance being prepared for use. """
default_path = this_class.rc_file_basename default_basename = os.path.basename(default_path) argparser.add_argument('-c', "--config-file", default=default_path, help=("Configuration file to use for lookups " + "(replaces DEFAULT=%s " % (default_path) + "but not ~/%s)" % (default_basename)))
<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_and_handle_includes(self, from_file): """Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed. """
logger.debug("Check/handle includes from %s", from_file) try: paths = self._parser.get("INCLUDE", "paths") except (config_parser.NoSectionError, config_parser.NoOptionError) as exc: logger.debug("_check_and_handle_includes: EXCEPTION: %s", exc) return paths_lines = [p.strip() for p in paths.split("\n")] logger.debug("paths = %s (wanted just once; CLEARING)", paths_lines) self._parser.remove_option("INCLUDE", "paths") for f in paths_lines: abspath = (f if os.path.isabs(f) else os.path.abspath( os.path.join(os.path.dirname(from_file), f))) use_path = os.path.normpath(abspath) if use_path in self._parsed_files: raise RecursionInConfigFile("In %s: %s already read", from_file, use_path) self._parsed_files.append(use_path) self._handle_rc_file(use_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 extract_imports(script): """Extract all imports from a python script"""
if not os.path.isfile(script): raise ValueError('Not a file: %s' % script) parse_tree = parse_python(script) result = find_imports(parse_tree) result.path = script 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 combine_counts( fns, define_sample_name=None, ): """ Combine featureCounts output files for multiple samples. Parameters fns : list of strings Filenames of featureCounts output files to combine. define_sample_name : function A function mapping the featureCounts output filenames to sample names. If this is not provided, the header of the last column in the featureCounts output will be used as the sample name. Returns ------- combined_counts : pandas.DataFrame Combined featureCount counts. """
counts = [] for fn in fns: df = pd.read_table(fn, skiprows=1, index_col=0) counts.append(df[df.columns[-1]]) combined_counts = pd.DataFrame(counts).T if define_sample_name: names = [define_sample_name(x) for x in fns] combined_counts.columns = names combined_counts.index.name = '' return combined_counts
<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_to_inventory(self): """Adds this server and its hostvars to the ansible inventory."""
self.stack.add_host(self.hostname, self.groups, self.hostvars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect_all(a, b): """\ Asserts that two iterables contain the same values. """
assert all(_a == _b for _a, _b in zip_longest(a, 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 coroutine(func): """ A decorator to wrap a generator function into a callable interface. 2 5 Traceback (most recent call last): StopIteration As you can see, this lets you keep state between calls easily, as expected from a generator, while calling the function looks like a function. The same without `@coroutine` would look like this: 0 2 5 Traceback (most recent call last): StopIteration Here is an example that shows how to translate traditional functions to use this decorator: 3 6 3 6 The two differences are that a) using traditional functions, func1 and func2 don't share any context and b) using the decorator, both calls use the same function name, and calling the function is limited to wice (in this case). """
def decorator(*args, **kwargs): generator = func(*args, **kwargs) next(generator) return lambda *args: generator.send(args) return decorator
<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_entity(self, entity, second=False): ''' Add entity to world. entity is of type Entity ''' if not entity in self._entities: if second: self._entities.append(entity) else: entity.set_world(self) else: raise DuplicateEntityError(entity)
<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_entity_to_group(self, entity, group): ''' Add entity to a group. If group does not exist, entity will be added as first member entity is of type Entity group is a string that is the name of the group ''' if entity in self._entities: if group in self._groups: self._groups[group].append(entity) else: self._groups[group] = [entity] else: raise UnmanagedEntityError(entity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def deregister_entity_from_group(self, entity, group): ''' Removes entity from group ''' if entity in self._entities: if entity in self._groups[group]: self._groups[group].remove(entity) else: raise UnmanagedEntityError(entity)
<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_entity(self, entity, second=False): ''' Removes entity from world and kills entity ''' if entity in self._entities: if second: for group in self._groups.keys(): if entity in self._groups[group]: self.deregister_entity_from_group(entity, group) self._entities.remove(entity) else: entity.kill() else: raise UnmanagedEntityError(entity)
<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_system(self, system): ''' Removes system from world and kills system ''' if system in self._systems: self._systems.remove(system) else: raise UnmanagedSystemError(system)
<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_entity_by_tag(self, tag): ''' Get entity by tag tag is a string that is the tag of the Entity. ''' matching_entities = list(filter(lambda entity: entity.get_tag() == tag, self._entities)) if matching_entities: return matching_entities[0] else: 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 get_entities_by_components(self, *components): ''' Get entity by list of components All members of components must be of type Component ''' return list(filter(lambda entity: set(components) <= set(map(type, entity.get_components())), self._entities))
<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_world(self, world): ''' Sets the world an entity belongs to. Checks for tag conflicts before adding. ''' if world.get_entity_by_tag(self._tag) and self._tag != '': raise NonUniqueTagError(self._tag) else: self._world = world world.add_entity(self, True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
<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_component(self, component): ''' Adds a Component to an Entity ''' if component not in self._components: self._components.append(component) else: # Replace Component self._components[self._components.index(component)] = 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 get_component(self, component_type): ''' Gets component of component_type or returns None ''' matching_components = list(filter(lambda component: isinstance(component, component_type), self._components)) if matching_components: return matching_components[0] else: 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 write_quota(outbytes: int, outfn: Path) -> Union[None, int]: """ aborts writing if not enough space on drive to write """
if not outfn: return None anch = Path(outfn).resolve().anchor freeout = shutil.disk_usage(anch).free if freeout < 10 * outbytes: raise IOError(f'out of disk space on {anch}.' '{freeout/1e9} GB free, wanting to write {outbytes/1e9} GB.') return freeout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sixteen2eight(I: np.ndarray, Clim: tuple) -> np.ndarray: """ scipy.misc.bytescale had bugs inputs: ------ I: 2-D Numpy array of grayscale image data Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image Michael Hirsch, Ph.D. """
Q = normframe(I, Clim) Q *= 255 # stretch to [0,255] as a float return Q.round().astype(np.uint8)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def req2frame(req, N: int=0): """ output has to be numpy.arange for > comparison """
if req is None: frame = np.arange(N, dtype=np.int64) elif isinstance(req, int): # the user is specifying a step size frame = np.arange(0, N, req, dtype=np.int64) elif len(req) == 1: frame = np.arange(0, N, req[0], dtype=np.int64) elif len(req) == 2: frame = np.arange(req[0], req[1], dtype=np.int64) elif len(req) == 3: # this is -1 because user is specifying one-based index frame = np.arange(req[0], req[1], req[2], dtype=np.int64) - 1 # keep -1 ! else: # just return all frames frame = np.arange(N, dtype=np.int64) return frame
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imgwriteincr(fn: Path, imgs, imgslice): """ writes HDF5 huge image files in increments """
if isinstance(imgslice, int): if imgslice and not (imgslice % 2000): print(f'appending images {imgslice} to {fn}') if isinstance(fn, Path): # avoid accidental overwriting of source file due to misspecified command line assert fn.suffix == '.h5', 'Expecting to write .h5 file' with h5py.File(fn, 'r+') as f: f['/rawimg'][imgslice, :, :] = imgs elif isinstance(fn, h5py.File): f['/rawimg'][imgslice, :, :] = imgs else: raise TypeError( f'{fn} must be Path or h5py.File instead of {type(fn)}')
<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_js(js, abspath, fastmode=False, compress=False, enable_verbose=True): """A stable version of dump_js, silently overwrite existing file. When your program been interrupted, you lose nothing. Typically if your program is interrupted by any reason, it only leaves a incomplete file. If you use replace=True, then you also lose your old file. So a bettr way is to: 1. dump json to a temp file. 2. when it's done, rename it to #abspath, overwrite the old one. This way guarantee atomic write. :param js: Serializable python object. :type js: dict or list :param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz`` (for compressed json). :type abspath: string :param fastmode: (default False) If ``True``, then dumping json without sorted keys and pretty indent, and it's faster and smaller in size. :type fastmode: boolean :param compress: (default False) If ``True``, use GNU program gzip to compress the json file. Disk usage can be greatly reduced. But you have to use :func:`load_js(abspath, compress=True)<load_js>` in loading. :type compress: boolean :param enable_verbose: (default True) Trigger for message. :type enable_verbose: boolean Usage:: Complete! Elapse 0.002432 sec **中文文档** 在对文件进行写入时, 如果程序中断, 则会留下一个不完整的文件。如果你使用了覆盖式 写入, 则你同时也丢失了原文件。所以为了保证写操作的原子性(要么全部完成, 要么全部 都不完成), 更好的方法是: 首先将文件写入一个临时文件中, 完成后再讲文件重命名, 覆盖旧文件。这样即使中途程序被中断, 也仅仅是留下了一个未完成的临时文件而已, 不会 影响原文件。 参数列表 :param js: 可Json化的Python对象 :type js: ``字典`` 或 ``列表`` :param abspath: 写入文件的路径。扩展名必须为 ``.json`` 或 ``.gz``, 其中gz用于被压 缩的Json :type abspath: ``字符串`` :param replace: (默认 False) 当为``True``时, 如果写入路径已经存在, 则会自动覆盖 原文件。而为``False``时, 则会抛出异常。防止误操作覆盖源文件。 :type replace: ``布尔值`` :param compress: (默认 False) 当为``True``时, 使用开源压缩标准gzip压缩Json文件。 通常能让文件大小缩小10-20倍不等。如要读取文件, 则需要使用函数 :func:`load_js(abspath, compress=True)<load_js>`. :type compress: ``布尔值`` :param enable_verbose: (默认 True) 是否打开信息提示开关, 批处理时建议关闭. :type enable_verbose: ``布尔值`` """
abspath = str(abspath) # try stringlize temp_abspath = "%s.tmp" % abspath dump_js(js, temp_abspath, fastmode=fastmode, 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 migrate_constituencies(apps, schema_editor): """ Re-save constituencies to recompute fingerprints """
Constituency = apps.get_model("representatives", "Constituency") for c in Constituency.objects.all(): c.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 treeprint(data, render_only=False, file=None, **options): """ Render a tree structure based on generic python containers. The keys should be titles and the values are children of the node or None if it's an empty leaf node; Primitives are valid leaf node labels too. E.g. sample = { "Leaf 1": None, "Leaf 2": "I have a label on me", "Branch A": { "Sub Leaf 1 with float label": 3.14, "Sub Branch": { "Deep Leaf": None } }, "Branch B": { "Sub Leaf 2": None } } """
def getiter(obj): if isinstance(obj, collections.abc.Mapping): return obj.items() elif (isinstance(obj, collections.abc.Iterable) and not isinstance(obj, str)): return enumerate(obj) def cycle_check(item, seen=set()): item_id = id(item) if item_id in seen: raise ValueError('Cycle detected for: %s' % repr(item)) else: seen.add(item_id) def crawl(obj, cc=cycle_check): cc(obj) objiter = getiter(obj) if objiter is None: yield TreeNode(obj) else: for key, item in objiter: if isinstance(item, collections.abc.Iterable) and \ not isinstance(item, str): yield TreeNode(key, children=crawl(item)) elif item is None: yield TreeNode(key) else: yield TreeNode(key, label=item) t = Tree(**options) render_gen = t.render(crawl(data)) if render_only: return render_gen else: file = sys.stdout if file is None else file conv = (lambda x: x.plain()) if not file.isatty() else (lambda x: x) for x in render_gen: print(conv(x), file=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 terminal_size(self): """Gets the terminal columns size."""
try: _, columns = os.popen('stty size', 'r').read().split() return min(int(columns) - 10, 100) except ValueError: return self.default_terminal_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 bar(self, progress): """Shows on the stdout the progress bar for the given progress."""
if not hasattr(self, "_limit") or not self._limit: self._limit = self.terminal_size() graph_progress = int(progress * self._limit) self.stdout.write('\r', ending='') progress_format = "[%-{}s] %d%%".format(self._limit) self.stdout.write( self.style.SUCCESS(progress_format % (self.progress_symbol * graph_progress, int(progress * 100))), ending='' ) self.stdout.flush()
<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, options): """Handles security groups operations."""
whitelist = dict( name=options["name"], description=options.get("description", "<empty>")) return self._agent.client.compute.security_groups.create(**whitelist)
<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_args(args): """ Load a config file. Merges CLI args and validates. """
config = kaptan.Kaptan(handler='yaml') conf_parent = os.path.expanduser('~') conf_app = '.clancy' conf_filename = 'config.yaml' conf_dir = os.path.join(conf_parent, conf_app) for loc in [os.curdir, conf_dir]: configpath = os.path.join(loc, conf_filename) try: if os.path.isfile(configpath): config.import_config(configpath) break except (ValueError, ParserError, ScannerError): warn("Ignoring invalid valid yaml file {}".format(configpath)) config = (config.configuration_data if config.configuration_data is not None else {}) # Prepend '--' to conf file keys so it matches docopt. This is the dumbest # thing in the world. for key, val in config.items(): config['--'+key] = val del config[key] return validate(merge(args, config))
<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_language(language_code=None): """ Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found """
if not language_code: language_code = settings.LANGUAGE_CODE languages = dict(settings.LANGUAGES).keys() # first try if there is an exact language if language_code in languages: return language_code # otherwise split the language code if possible, so iso3 language_code = language_code.split("-")[0] if language_code not in languages: raise ImproperlyConfigured("No match in LANGUAGES for LANGUAGE_CODE %s" % settings.LANGUAGE_CODE) return language_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 as_method(self, docstring=""): """ Converts this action to a function or method. An optional docstring may be passed. """
method = lambda obj, *args, **kwargs: self(obj, *args, **kwargs) if docstring: method.__doc__ = docstring return method
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create(self, rawtitle): """Create a page with this title, if it doesn't exist. This method first checks whether a page with the same slug (sanitized name) exists_on_disk. If it does, it doesn't do antyhing. Otherwise, the relevant attributes are created. Nothing is written to disc (to the source file). You must call the write_page method to do that. Doing it this way, after creation you can call a method to add random text, for example, before committing the page to disk. """
slug = util.make_slug(rawtitle) if self.site.page_exists_on_disk(slug): raise ValueError #print "Attempted to create a page which already exists." #return False self._title = unicode(rawtitle,"UTF-8") self._slug = slug self._dirs['source_dir'] = os.path.join(self.site.dirs['source'], slug) self._dirs['source_filename'] = os.path.join(self._dirs['source_dir'], slug + '.md') self._dirs['www_dir'] = os.path.join(self.site.dirs['www'], slug) self._dirs['www_filename'] = os.path.join(self._dirs['www_dir'], \ 'index.html') self._config = self._create_config() 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 write(self): """Write the s2 page to the corresponding source file. It always writes the (serialized) config first, and then the content (normally markdown). The destination file is in the source_dir of the site. """
if not os.path.isdir(self._dirs['source_dir']): os.mkdir(self._dirs['source_dir']) fout = codecs.open(self._dirs['source_filename'], 'w', encoding="utf-8", errors="xmlcharrefreplace") fout.write(self._config_to_text()) if self._content: fout.write('\n') fout.write(self._content) fout.write('\n') fout.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(self, new_title): """Rename an existing s2 page. For an existing s2 page, updates the directory and file name, as well as the internal configuration information (since it contains the title and the slug) """
if not isinstance(new_title, str) and \ not isinstance(new_title, unicode): raise TypeError # print "Cannot rename page. New title must be string or unicode." new_slug = util.make_slug(new_title) if self.site.page_exists_on_disk(new_slug): raise ValueError # print "Cannot rename page. A page with the same \ # title/slug already exists." #wipe the source directory for this page shutil.rmtree(self._dirs['source_dir']) #just change dirinfo, config, and write self._title = new_title self._slug = new_slug self._config['title'] = [self._title] self._config['slug'] = [self._slug] self._dirs['source_dir'] = os.path.join(self.site.dirs['source'], new_slug) self._dirs['source_filename'] = os.path.join(self._dirs['source_dir'], new_slug + '.md') self._dirs['www_dir'] = os.path.join(self.site.dirs['www'], new_slug) #self._dirs['www_filename'] = os.path.join(self._dirs['www_dir'], \ # new_slug + '.html') self.write()
<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): """Render this page and return the rendition. Converts the markdown content to html, and then renders the (mako) template specified in the config, using that html. The task of writing of the rendition to a real file is responsibility of the generate method. """
(pthemedir, ptemplatefname) = self._theme_and_template_fp() mylookup = TemplateLookup(directories=[self.site.dirs['s2'], pthemedir], input_encoding='utf-8', output_encoding='utf-8') makotemplate = Template(filename=ptemplatefname, lookup=mylookup, module_directory=self.site._makodir) # I don't really need to use the meta extension here, because I render self._content (has no metadata) #page_html = markdown.markdown(self._content) md = markdown.Markdown(extensions=['meta','fenced_code', 'codehilite'],output_format="html5") page_html = md.convert(self._content) # need to trigger the conversion to obtain md.Meta # We assume that the page is always in a dir one level below www themepath = "../themes/" + os.path.split(pthemedir)[1] + '/' commonpath = "../common/" # HERE I'll pass the config variable to the mako template, so I can use the title etc. #buf = StringIO() #ctx = Context(buf, dict(pageContent=page_html, isFrontPage=False, themePath=themepath, pageTitle='pedo', # commonPath=commonpath)) #makotemplate.render_context(ctx) #rendition = buf.getvalue() # IS THERE `PIWIK CODE? # IS THERE DISQUS CODE? # READ from s2 if there's disqus_code.html.tpl and piwik_code.html.tpl # if there's piwik, just define the variable piwik_code with its contents # if there's disqus... nested render? # HERE I NEED TO DIRECTLY INCLUDE A TEMPLATE IN ANOTHER TEMPLATE!!! MAKO! #d_sn = self.site.site_config['disqus_shortname'] #if d_sn: # the site uses disqus piwik_code = None disqus_code, disqus_shortname, disqus_identifier, disqus_title, disqus_url= None, None, None, None, None piwik_code_tpl = os.path.join(self.site.dirs['s2'],'piwik_code.html.tpl') if os.path.isfile(piwik_code_tpl): piwik_code = '/piwik_code.html.tpl' disqus_code_tpl = os.path.join(self.site.dirs['s2'],'disqus_code.html.tpl') if os.path.isfile(disqus_code_tpl): disqus_code = '/disqus_code.html.tpl' disqus_shortname = self.site.site_config['disqus_shortname'] disqus_identifier = self._config['page_id'][0] disqus_title = self.title disqus_url = os.path.join(self.site.site_config['site_url'],self._slug) rendition = makotemplate.render(pageContent=page_html,isFrontPage=False, themePath=themepath, commonPath=commonpath, pageTitle=self.title, piwik_code=piwik_code, disqus_code=disqus_code, disqus_shortname = disqus_shortname, disqus_identifier = disqus_identifier, disqus_url = disqus_url, disqus_title= disqus_title) return rendition
<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(self): """Generate the page html file. Just open the destination file for writing and write the result of rendering this page. """
generated_content = '' if 'published' in (self._config['status'][0]).lower(): if os.path.isdir(self.dirs['www_dir']): shutil.rmtree(self.dirs['www_dir']) os.mkdir(self.dirs['www_dir']) # copy the whole source directory of the page, # excluding 'nowww' and *s2md sfl = glob.glob(os.path.join(self.dirs['source_dir'], "*")) dirlist = [f for f in sfl if os.path.isdir(f)] filelist = [f for f in sfl if os.path.isfile(f)] for f in filelist: if not '.md' in os.path.split(f)[1]: shutil.copy(f, self.dirs['www_dir']) for d in dirlist: rfn = os.path.split(d)[1] if rfn != 'nowww': shutil.copytree(d, os.path.join(self.dirs['www_dir'], rfn)) #write the rendered "page" to file #fout = open(self.dirs['www_filename'], 'w') #fout.write(self.render()) #fout.close() generated_content = self.render() fout = codecs.open(self.dirs['www_filename'], "w", encoding="utf-8", errors="xmlcharrefreplace") fout.write(generated_content) fout.close() return generated_content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_config(self): """Create the default configuration dictionary for this page."""
configinfo = {'creation_date': [ datetime.datetime.now().date().isoformat()], 'author': [self.site.site_config['default_author']], 'status': [u'draft'], 'lang': [u''], 'tags': [u''], 'title': [self._title], 'slug': [self._slug], 'theme': [u''], 'template': [u''], 'page_id': [uuid.uuid4().hex] } # when theme and template are empty, the generator uses the defaults. Thus, initially # they should be empty, to allow for global changes just by changing the site config files. return configinfo
<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, slug): """Load the page. The _file_name param is known, because this method is only called after having checked that the page exists. """
#here we know that the slug exists self._slug = slug page_dir = os.path.join(self.site.dirs['source'], self._slug) page_file_name = os.path.join(page_dir, self._slug + '.md') self._dirs['source_dir'] = page_dir self._dirs['source_filename'] = page_file_name self._dirs['www_dir'] = os.path.join(self.site.dirs['www'], slug) self._dirs['www_filename'] = os.path.join(self._dirs['www_dir'], 'index.html') #pf = open(self._dirs['source_filename'], 'r') #page_text = pf.read() #pf.close() # need to decode! pf = codecs.open(self._dirs['source_filename'], mode="r", encoding="utf-8") page_text = pf.read() pf.close() self._parse_text(page_text) if not self._check_config(): raise ValueError #sys.exit() self._title = self._config['title'][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 _check_config(self): """Verify that the configuration is correct."""
required_data = ['creation_date', 'author', 'status', 'lang', 'tags', 'title', 'slug', 'theme', 'template', 'page_id'] isok = True # exclude some statements from coverage analysis. I would need to # refactor how the config is loaded/handled etc. It's not worth # to do that now. Maybe when I change yaml for the markdwn extension. for e in self._config.keys(): if not e in required_data: # pragma: no cover print "The configuration in page '" + \ self._slug + "' is corrupt." isok = False # check that the theme and template exist, even if they're default. (pthemedir, ptemplatefname) = self._theme_and_template_fp() if not os.path.isdir(pthemedir): # pragma: no cover print "Theme " + self._config['theme'][0] + \ " specified in page '" + \ self._slug + "' does not exist." isok = False if not os.path.isfile(ptemplatefname): # pragma: no cover print "Template " + self._config['template'][0] + \ " specified in page '" + self._slug + \ "' does not exist." isok = False return isok
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _theme_and_template_fp(self): """Return the full paths for theme and template in this page"""
ptheme = self._config['theme'][0] if ptheme == "": ptheme = self.site.site_config['default_theme'] pthemedir = os.path.join(self.site.dirs['themes'], ptheme) ptemplate = self._config['template'][0] if ptemplate == "": ptemplate = self.site.site_config['default_template'] ptemplatefname = os.path.join(pthemedir, ptemplate) return (pthemedir, ptemplatefname)
<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_text(self, page_text): """Extract the s2config and the content from the raw page text."""
# 1 sanitize: remove leading blank lines # 2 separate "config text" from content, store content # 3 convert config text + \n to obtain Meta, this is the config. lines = page_text.split('\n') i = 0 while lines[i].strip() == '': i += 1 if i > 0: # i points to the first non-blank line. Else, i is 0, there are no leading blank lines lines = lines[i:] #remove leading blank lines i = 0 while lines[i].strip() != '': i += 1 # i points to the first blank line cfg_lines = '\n'.join(lines[0:i + 1]) #config lines, plus the empty line md = markdown.Markdown(extensions=['meta','fenced_code', 'codehilite'],output_format="html5") md.convert(cfg_lines) # need to trigger the conversion to obtain md.Meta self._config = md.Meta self._content = '\n'.join(lines[i+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 _config_to_text(self): """Render the configuration as text."""
r = u'' # unicode('',"UTF-8") for k in self._config: # if k == 'creation_date': # r += k + ": " + self._config[k][0] + '\n' # else: #uk = unicode(k,"UTF-8") cosa = '\n '.join(self._config[k]) + '\n' r += k + ": " + cosa #r += k + ": " + '\n '.join(self._config[k]) + '\n' r += '\n' return 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 author(self): """Return the full path of the theme used by this page."""
r = self.site.site_config['default_author'] if 'author' in self._config: r = self._config['author'] return 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 memoize(method): """A new method which acts like the given method but memoizes arguments See https://en.wikipedia.org/wiki/Memoization for the general idea called 2 called 3 2 The returned method also has an attached method "invalidate" which removes given values from the cache Or empties the cache if no values are given 2 called 3 """
method.cache = {} def invalidate(*arguments, **keyword_arguments): key = _represent_arguments(*arguments, **keyword_arguments) if not key: method.cache = {} elif key in method.cache: del method.cache[key] else: raise KeyError( 'Not prevously cached: %s(%s)' % (method.__name__, key)) def new_method(*arguments, **keyword_arguments): """Cache the arguments and return values of the call The key cached is the repr() of arguments This allows more types of values to be used as keys to the cache Such as lists and tuples """ key = _represent_arguments(*arguments, **keyword_arguments) if key not in method.cache: method.cache[key] = method(*arguments, **keyword_arguments) return method.cache[key] new_method.invalidate = invalidate new_method.__doc__ = method.__doc__ new_method.__name__ = 'memoize(%s)' % method.__name__ return new_method
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug(method): """Decorator to debug the given method"""
def new_method(*args, **kwargs): import pdb try: import pudb except ImportError: pudb = pdb try: pudb.runcall(method, *args, **kwargs) except pdb.bdb.BdbQuit: sys.exit('Normal quit from debugger') new_method.__doc__ = method.__doc__ new_method.__name__ = 'debug(%s)' % method.__name__ return new_method
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def globber(main_method, globs): """Recognise globs in args"""
import os from glob import glob def main(arguments): lists_of_paths = [_ for _ in arguments if glob(pathname, recursive=True)] return main_method(arguments, lists_of_paths) return main
<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_trigger(self, msg): """ Dispatches the message to the corresponding method. """
if not msg.args[0].startswith(self.trigger_char): return split_args = msg.args[0].split() trigger = split_args[0].lstrip(self.trigger_char) if trigger in self.triggers: method = getattr(self, trigger) if msg.command == PRIVMSG: if msg.dst == self.irc.nick: if EVT_PRIVATE in self.triggers[trigger]: msg.event = EVT_PRIVATE method(msg) else: if EVT_PUBLIC in self.triggers[trigger]: msg.event = EVT_PUBLIC method(msg) elif (msg.command == NOTICE) and (EVT_NOTICE in self.triggers[trigger]): msg.event = EVT_NOTICE method(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_restriction(self, command, user, event_types): """ Adds restriction for given `command`. :param command: command on which the restriction should be set. :type command: str :param user: username for which the restriction applies. :type user: str :param event_types: types of events for which the command is allowed. :type event_types: list """
self.commands_rights[command][user.lower()] = event_types if command not in self.triggers: self.triggers[command] = [EVT_PUBLIC, EVT_PRIVATE, EVT_NOTICE] if not hasattr(self, command): setattr(self, command, lambda msg: self.handle_rights(msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_restriction(self, command, user, event_types): """ Removes restriction for given `command`. :param command: command on which the restriction should be removed. :type command: str :param user: username for which restriction should be removed. :type user: str :param event_types: types of events that should be removed from restriction. :type event_types: list """
if user.lower() in self.commands_rights[command]: for event_type in event_types: try: self.commands_rights[command][user.lower()].remove(event_type) except ValueError: pass if not self.commands_rights[command][user.lower()]: self.commands_rights[command].pop(user.lower())
<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_rights(self, msg): """ Catch-all command that is called whenever a restricted command is triggered. :param msg: message that triggered the command. :type msg: :class:`fatbotslim.irc.Message` """
command = msg.args[0][1:] if command in self.commands_rights: if msg.src.name.lower() in self.commands_rights[command]: if msg.event not in self.commands_rights[command][msg.src.name.lower()]: msg.propagate = False elif '*' in self.commands_rights[command]: if msg.event not in self.commands_rights[command]['*']: msg.propagate = False if (not msg.propagate) and self.notify: message = "You're not allowed to use the '%s' command" % command if msg.event == EVT_PUBLIC: self.irc.msg(msg.dst, message) elif msg.event == EVT_PRIVATE: self.irc.msg(msg.src.name, message) elif msg.event == EVT_NOTICE: self.irc.notice(msg.src.name, message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_inclusions(item, included=[], excluded=[]): """Everything passes if both are empty, otherwise, we have to check if \ empty or is present."""
if (len(included) == 0): if len(excluded) == 0 or item not in excluded: return True else: return False else: if item in included: 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 toto(arch_name, comment='', clear=False, read_comment=False, list_members=False, time_show=False): """ Small utility for changing comment in a zip file without changing the file modification datetime. """
if comment and clear: clingon.RunnerError("You cannot specify --comment and --clear together") z = None # if archive does not exist, create it with up to 3 files from current directory if not os.path.isfile(arch_name): print "Creating archive", arch_name z = zipfile.ZipFile(arch_name, 'w') for f in [x for x in glob.iglob('*.*') if not x.endswith('.zip')][:3]: print " Add file %s to %s" % (f, arch_name) z.write(f) if comment: mtime = os.path.getmtime(arch_name) if not z: z = zipfile.ZipFile(arch_name, 'a') z.comment = comment if z: z.close() if comment: os.utime(arch_name, (time.time(), mtime)) if read_comment: z = zipfile.ZipFile(arch_name, 'r') print "Comment:", z.comment, len(z.comment) if list_members: z = zipfile.ZipFile(arch_name, 'r') print "Members:", z.namelist() if time_show: print "Access time:", time.ctime(os.path.getatime(arch_name)) print "Modif time:", time.ctime(os.path.getmtime(arch_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 cli(ctx, data, verbose, color, format, editor): """Query a meetup database. """
ctx.obj['verbose'] = verbose if verbose: logging.basicConfig(level=logging.INFO) logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) ctx.obj['datadir'] = os.path.abspath(data) if 'db' not in ctx.obj: ctx.obj['db'] = get_db(data) if color is None: ctx.obj['term'] = blessings.Terminal() elif color is True: ctx.obj['term'] = blessings.Terminal(force_styling=True) elif color is False: ctx.obj['term'] = blessings.Terminal(force_styling=None) if 'PYVO_TEST_NOW' in os.environ: # Fake the current date for testing ctx.obj['now'] = datetime.datetime.strptime( os.environ['PYVO_TEST_NOW'], '%Y-%m-%d %H:%M:%S') else: ctx.obj['now'] = datetime.datetime.now() ctx.obj['format'] = format ctx.obj['editor'] = shlex.split(editor)
<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_iterator(self, file_obj): """ For given `file_obj` return iterator, which will read the file in `self.read_bs` chunks. Args: file_obj (file): File-like object. Return: iterator: Iterator reading the file-like object in chunks. """
file_obj.seek(0) return iter(lambda: file_obj.read(self.read_bs), '')
<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_hash(self, file_obj): """ Compute hash for the `file_obj`. Attr: file_obj (obj): File-like object with ``.write()`` and ``.seek()``. Returns: str: Hexdigest of the hash. """
size = 0 hash_buider = self.hash_builder() for piece in self._get_file_iterator(file_obj): hash_buider.update(piece) size += len(piece) file_obj.seek(0) return "%s_%x" % (hash_buider.hexdigest(), 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 _create_dir_path(self, file_hash, path=None, hash_list=None): """ Create proper filesystem paths for given `file_hash`. Args: file_hash (str): Hash of the file for which the path should be created. path (str, default None): Recursion argument, don't set this. hash_list (list, default None): Recursion argument, don't set this. Returns: str: Created path. """
# first, non-recursive call - parse `file_hash` if hash_list is None: hash_list = list(file_hash) if not hash_list: raise IOError("Directory structure is too full!") # first, non-recursive call - look for subpath of `self.path` if not path: path = os.path.join( self.path, hash_list.pop(0) ) # if the path not yet exists, create it and work on it if not os.path.exists(path): os.mkdir(path) return self._create_dir_path( file_hash=file_hash, path=path, hash_list=hash_list ) files = os.listdir(path) # file is already in storage if file_hash in files: return path # if the directory is not yet full, use it if len(files) < self.dir_limit: return path # in full directories create new sub-directories return self._create_dir_path( file_hash=file_hash, path=os.path.join(path, hash_list.pop(0)), hash_list=hash_list )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_path_from_hash(self, file_hash, path=None, hash_list=None): """ For given `file_hash`, return path on filesystem. Args: file_hash (str): Hash of the file, for which you wish to know the path. path (str, default None): Recursion argument, don't set this. hash_list (list, default None): Recursion argument, don't set this. Returns: str: Path for given `file_hash` contained in :class:`.PathAndHash`\ object. Raises: IOError: If the file with corresponding `file_hash` is not in \ storage. """
# first, non-recursive call - parse `file_hash` if hash_list is None: hash_list = list(file_hash) if not hash_list: raise IOError("Directory structure is too full!") # first, non-recursive call - look for subpath of `self.path` if not path: path = os.path.join( self.path, hash_list.pop(0) ) files = os.listdir(path) # is the file/unpacked archive in this `path`? if file_hash in files: full_path = os.path.join(path, file_hash) if os.path.isfile(full_path): return PathAndHash(path=full_path, hash=file_hash) return PathAndHash(path=full_path + "/", hash=file_hash) # end of recursion, if there are no more directories to look into next_path = os.path.join(path, hash_list.pop(0)) if not os.path.exists(next_path): raise IOError("File not found in the structure.") # look into subdirectory return self.file_path_from_hash( file_hash=file_hash, path=next_path, hash_list=hash_list )
<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_file(self, file_obj): """ Add new file into the storage. Args: file_obj (file): Opened file-like object. Returns: obj: Path where the file-like object is stored contained with hash\ in :class:`.PathAndHash` object. Raises: AssertionError: If the `file_obj` is not file-like object. IOError: If the file couldn't be added to storage. """
BalancedDiscStorage._check_interface(file_obj) file_hash = self._get_hash(file_obj) dir_path = self._create_dir_path(file_hash) final_path = os.path.join(dir_path, file_hash) def copy_to_file(from_file, to_path): with open(to_path, "wb") as out_file: for part in self._get_file_iterator(from_file): out_file.write(part) try: copy_to_file(from_file=file_obj, to_path=final_path) except Exception: os.unlink(final_path) raise return PathAndHash(path=final_path, hash=file_hash)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recursive_remove_blank_dirs(self, path): """ Make sure, that blank directories are removed from the storage. Args: path (str): Path which you suspect that is blank. """
path = os.path.abspath(path) # never delete root of the storage or smaller paths if path == self.path or len(path) <= len(self.path): return # if the path doesn't exists, go one level upper if not os.path.exists(path): return self._recursive_remove_blank_dirs( os.path.dirname(path) ) # if the directory contains files, end yourself if os.listdir(path): return # blank directories can be removed shutil.rmtree(path) # go one level up, check whether the directory is blank too return self._recursive_remove_blank_dirs( os.path.dirname(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 pseudolocalize(self, s): """ Performs pseudo-localization on a string. The specific transforms to be applied to the string is defined in the transforms field of the object. :param s: String to pseudo-localize. :returns: Copy of the string s with the transforms applied. If the input string is an empty string or None, an empty string is returned. """
if not s: # If the string is empty or None return u"" if not isinstance(s, six.text_type): raise TypeError("String to pseudo-localize must be of type '{0}'.".format(six.text_type.__name__)) # If no transforms are defined, return the string as-is. if not self.transforms: return s fmt_spec = re.compile( r"""( {.*?} # https://docs.python.org/3/library/string.html#formatstrings | %(?:\(\w+?\))?.*?[acdeEfFgGiorsuxX%] # https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting )""", re.VERBOSE) # If we don't find any format specifiers in the input string, just munge the entire string at once. if not fmt_spec.search(s): result = s for munge in self.transforms: result = munge(result) # If there are format specifiers, we do transliterations on the sections of the string that are not format # specifiers, then do any other munging (padding the length, adding brackets) on the entire string. else: substrings = fmt_spec.split(s) for munge in self.transforms: if munge in transforms._transliterations: for idx in range(len(substrings)): if not fmt_spec.match(substrings[idx]): substrings[idx] = munge(substrings[idx]) else: continue else: continue result = u"".join(substrings) for munge in self.transforms: if munge not in transforms._transliterations: result = munge(result) 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 pseudolocalizefile(self, input_filename, output_filename, input_encoding='UTF-8', output_encoding='UTF-8', overwrite_existing=True): """ Method for pseudo-localizing the message catalog file. :param input_filename: Filename of the source (input) message catalog file. :param output_filename: Filename of the target (output) message catalog file. :param input_encoding: String indicating the encoding of the input file. Optional, defaults to 'UTF-8'. :param output_encoding: String indicating the encoding of the output file. Optional, defaults to 'UTF-8'. :param overwrite_existing: Boolean indicating if an existing output message catalog file should be overwritten. True by default. If False, an IOError will be raised. """
leading_trailing_double_quotes = re.compile(r'^"|"$') if not os.path.isfile(input_filename): raise IOError("Input message catalog not found: {0}".format(os.path.abspath(input_filename))) if os.path.isfile(output_filename) and not overwrite_existing: raise IOError("Error, output message catalog already exists: {0}".format(os.path.abspath(output_filename))) with codecs.open(input_filename, mode="r", encoding=input_encoding) as in_fileobj: with codecs.open(output_filename, mode="w", encoding=output_encoding) as out_fileobj: for current_line in in_fileobj: out_fileobj.write(current_line) if current_line.startswith("msgid"): msgid = current_line.split(None, 1)[1].strip() msgid = leading_trailing_double_quotes.sub('', msgid) msgstr = self.l10nutil.pseudolocalize(msgid) out_fileobj.write(u"msgstr \"{0}\"\n".format(msgstr)) next(in_fileobj)
<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_quantities(d, coords=None, massE=0.511e6): ''' Add physically interesting quantities to pext data. Parameters: ----------- d : pext array Keywords: --------- coords : sequence of positions for angle calculation. None or by default, calculate no angles. For 2D, takes the angle depending on the order passed, so this can be used for left-handed coordinate systems like LSP's xz. massE : rest mass energy of particles. Returns a copy with the quantities appended. ''' keys,items = zip(*calc_quantities(d,coords=coords,massE=massE).items()); return rfn.rec_append_fields( d, keys, 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 calc_quantities(d, coords=None, massE=0.511e6): ''' Calculate physically interesting quantities from pext Parameters: ----------- d : pext array Keywords: --------- coords : sequence of positions for angle calculation. None or by default, calculate no angles. For 2D, takes the angle depending on the order passed, so this can be used for left-handed coordinate systems like LSP's xz. massE : rest mass energy of particles. Returns a dictionary of physical quantities. ''' quants = dict(); quants['u_norm'] = np.sqrt(d['ux']**2+d['uy']**2+d['uz']**2) quants['KE'] =(np.sqrt(quants['u_norm']**2+1)-1)*massE; coords[:] = ['u'+coord for coord in coords]; if not coords: pass; elif len(coords) == 3: quants['theta'] = np.arccos(d[coords[2]]/quants['u_norm']); quants['phi'] = np.arctan2(d[coords[1]],d[coords[0]]); quants['phi_n'] = np.arctan2(d[coords[2]],d[coords[0]]); elif len(coords) == 2: quants['phi'] = np.arctan2(d[coords[1]],d[coords[0]]); return quants;
<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_server(initialize=True): """Create a server"""
with provider() as p: host_string = p.create_server() if initialize: env.host_string = host_string initialize_server()
<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(self, list_id): """ Retrieve the list given for the user. """
r = requests.get( "https://kippt.com/api/users/%s/lists/%s" % (self.id, list_id), headers=self.kippt.header ) return (r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relationship(self): """ Retrieve what the relationship between the user and then authenticated user is. """
r = requests.get( "https://kippt.com/api/users/%s/relationship" % (self.id), headers=self.kippt.header ) return (r.json())
<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_titles(self, row_index, column_index): ''' Helper method to find all titles for a particular cell. ''' titles = [] for column_search in range(self.start[1], column_index): cell = self.table[row_index][column_search] if cell == None or (isinstance(cell, basestring) and not cell): continue elif isinstance(cell, basestring): titles.append(cell) else: break for row_search in range(self.start[0], row_index): cell = self.table[row_search][column_index] if cell == None or (isinstance(cell, basestring) and not cell): continue elif isinstance(cell, basestring): titles.append(cell) else: break return titles
<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_raw_block(self): ''' Copies the block as it was originally specified by start and end into a new table. Returns: A copy of the block with no block transformations. ''' ctable = [] r, c = 0, 0 try: for row_index in range(self.start[0], self.end[0]): r = row_index row = [] ctable.append(row) for column_index in range(self.start[1], self.end[1]): c = column_index row.append(self.table[row_index][column_index]) except IndexError: raise InvalidBlockError('Missing table element at [%d, %d]' % (r, c)) return ctable
<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_numbered_block(self): ''' Copies the block as it was originally specified by start and end into a new table. Additionally inserts the original table indices in the first row of the block. Returns: A copy of the block with no block transformations. ''' raw_block = self.copy_raw_block() # Inserts the column number in row 0 raw_block.insert(0, range(self.start[1], self.end[1])) return raw_block
<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_to_row_table(self, add_units=True): ''' Converts the block into row titled elements. These elements are copied into the return table, which can be much longer than the original block. Args: add_units: Indicates if units should be appened to each row item. Returns: A row-titled table representing the data in the block. ''' rtable = [] if add_units: relavent_units = self.get_relavent_units() # Create a row for each data element for row_index in range(self.start[0], self.end[0]): for column_index in range(self.start[1], self.end[1]): cell = self.table[row_index][column_index] if cell != None and isinstance(cell, (int, float, long)): titles = self._find_titles(row_index, column_index) titles.append(cell) if add_units: titles.append(relavent_units.get((row_index, column_index))) rtable.append(titles) # If we had all 'titles', just return the original block if not rtable: for row_index in range(self.start[0], self.end[0]): row = [] rtable.append(row) for column_index in range(self.start[1], self.end[1]): row.append(self.table[row_index][column_index]) if add_units: row.append(relavent_units.get((row_index, column_index))) return rtable
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def flag_is_related(self, flag): ''' Checks for relationship between a flag and this block. Returns: True if the flag is related to this block. ''' same_worksheet = flag.worksheet == self.worksheet if isinstance(flag.location, (tuple, list)): return (flag.location[0] >= self.start[0] and flag.location[0] < self.end[0] and flag.location[1] >= self.start[1] and flag.location[1] < self.end[1] and same_worksheet) else: return same_worksheet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unit_is_related(self, location, worksheet): ''' Checks for relationship between a unit location and this block. Returns: True if the location is related to this block. ''' same_worksheet = worksheet == self.worksheet if isinstance(location, (tuple, list)): return (location[0] >= self.start[0] and location[0] < self.end[0] and location[1] >= self.start[1] and location[1] < self.end[1] and same_worksheet) else: return same_worksheet
<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_relavent_flags(self): ''' Retrieves the relevant flags for this data block. Returns: All flags related to this block. ''' relavent_flags = {} for code, flags_list in self.flags.items(): relavent_flags[code] = [] for flag in flags_list: if self.flag_is_related(flag): relavent_flags[code].append(flag) # Remove that flag level if no error exists if not relavent_flags[code]: del relavent_flags[code] return relavent_flags
<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_relavent_units(self): ''' Retrieves the relevant units for this data block. Returns: All flags related to this block. ''' relavent_units = {} for location,unit in self.units.items(): if self.unit_is_related(location, self.worksheet): relavent_units[location] = unit return relavent_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 validate_block(self): ''' This method is a multi-stage process which repairs row titles, then repairs column titles, then checks for invalid rows, and finally for invalid columns. This maybe should have been written via state machines... Also suggested as being possibly written with code-injection. ''' # Don't allow for 0 width or 0 height blocks if self._check_zero_size(): return False # Single width or height blocks should be considered self._check_one_size() # Repair any obvious block structure issues self._repair_row() self._repair_column() # Fill any remaining empty titles if we're not a complete block if not self.complete_block: self._fill_row_holes() self._fill_column_holes() # Check for invalid data after repairs self._validate_rows() self._validate_columns() # We're valid enough to be used -- though error flags may have # been thrown into flags. 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 _check_zero_size(self): ''' Checks for zero height or zero width blocks and flags the occurrence. Returns: True if the block is size 0. ''' block_zero = self.end[0] <= self.start[0] or self.end[1] <= self.start[1] if block_zero: self.flag_change(self.flags, 'fatal', worksheet=self.worksheet, message=self.FLAGS['0-size']) return block_zero
<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_one_size(self): ''' Checks for single height or single width blocks and flags the occurrence. Returns: True if the block is size 1. ''' block_one = self.end[0] == self.start[0]+1 or self.end[1] == self.start[1]+1 if block_one: self.flag_change(self.flags, 'error', self.start, self.worksheet, message=self.FLAGS['1-size']) return block_one
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _repair_row(self): ''' Searches for missing titles that can be inferred from the surrounding data and automatically repairs those titles. ''' # Repair any title rows check_for_title = True for row_index in range(self.start[0], self.end[0]): table_row = self.table[row_index] row_start = table_row[self.start[1]] # Look for empty cells leading titles if check_for_title and is_empty_cell(row_start): self._stringify_row(row_index) # Check for year titles in column or row elif (isinstance(row_start, basestring) and re.search(allregex.year_regex, row_start)): self._check_stringify_year_row(row_index) else: check_for_title = 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 _repair_column(self): ''' Same as _repair_row but for columns. ''' # Repair any title columns check_for_title = True for column_index in range(self.start[1], self.end[1]): table_column = TableTranspose(self.table)[column_index] column_start = table_column[self.start[0]] # Only iterate through columns starting with a blank cell if check_for_title and is_empty_cell(column_start): self._stringify_column(column_index) # Check for year titles in column or row elif (isinstance(column_start, basestring) and re.search(allregex.year_regex, column_start)): self._check_stringify_year_column(column_index) else: check_for_title = 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 _fill_row_holes(self): ''' Fill any remaining row title cells that are empty. This must be done after the other passes to avoid preemptively filling in empty cells reserved for other operations. ''' for row_index in range(self.start[0], self.max_title_row): table_row = self.table[row_index] row_start = table_row[self.start[1]] if is_text_cell(row_start): self._check_fill_title_row(row_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _fill_column_holes(self): ''' Same as _fill_row_holes but for columns. ''' for column_index in range(self.start[1], self.end[1]): table_column = TableTranspose(self.table)[column_index] column_start = table_column[self.start[0]] if is_text_cell(column_start): self._check_fill_title_column(column_index)
<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_rows(self): ''' Checks for any missing data row by row. It also checks for changes in cell type and flags multiple switches as an error. ''' for row_index in range(self.start[0], self.end[0]): table_row = self.table[row_index] used_row = self.used_cells[row_index] row_type = None if self.end[1] > self.start[1]: row_type = get_cell_type(table_row[self.start[1]]) num_type_changes = 0 for column_index in range(self.start[1], self.end[1]): if used_row[column_index]: self.flag_change(self.flags, 'error', (row_index, column_index), self.worksheet, self.FLAGS['used']) if not check_cell_type(table_row[column_index], row_type): row_type = get_cell_type(table_row[column_index]) num_type_changes += 1 if num_type_changes > 1: self.flag_change(self.flags, 'warning', (row_index, column_index-1), self.worksheet, self.FLAGS['unexpected-change']) # Decrement this to catch other cells which change again num_type_changes -= 1 # Mark this cell as used used_row[column_index] = 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 _validate_columns(self): ''' Same as _validate_rows but for columns. Also ignore used_cells as _validate_rows should update used_cells. ''' for column_index in range(self.start[1], self.end[1]): table_column = TableTranspose(self.table)[column_index] column_type = None if self.end[0] > self.start[0]: column_type = get_cell_type(table_column[self.start[0]]) num_type_changes = 0 for row_index in range(self.start[0], self.end[0]): if not check_cell_type(table_column[row_index], column_type): column_type = get_cell_type(table_column[row_index]) num_type_changes += 1 if num_type_changes > 1: self.flag_change(self.flags, 'warning', (row_index-1, column_index), self.worksheet, self.FLAGS['unexpected-change']) # Decrement this to catch other cells which change again num_type_changes -= 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 _stringify_row(self, row_index): ''' Stringifies an entire row, filling in blanks with prior titles as they are found. ''' table_row = self.table[row_index] prior_cell = None for column_index in range(self.start[1], self.end[1]): cell, changed = self._check_interpret_cell(table_row[column_index], prior_cell, row_index, column_index) if changed: table_row[column_index] = cell prior_cell = cell
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _stringify_column(self, column_index): ''' Same as _stringify_row but for columns. ''' table_column = TableTranspose(self.table)[column_index] prior_cell = None for row_index in range(self.start[0], self.end[0]): cell, changed = self._check_interpret_cell(table_column[row_index], prior_cell, row_index, column_index) if changed: table_column[row_index] = cell prior_cell = cell
<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_interpret_cell(self, cell, prior_cell, row_index, column_index): ''' Helper function which checks cell type and performs cell translation to strings where necessary. Returns: A tuple of the form '(cell, changed)' where 'changed' indicates if 'cell' differs from input. ''' changed = False if (not is_empty_cell(cell) and not is_text_cell(cell)): self.flag_change(self.flags, 'interpreted', (row_index, column_index), self.worksheet, self.FLAGS['converted-to-string']) cell = str(cell) changed = True # If we find a blank cell, propagate the prior title elif is_empty_cell(cell): self.flag_change(self.flags, 'interpreted', (row_index, column_index), self.worksheet, self.FLAGS['copied-title']) cell = prior_cell changed = True return cell, changed
<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_fill_title_row(self, row_index): ''' Checks the given row to see if it is all titles and fills any blanks cells if that is the case. ''' table_row = self.table[row_index] # Determine if the whole row is titles prior_row = self.table[row_index-1] if row_index > 0 else table_row for column_index in range(self.start[1], self.end[1]): if is_num_cell(table_row[column_index]) or is_num_cell(prior_row[column_index]): return # Since we're a title row, stringify the row self._stringify_row(row_index)
<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_fill_title_column(self, column_index): ''' Same as _check_fill_title_row but for columns. ''' # Determine if the whole column is titles table_column = TableTranspose(self.table)[column_index] prior_column = TableTranspose(self.table)[column_index-1] if column_index > 0 else table_column for row_index in range(self.start[0], self.end[0]): if is_num_cell(table_column[row_index]) or is_num_cell(prior_column[row_index]): return # Since we're a title row, stringify the column self._stringify_column(column_index)