text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, other, copy=True, *args, **kwargs): """Update this composite model element with other element content. :param other: element to update with this. Must be the same type of this or this __contenttype__. :param bool copy: copy other before updating. :return: self"""
super(CompositeModelElement, self).update( other, copy=copy, *args, **kwargs ) if other: # dirty hack for python2.6 contents = [] if isinstance(other, self.__class__): contents = list(other.values()) elif isinstance(other, self.__contenttype__): contents = [other] else: raise TypeError( 'Wrong element to update with {0}: {1}'.format(self, other) ) for content in contents: selfcontent = self.get(content.name) if selfcontent is None: if copy: content = content.copy(local=False) self[content.name] = content else: selfcontent.update(content, copy=copy, *args, **kwargs) 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 params(self): """Get set of parameters by names. :rtype: dict"""
result = {} for content in list(self.values()): if isinstance(content, CompositeModelElement): cparams = content.params for cpname in cparams: cparam = cparams[cpname] if cpname in result: result[cpname].update(cparam) else: result[cpname] = cparam.copy() elif content.name in result: result[content.name].update(content) else: result[content.name] = content.copy() 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 cached_property(): """ Handy utility to build caching properties in your classes. Decorated code will be run only once and then result will be stored in private class property with the given name. When called for the second time, property will return cached value. :param storage_var_name: Name of the class property to store cached data. :type storage_var_name: str :return: Decorator for the class property """
def _stored_value(f): storage_var_name = "__{}".format(f.__name__) def _wrapper(self, *args, **kwargs): value_in_cache = getattr(self, storage_var_name, Sentinel) if value_in_cache is not Sentinel: return value_in_cache calculated_value = f(self, *args, **kwargs) setattr(self, storage_var_name, calculated_value) return calculated_value return _wrapper return _stored_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 deprecated(message=DEPRECATION_MESSAGE, logger=None): """ This decorator will simply print warning before running decoratee. So, presumably, you want to use it with console-based commands. :return: Decorator for the function. """
if logger is None: logger = default_logger def _deprecated(f): def _wrapper(*args, **kwargs): f_name = f.__name__ logger.warning(message.format(name=f_name)) result = f(*args, **kwargs) return result return _wrapper return _deprecated
<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_fixture_file(context, path): """Write fixture to disk."""
print('CWD:', os.getcwd()) print('FIXTURE:', path) with open(path, 'w') as stream: stream.write(context.text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_section(self, section): """Add a new Section object to the config. Should be a subclass of _AbstractSection."""
if not issubclass(section.__class__, _AbstractSection): raise TypeError("argument should be a subclass of Section") self.sections[section.get_key_name()] = section return section
<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_parser(self, **kwargs): """This method will create and return a new parser with prog_name, description, and a config file argument. """
self.parser = argparse.ArgumentParser(prog=self.prog_name, description=self._desc, add_help=False, **kwargs) # help is removed because parser.parse_known_args() show help, # often partial help. help action will be added during # reloading step for parser.parse_args() if self.use_config_file: self.parser.add_argument('--config-file', action="store", help="Other configuration file.") return self.parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload(self, hooks=None): """This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file name. """
#from argcomplete import debug # Parsing the command line looking for the previous options like # configuration file name or server section. Extra arguments # will be store into argv. args = None if os.environ.get('_ARGCOMPLETE'): # During argcomplete completion, parse_known_args will return an # empty Namespace. In this case, we feed the previous function with # data comming from the input completion data compline = os.environ.get('COMP_LINE') args = self.parser.parse_known_args(compline.split()[1:])[0] else: args = self.parser.parse_known_args()[0] if hooks is not None: if isinstance(hooks, list): for h in hooks: if isinstance(h, SectionHook): h(args) else: if isinstance(hooks, SectionHook): hooks(args) # After the first argument parsing, for configuration reloading, # we can add the help action. self.parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='show this help message and exit') # Reloading if self.use_config_file: # pylint: disable-msg=W0621 log = logging.getLogger('argtoolbox') log.debug("reloading configuration ...") if args.config_file: self.file_parser = ConfigParser.SafeConfigParser() discoveredFileList = self.file_parser.read(args.config_file) log.debug("discoveredFileList: " + str(discoveredFileList)) for s in self.sections.values(): log.debug("loading section : " + s.get_section_name()) s.reset() s.load(self.file_parser) log.debug("configuration reloaded.")
<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_representation(self, prefix="", suffix="\n"): """return the string representation of the current object."""
res = prefix + "Section " + self.get_section_name().upper() + suffix return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_element(self, elt): """Helper to add a element to the current section. The Element name will be used as an identifier."""
if not isinstance(elt, Element): raise TypeError("argument should be a subclass of Element") self.elements[elt.get_name()] = elt return elt
<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_element_list(self, elt_list, **kwargs): """Helper to add a list of similar elements to the current section. Element names will be used as an identifier."""
for e in elt_list: self.add_element(Element(e, **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 get_representation(self, prefix="", suffix="\n"): """This method build a array that will contain the string representation of the current object. Every lines could be prefixed and suffixed. """
res = [] if self.hidden: res.append(prefix + " - " + str(self._name) + " : xxxxxxxx" + suffix) else: default = self.default if default is None: default = " - " a = prefix + " - " a += str(self._name) + " : " if isinstance(default, types.UnicodeType): a += default else: a += str(default) a += suffix res.append(a) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, file_parser, section_name): """The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied. """
self._load(file_parser, section_name) self.post_load()
<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_arg_parse_arguments(self): """ During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You does not need to have multiple declarations. """
ret = dict() if self._required: if self.value is not None: ret["default"] = self.value else: ret["required"] = True ret["dest"] = self._name if not self.e_type_exclude: if self.e_type == int or self.e_type == float: # Just override argparse.add_argument 'type' parameter for int or float. ret["type"] = self.e_type if self.value is not None: ret["default"] = self.value if self._desc: ret["help"] = self._desc return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_section(self, section): """You can add section inside a Element, the section must be a subclass of SubSection. You can use this class to represent a tree. """
if not issubclass(section.__class__, SubSection): raise TypeError("Argument should be a subclass of SubSection, \ not :" + str(section.__class__)) self.sections[section.name] = section return section
<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_commands(self): """ You can override this method in order to add your command line arguments to the argparse parser. The configuration file was reloaded at this time."""
self.parser.add_argument( '-d', action="count", **self.config.default.debug.get_arg_parse_arguments())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_html(self, doc): """ This method removes all HTML from a docstring. Lighter than ``convert_docs``, this is intended for the documentation on **parameters**, not the overall docs themselves. :param doc: The initial docstring :type doc: string :returns: The stripped/cleaned docstring :rtype: string """
if not isinstance(doc, six.string_types): return '' doc = doc.strip() doc = self.tag_re.sub('', doc) return doc
<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_param(self, core_param): """ Returns data about a specific parameter. :param core_param: The ``Parameter`` to introspect :type core_param: A ``<botocore.parameters.Parameter>`` subclass :returns: A dict of the relevant information """
return { 'var_name': core_param.py_name, 'api_name': core_param.name, 'required': core_param.required, 'docs': self.strip_html(core_param.documentation), 'type': core_param.type, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_params(self, core_params): """ Goes through a set of parameters, extracting information about each. :param core_params: The collection of parameters :type core_params: A collection of ``<botocore.parameters.Parameter>`` subclasses :returns: A list of dictionaries """
params = [] for core_param in core_params: params.append(self.parse_param(core_param)) return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addFile(self,file): """ Permet d'ajouter un fichier Args: file (string): path d'un fichier json Returns: type: None Raises: FileFormatException: Erreur du format de fichier """
mylambda= lambda adict : { key.upper() : mylambda(adict[key]) if isinstance(adict[key],dict) else adict[key] for key in adict.keys() } if file.endswith('.json') : with open(file, 'r') as f: fileContent = mylambda(json.load(f)) elif file.endswith('.ini') : parser = configparser.ConfigParser() parser.read(file) fileContent = { section : { conflist[0].upper() : conflist[1] for conflist in parser.items(section) } for section in parser.sections() } else : raise FileFormatException() self._config = {**self._config, **mylambda(fileContent)}
<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_document(template_name, data_name, output_name): """ Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact name of the MarkDown template file from the aide_document/templates folder. Do not use the file path. data_name : String Relative file path from where this method is called to the location of the YAML data file to be used. output_name : String Relative file path from where this method is called to the location to which the output file is written. Examples ======== Suppose we have template.md in aide_document and a directory as follows: data/ params.yaml To render the document: This will then combine the data and template files and write to a new output file within data/. """
# Set up environment and load templates from pip package env = Environment(loader=PackageLoader('aide_document')) #TODO: add custom path to templates # Create output file, open template and data files, then combine with open(output_name, 'w') as output_file: output = env.get_template(template_name).render(yaml.load(open(data_name))) output_file.write(output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache(self, refreshing=None, next_action=None, data_blob=None, json_last_refresh=None, rollback_point=False): """ push this component into the cache :param refreshing: the new refreshing value :param next_action: the new next action value :param data_blob: the new data blob value :param json_last_refresh: the new json last refresh value - if None the date of this call :param rollback_point: define the rollback point with provided values (refreshing, next_action, data_blob and json_last_refresh) :return: """
LOGGER.debug("InjectorComponentSkeleton.cache") if json_last_refresh is None: json_last_refresh = datetime.datetime.now() if rollback_point: self.rollback_point_refreshing = refreshing self.rollback_point_next_action = next_action self.rollback_point_data_blob = data_blob self.rollback_point_refreshing = refreshing return self.component_cache_actor.save(refreshing=refreshing, next_action=next_action, json_last_refresh=json_last_refresh, data_blob=data_blob).get()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollback(self): """ push back last rollbackpoint into the cache :return: """
return self.component_cache_actor.save(refreshing=self.rollback_point_refreshing, next_action=self.rollback_point_next_action, json_last_refresh=self.rollback_point_last_refresh, data_blob=self.rollback_point_data_blob).get()
<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, section, name, has_default=False, value=None, allowEmpty=False): """ Check if a config value is set Returns True - config value is set and valid False - config value is not set or invalid """
cfg = self.config if not cfg.has_key(section) or not cfg.get(section).has_key(name): if not has_default: self.config_errors.append("%s: %s -> missing" % (section, name)) return False else: return True v = cfg.get(section).get(name) if v == "" and not allowEmpty: self.config_errors.append("%s: %s -> empty" % (section, name)) 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 transform(self, text): """Replaces characters in string ``text`` based in regex sub"""
return re.sub(self.regex, self.repl, text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(values): """ Dump a ValueTree instance, returning its dict representation. :param values: :type values: ValueTree :return: :rtype: dict """
root = {} def _dump(_values, container): for name,value in _values._values.items(): if isinstance(value, ValueTree): container[name] = _dump(value, {}) elif isinstance(value, list): items = [] for item in value: if not isinstance(item, str): raise ValueError() items.append(item) container[name] = items elif isinstance(value, str): container[name] = value else: raise ValueError() return container return _dump(values, root)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(obj): """ Load a ValueTree instance from its dict representation. :param obj: :type obj: dict :return: :rtype: ValueTree """
values = ValueTree() def _load(_obj, container): for name,value in _obj.items(): if isinstance(value, dict): path = make_path(name) container.put_container(path) _load(value, container.get_container(path)) elif isinstance(value, list): for item in value: container.append_field(ROOT_PATH, name, item) elif isinstance(value, str): container.put_field(ROOT_PATH, name, value) else: raise ValueError() _load(obj, values) return values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_container(self, path): """ Creates a container at the specified path, creating any necessary intermediate containers. :param path: str or Path instance :raises ValueError: A component of path is a field name. """
path = make_path(path) container = self for segment in path: try: container = container._values[segment] if not isinstance(container, ValueTree): raise ValueError() except KeyError: valuetree = ValueTree() container._values[segment] = valuetree container = valuetree
<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_container(self, path): """ Removes the container at the specified path. :param path: str or Path instance :raises ValueError: A component of path is a field name. :raises KeyError: A component of path doesn't exist. """
path = make_path(path) container = self parent = None for segment in path: parent = container try: container = container._values[segment] if not isinstance(container, ValueTree): raise ValueError() except KeyError: raise KeyError() del parent._values[path.segments[-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 get_container(self, path): """ Retrieves the container at the specified path. :param path: str or Path instance :return: :rtype: ValueTree :raises ValueError: A component of path is a field name. :raises KeyError: A component of path doesn't exist. """
path = make_path(path) container = self for segment in path: try: container = container._values[segment] if not isinstance(container, ValueTree): raise ValueError() except KeyError: raise KeyError() return container
<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_container(self, path): """ Returns True if a container exists at the specified path, otherwise False. :param path: str or Path instance :return: :rtype: bool :raises ValueError: A component of path is a field name. """
path = make_path(path) try: self.get_container(path) return True except KeyError: 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 put_field(self, path, name, value): """ Creates a field with the specified name an value at path. If the field already exists, it will be overwritten with the new value. :param path: str or Path instance :param name: :type name: str :param value: :type value: str """
if not isinstance(value, str): raise ValueError() path = make_path(path) container = self.get_container(path) current = self._values.get(name) if current is not None and isinstance(current, ValueTree): raise TypeError() container._values[name] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_field(self, path, name, value): """ Appends the field to the container at the specified path. :param path: str or Path instance :param name: :type name: str :param value: :type value: str """
path = make_path(path) container = self.get_container(path) current = container._values.get(name, None) if current is None: container._values[name] = value elif isinstance(current, ValueTree): raise TypeError() elif isinstance(current, list): container._values[name] = current + [value] else: container._values[name] = [current, value]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field(self, path, name): """ Retrieves the value of the field at the specified path. :param path: str or Path instance :param name: :type name: str :return: :raises ValueError: A component of path is a field name. :raises KeyError: A component of path doesn't exist. :raises TypeError: The field name is a component of a path. """
try: value = self.get(path, name) if not isinstance(value, str): raise TypeError() return value except KeyError: raise KeyError()
<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_field(self, path, name): """ Returns True if a field exists at the specified path, otherwise False. :param path: str or Path instance :param name: :type name: str :return: :raises ValueError: A component of path is a field name. :raises TypeError: The field name is a component of a path. """
try: self.get_field(path, name) return True except KeyError: 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 contains_field_list(self, path, name): """ Returns True if a multi-valued field exists at the specified path, otherwise False. :param path: str or Path instance :param name: :type name: str :return: :raises ValueError: A component of path is a field name. :raises TypeError: The field name is a component of a path. """
try: self.get_field_list(path, name) return True except KeyError: 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 get(): """ Get local facts about this machine. Returns: json-compatible dict with all facts of this host """
result = runCommand('facter --json', raise_error_on_fail=True) json_facts = result[1] facts = json.loads(json_facts) return facts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all(): """ Get all facts about all nodes """
result = {} for k,v in nago.extensions.info.node_data.items(): result[k] = v.get('facts', {}) 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 send(remote_host=None): """ Send my facts to a remote host if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master. """
my_facts = get() if not remote_host: remote_host = nago.extensions.settings.get('server') remote_node = nago.core.get_node(remote_host) if not remote_node: raise Exception("Remote host with token='%s' not found" % remote_host) response = remote_node.send_command('facts', 'post', host_token=remote_node.token, **my_facts) result = {} result['server_response'] = response result['message'] = "sent %s facts to remote node '%s'" % (len(my_facts), remote_node.get('host_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 extend_array(a, n): """Increase the resolution of an array by duplicating its values to fill a larger array. Parameters n: integer Factor by which to expand the array. Returns ------- """
a_new = a.copy() for d in range(a.ndim): a_new = np.repeat(a_new, n, axis=d) return a_new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field_subset(f, inds, rank=0): """Return the value of a field at a subset of points. Parameters Rank-r field in d dimensions inds: integer array, shape (n, d) Index vectors rank: integer The rank of the field (0: scalar field, 1: vector field and so on). Returns ------- f_sub: array, shape (n, rank) The subset of field values. """
f_dim_space = f.ndim - rank if inds.ndim > 2: raise Exception('Too many dimensions in indices array') if inds.ndim == 1: if f_dim_space == 1: return f[inds] else: raise Exception('Indices array is 1d but field is not') if inds.shape[1] != f_dim_space: raise Exception('Indices and field dimensions do not match') # It's magic, don't touch it! return f[tuple([inds[:, i] for i in range(inds.shape[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 pad_to_3d(a): """Return 1- or 2-dimensional cartesian vectors, converted into a 3-dimensional representation, with additional dimensional coordinates assumed to be zero. Parameters a: array, shape (n, d), d < 3 Returns ------- ap: array, shape (n, 3) """
a_pad = np.zeros([len(a), 3], dtype=a.dtype) a_pad[:, :a.shape[-1]] = a return a_pad
<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_parent(self, level=1): ''' get parent dir as a `DirectoryInfo`. return `None` if self is top. ''' try: parent_path = self.path.get_parent(level) except ValueError: # abspath cannot get parent return None assert parent_path return DirectoryInfo(parent_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 from_path(path): ''' create from path. return `None` if path is not exists. ''' if os.path.isdir(path): return DirectoryInfo(path) if os.path.isfile(path): return FileInfo(path) 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 open(self, mode='r', *, buffering=-1, encoding=None, newline=None, closefd=True): ''' open the file. ''' return open(self._path, mode=mode, buffering=buffering, encoding=encoding, newline=newline, closefd=closefd)
<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, data, *, mode=None, buffering=-1, encoding=None, newline=None): ''' write data into the file. ''' if mode is None: mode = 'w' if isinstance(data, str) else 'wb' with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp: return fp.write(data)
<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(self, mode='r', *, buffering=-1, encoding=None, newline=None): ''' read data from the file. ''' with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp: return fp.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_text(self, text: str, *, encoding='utf-8', append=True): ''' write text into the file. ''' mode = 'a' if append else 'w' return self.write(text, mode=mode, encoding=encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_bytes(self, data: bytes, *, append=True): ''' write bytes into the file. ''' mode = 'ab' if append else 'wb' return self.write(data, mode=mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy_to(self, dest, buffering: int = -1): ''' copy the file to dest path. `dest` canbe `str`, `FileInfo` or `DirectoryInfo`. if `dest` is `DirectoryInfo`, that mean copy into the dir with same name. ''' if isinstance(dest, str): dest_path = dest elif isinstance(dest, FileInfo): dest_path = dest.path elif isinstance(dest, DirectoryInfo): dest_path = dest.path / self.path.name else: raise TypeError('dest is not one of `str`, `FileInfo`, `DirectoryInfo`') with open(self._path, 'rb', buffering=buffering) as source: # use x mode to ensure dest does not exists. with open(dest_path, 'xb') as dest_file: for buffer in source: dest_file.write(buffer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read_text(self, encoding='utf-8') -> str: ''' read all text into memory. ''' with self.open('r', encoding=encoding) as fp: return fp.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load(self, format=None, *, kwargs={}): ''' deserialize object from the file. auto detect format by file extension name if `format` is None. for example, `.json` will detect as `json`. * raise `FormatNotFoundError` on unknown format. * raise `SerializeError` on any serialize exceptions. ''' return load(self, format=format, kwargs=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 dump(self, obj, format=None, *, kwargs={}): ''' serialize the `obj` into file. * raise `FormatNotFoundError` on unknown format. * raise `SerializeError` on any serialize exceptions. ''' return dump(self, obj, format=format, kwargs=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 get_file_hash(self, *algorithms: str): ''' get lower case hash of file. return value is a tuple, you may need to unpack it. for example: `get_file_hash('md5', 'sha1')` return `('XXXX1', 'XXXX2')` ''' from .hashs import hashfile_hexdigest return hashfile_hexdigest(self._path, algorithms)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iter_items(self, depth: int = 1): ''' get items from directory. ''' if depth is not None and not isinstance(depth, int): raise TypeError def itor(root, d): if d is not None: d -= 1 if d < 0: return for name in os.listdir(root): path = os.path.join(root, name) node = NodeInfo.from_path(path) yield node if isinstance(node, DirectoryInfo): yield from itor(path, d) yield from itor(self._path, depth)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def has_file(self, name: str): ''' check whether this directory contains the file. ''' return os.path.isfile(self._path / 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 has_directory(self, name: str): ''' check whether this directory contains the directory. ''' return os.path.isdir(self._path / 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 create_file(self, name: str, generate_unique_name: bool = False): ''' create a `FileInfo` for a new file. if the file was exists, and `generate_unique_name` if `False`, raise `FileExistsError`. the op does mean the file is created on disk. ''' def enumerate_name(): yield name index = 0 while True: index += 1 yield f'{name} ({index})' for n in enumerate_name(): path = os.path.join(self._path, n) if os.path.exists(path): if not generate_unique_name: raise FileExistsError return FileInfo(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 rand_bivar(X, rho): """Transform two unrelated random variables into correlated bivariate data X : ndarray two univariate random variables with N observations as <N x 2> matrix rho : float The Pearson correlations coefficient as number between [-1, +1] """
import numpy as np Y = np.empty(X.shape) Y[:, 0] = X[:, 0] Y[:, 1] = rho * X[:, 0] + np.sqrt(1.0 - rho**2) * X[:, 1] return Y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_to(self, source, transformation=None): """ Kervi values may be linked together. A KerviValue is configured to be either an input or output. When an output value is linked to an input value the input will become an observer of the output. Every time the output value change it will notify the input about the change. :param source: It is possible to make direct and indirect link. If the type of the source parameter is of type KerviValue a direct link is created. this is a fast link where the output can notify directly to input. This type of link is possible if both output and input resides in the same process. If the type of the source parameter is a string it is expected to hold the id of a another KerviValue. In this mode the input value will listen on the kervi spine for events from the output value. This mode is useful if the output and input does not exists in the same process. This type of link must be made by the input. :type source: ``str`` or ``KerviValue`` :param transformation: A function or lambda expression that transform the value before the output is update. This is usefull if the input expects other ranges that the output produce or need to change the sign of the value. """
if isinstance(source, KerviValue): if source.is_input and not self.is_input: self.add_observer(source, transformation) elif not source.is_input and self.is_input: source.add_observer(self, transformation) else: raise Exception("input/output mismatch in kervi value link:{0} - {1}".format(source.name, self.name)) elif isinstance(source, str): if len(self._spine_observers) == 0: self.spine.register_event_handler("valueChanged", self._link_changed_event) self._spine_observers[source] = transformation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs): r""" Links this value to a dashboard panel. :param dashboard_id: Id of the dashboard to link to. :type dashboard_id: str :param panel_id: Id of the panel on the dashboard to link to. :type panel_id: str :param \**kwargs: Use the kwargs below to override default values for ui parameters :Keyword Arguments: * *link_to_header* (``str``) -- Link this value to header of the panel. * *label_icon* (``str``) -- Icon that should be displayed together with label. * *label* (``str``) -- Label text, default value is the name of the value. * *flat* (``bool``) -- Flat look and feel. * *inline* (``bool``) -- Display value and label in its actual size If you set inline to true the size parameter is ignored. The value will only occupy as much space as the label and input takes. * *input_size* (``int``) -- width of the slider as a percentage of the total container it sits in. * *value_size* (``int``) -- width of the value area as a percentage of the total container it sits in. """
KerviComponent.link_to_dashboard( self, dashboard_id, panel_id, **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 get(url): """Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url) data = response.read() data = data.decode("utf-8") data = json.loads(data) return data
<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_day(): """Function for retrieving the wanted day"""
day = datetime.datetime.today().weekday() if len(sys.argv) == 3: if sys.argv[2] == "mon": day = 0 elif sys.argv[2] == "tue": day = 1 elif sys.argv[2] == "wed": day = 2 elif sys.argv[2] == "thur": day = 3 elif sys.argv[2] == "fri": day = 4 else: day = 5 if day > 4: print("There is no information about the menu today.") exit(5) return day
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_menu(place, static=False): """Function for printing the menu Keyword arguments: place -- name of the cafeteria / mensa static -- set true if a static menu exists (default: False) """
day = get_day() if static: plan = get(FILES[1]) for meal in plan["weeks"][0]["days"][day][place]["meals"]: if place == "Diner": print(meal["category"] + " " + meal["meal"]) else: print(meal["category"] + ": " + meal["meal"]) else: plan = get(FILES[0]) for meal in plan["weeks"][0]["days"][day][place]["meals"]: print(meal["category"] + ": " + meal["meal"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_init(prog_name, prof_mgr, prof_name, prog_args): """ Initialize a profile. """
# Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) parser.add_argument( "type", metavar="type", type=str, nargs=1, help="profile type" ) args = parser.parse_args(prog_args) # Profile store prof_type = args.type[0] prof_mgr.store(prof_name, prof_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_list(prog_name, prof_mgr, prof_name, prog_args): """ Print the list of components. """
# Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) args = parser.parse_args(prog_args) # Profile load prof_stub = prof_mgr.load(prof_name) # Print component list out = io.StringIO() for comp_stub in prof_stub.component_list(): if comp_stub.name() is not None: out.write(comp_stub.name()) out.write("\n") out.seek(0) sys.stdout.write(out.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_status(prog_name, prof_mgr, prof_name, prog_args): """ Show status of component tree. """
# Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) parser.add_argument( "-t", "--type", required=False, action="store_true", default=False, dest="show_type", help="show component qualified class name" ) parser.add_argument( "-d", "--depth", metavar="tree_depth", required=False, type=argparse_status_depth, default=None, dest="tree_depth", help="integer value of dependency tree depth" ) parser.add_argument( "components", metavar="comps", nargs=argparse.REMAINDER, help="system components" ) args = parser.parse_args(prog_args) # Profile load prof_stub = prof_mgr.load(prof_name) # Collect component stubs comp_stubs = [] if len(args.components) == 0: raise Exception("Empty component list") for comp_name in args.components: comp_stub = prof_stub.component(comp_name) component_exists(prof_stub, comp_stub) comp_stubs.append(comp_stub) # Print status show_type = args.show_type tree_depth = args.tree_depth context = prof_stub.context() out = io.StringIO() for i, comp_stub in enumerate(comp_stubs): last = i == len(comp_stubs) - 1 print_component_status(out, context, comp_stub, last, 1, [], show_type, tree_depth) out.seek(0) sys.stdout.write(out.read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_insert(prog_name, prof_mgr, prof_name, prog_args): """ Insert components. """
# Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) parser.add_argument( "components", metavar="comps", nargs=argparse.REMAINDER, help="system components" ) args = parser.parse_args(prog_args) # Profile load prof_stub = prof_mgr.load(prof_name) # Collect component stubs comp_stubs = [] if len(args.components) == 0: raise Exception("Empty component list") for comp_name in args.components: comp_stub = prof_stub.component(comp_name) component_exists(prof_stub, comp_stub) comp_stubs.append(comp_stub) # Create insert plan context = prof_stub.context() plan = [] for comp_stub in comp_stubs: comp_stub.insert(context, plan) # Execute insert plan for op in plan: operation_execute(op, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command_update(prog_name, prof_mgr, prof_name, prog_args): """ Update components. """
# Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) parser.add_argument( "components", metavar="comps", nargs=argparse.REMAINDER, help="system components" ) args = parser.parse_args(prog_args) # Profile load prof_stub = prof_mgr.load(prof_name) # Collect component stubs comp_stubs = [] if len(args.components) == 0: raise Exception("Empty component list") for comp_name in args.components: comp_stub = prof_stub.component(comp_name) component_exists(prof_stub, comp_stub) comp_stubs.append(comp_stub) context = prof_stub.context() # Create delete plan plan = [] for comp_stub in comp_stubs: comp_stub.delete(context, plan) # Execute delete plan for op in plan: operation_execute(op, context) # Update component stub list for op in plan: comp_stub = prof_stub.component(op.name()) if comp_stub not in comp_stubs: comp_stubs.append(comp_stub) # Create insert plan plan = [] for comp_stub in comp_stubs: comp_stub.insert(context, plan) # Execute insert plan for op in plan: operation_execute(op, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gp_sims_panel(version): """panel plot of cocktail simulations at all energies, includ. total :param version: plot version / input subdir name :type version: str """
inDir, outDir = getWorkDirs() inDir = os.path.join(inDir, version) mesons = ['pion', 'eta', 'etap', 'rho', 'omega', 'phi', 'jpsi'] fstems = ['cocktail_contribs/'+m for m in mesons] + ['cocktail', 'cocktail_contribs/ccbar'] data = OrderedDict((energy, [ np.loadtxt(open(os.path.join(inDir, fstem+str(energy)+'.dat'), 'rb')) for fstem in fstems ]) for energy in energies) for v in data.values(): # keep syserrs for total cocktail v[-2][:,(2,3)] = 0 # all errors zero for cocktail contribs v[-1][:,2:] = 0 for d in v[:-2]: d[:,2:] = 0 make_panel( dpt_dict = OrderedDict(( ' '.join([getEnergy4Key(str(energy)), 'GeV']), [ data[energy], [ 'with %s lc %s lw 5 lt %d' % ( 'lines' if i!=len(fstems)-2 else 'filledcurves pt 0', default_colors[(-2*i-2) if i!=len(fstems)-2 else 0] \ if i!=len(fstems)-1 else default_colors[1], int(i==3)+1 ) for i in xrange(len(fstems)) ], [particleLabel4Key(m) for m in mesons] + [ 'Cocktail (w/o {/Symbol \162})', particleLabel4Key('ccbar') ]] ) for energy in energies), name = os.path.join(outDir, 'sims_panel'), ylog = True, xr = [0.,3.2], yr = [1e-6,9], xlabel = xlabel, ylabel = ylabel, layout = '2x2', size = '7in,9in', key = ['width -4', 'spacing 1.5', 'nobox', 'at graph 0.9,0.95'] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gp_sims_total_overlay(version): """single plot comparing total cocktails at all energies :param version: plot version / input subdir name :type version: str """
inDir, outDir = getWorkDirs() inDir = os.path.join(inDir, version) data = OrderedDict() for energy in energies: fname = os.path.join(inDir, 'cocktail'+str(energy)+'.dat') data[energy] = np.loadtxt(open(fname, 'rb')) data[energy][:,2:] = 0 make_plot( data = data.values(), properties = [ 'with lines lc %s lw 4 lt 1' % (default_colors[i]) for i in xrange(len(energies)) ], titles = [ ' '.join([getEnergy4Key(str(energy)), 'GeV']) for energy in energies ], xlabel = xlabel, ylabel = ylabel, name = os.path.join(outDir, 'sims_total_overlay'), ylog = True, xr = [0.,3.2], yr = [1e-6,9], tmargin = 0.98, rmargin = 0.99, bmargin = 0.14, size = '8.5in,8in', )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_image(tarpath, outfolder, **kwargs): """Unpack the OS image stored at tarpath to outfolder. Prepare the unpacked image for use as a VR base image. """
outfolder = path.Path(outfolder) untar(tarpath, outfolder, **kwargs) # Some OSes have started making /etc/resolv.conf into a symlink to # /run/resolv.conf. That prevents us from bind-mounting to that # location. So delete that symlink, if it exists. resolv_path = outfolder / 'etc' / 'resolv.conf' if resolv_path.islink(): resolv_path.remove().write_text('', encoding='ascii')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_image(self): """ Ensure that config.image_url has been downloaded and unpacked. """
image_folder = self.get_image_folder() if os.path.exists(image_folder): print( 'OS image directory {} exists...not overwriting' .format( image_folder)) return ensure_image( self.config.image_name, self.config.image_url, IMAGES_ROOT, getattr(self.config, 'image_md5', None), self.get_image_folder() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, msg): """Send a notification to all registered listeners. msg : str Message to send to each listener """
for listener in self.listeners: self._send(listener, 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 get_deps_manager(self, *args, **kwargs): """ Return instance of the dependancies manager using given args and kwargs Add 'silent_key_error' option in kwargs if not given. """
if 'silent_key_error' not in kwargs: kwargs['silent_key_error'] = self.silent_key_error return self.deps_manager(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_template(self, mapfile, names, renderer): """ Build source from global and item templates """
AVAILABLE_DUMPS = json.load(open(mapfile, "r")) manager = self.get_deps_manager(AVAILABLE_DUMPS) fp = StringIO.StringIO() for i, item in enumerate(manager.get_dump_order(names), start=1): fp = renderer(fp, i, item, manager[item]) if self.dump_other_apps: exclude_models = ['-e {0}'.format(app) for app in self.exclude_apps] for i, item in enumerate(manager.get_dump_order(names), start=1): for model in manager[item]['models']: if '-e ' not in model: model = "-e {0}".format(model) if model not in exclude_models: exclude_models.append(model) fp = renderer(fp, i+1, 'other_apps', {'models': exclude_models, 'use_natural_key': True}) content = fp.getvalue() fp.close() context = self.get_global_context().copy() context.update({'items': content}) return self.base_template.format(**context)
<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_dump_item_context(self, index, name, opts): """ Return a formated dict context """
c = { 'item_no': index, 'label': name, 'name': name, 'models': ' '.join(opts['models']), 'natural_key': '', } if opts.get('use_natural_key', False): c['natural_key'] = ' -n' c.update(self.get_global_context()) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dumpdata_template(self, stringbuffer, index, name, opts): """ StringIO "templates" to build a command line for 'dumpdata' """
context = self._get_dump_item_context(index, name, opts) stringbuffer.write(self.dumper_item_template.format(**context)) return stringbuffer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _loaddata_template(self, stringbuffer, index, name, opts): """ StringIO "templates" to build a command line for 'loaddata' """
context = self._get_dump_item_context(index, name, opts) stringbuffer.write(self.loadder_item_template.format(**context)) return stringbuffer
<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_dumper(self, mapfile, names): """ Build dumpdata commands """
return self.build_template(mapfile, names, self._dumpdata_template)
<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_loader(self, mapfile, names): """ Build loaddata commands """
return self.build_template(mapfile, names, self._loaddata_template)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tbframes(tb): 'unwind traceback tb_next structure to array' frames=[tb.tb_frame] while tb.tb_next: tb=tb.tb_next; frames.append(tb.tb_frame) return frames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tbfuncs(frames): 'this takes the frames array returned by tbframes' return ['%s:%s:%s'%(os.path.split(f.f_code.co_filename)[-1],f.f_code.co_name,f.f_lineno) for f in frames]
<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_result(self, _type, test, exc_info=None): """ Adds the given result to the list :param test: the test :param exc_info: additional execution information """
if exc_info is not None: exc_info = FrozenExcInfo(exc_info) test.time_taken = time.time() - self.start_time test._outcome = None self.result_queue.put((_type, test, exc_info))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addError(self, test, err): """ registers a test as error :param test: test to register :param err: error the test gave """
super().addError(test, err) self.test_info(test) self._call_test_results('addError', test, err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addExpectedFailure(self, test, err): """ registers as test as expected failure :param test: test to register :param err: error the test gave """
super().addExpectedFailure(test, err) self.test_info(test) self._call_test_results('addExpectedFailure', test, err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addFailure(self, test, err): """ registers a test as failure :param test: test to register :param err: error the test gave """
super().addFailure(test, err) self.test_info(test) self._call_test_results('addFailure', test, err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSkip(self, test, reason): """ registers a test as skipped :param test: test to register :param reason: reason why the test was skipped """
super().addSkip(test, reason) self.test_info(test) self._call_test_results('addSkip', test, reason)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addSuccess(self, test): """ registers a test as successful :param test: test to register """
super().addSuccess(test) self.test_info(test) self._call_test_results('addSuccess', test)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addUnexpectedSuccess(self, test): """ registers a test as an unexpected success :param test: test to register """
super().addUnexpectedSuccess(test) self.test_info(test) self._call_test_results('addUnexpectedSuccess', test)
<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) -> None: """ processes entries in the queue until told to stop """
while not self.cleanup: try: result, test, additional_info = self.result_queue.get(timeout=1) except queue.Empty: continue self.result_queue.task_done() if result == TestState.serialization_failure: test = self.tests[test] warnings.warn("Serialization error: {} on test {}".format( additional_info, test), SerializationWarning) test(self) else: self.testsRun += 1 if result == TestState.success: self.addSuccess(test) elif result == TestState.failure: self.addFailure(test, additional_info) elif result == TestState.error: self.addError(test, additional_info) elif result == TestState.skipped: self.addSkip(test, additional_info) elif result == TestState.expected_failure: self.addExpectedFailure(test, additional_info) elif result == TestState.unexpected_success: self.addUnexpectedSuccess(test) else: raise Exception("This is not a valid test type :", 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 _expand_argument(self, arg): """Performs argument glob expansion on an argument string. Returns a list of strings. """
if isinstance(arg, R): return [arg.str] scope = self._scope or self._exports arg = arg % scope arg = os.path.expanduser(arg) res = glob.glob(self._expand_path(arg)) if not res: return [arg] if self._cwd != "/": for idx in xrange(0, len(res)): if res[idx].startswith(self._cwd + "/"): res[idx] = "./" + res[idx][len(self._cwd + "/"):] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry_on_bad_auth(func): """If bad token or board, try again after clearing relevant cache entries"""
@wraps(func) def retry_version(self, *args, **kwargs): while True: try: return func(self, *args, **kwargs) except trolly.ResourceUnavailable: sys.stderr.write('bad request (refresh board id)\n') self._board_id = None self.save_key('board_id', None) except trolly.Unauthorised: sys.stderr.write('bad permissions (refresh token)\n') self._client = None self._token = None self.save_key('token', None) return retry_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 cached_accessor(func_or_att): """Decorated function checks in-memory cache and disc cache for att first"""
if callable(func_or_att): #allows decorator to be called without arguments att = func_or_att.__name__ return cached_accessor(func_or_att.__name__)(func_or_att) att = func_or_att def make_cached_function(func): @wraps(func) def cached_check_version(self): private_att = '_'+att if getattr(self, private_att): return getattr(self, private_att) setattr(self, private_att, self.load_key(att)) if getattr(self, private_att): return getattr(self, private_att) value = func(self) setattr(self, private_att, value) self.save_key(att, value) return value return cached_check_version return make_cached_function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_for_board_id(self): """Factored out in case interface isn't keyboard"""
board_id = raw_input("paste in board id or url: ").strip() m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id) if m: board_id = m.group(1) return board_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_share(self, sharename): """ Get a specific share. Does not require authentication. Input: * A sharename Output: * A :py:mod:`pygett.shares.GettShare` object Example:: share = client.get_share("4ddfds") """
response = GettRequest().get("/shares/%s" % sharename) if response.http_status == 200: return GettShare(self.user, **response.response)
<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(self, sharename, fileid): """ Get a specific file. Does not require authentication. Input: * A sharename * A fileid - must be an integer Output: * A :py:mod:`pygett.files.GettFile` object Example:: file = client.get_file("4ddfds", 0) """
if not isinstance(fileid, int): raise TypeError("'fileid' must be an integer") response = GettRequest().get("/files/%s/%d" % (sharename, fileid)) if response.http_status == 200: return GettFile(self.user, **response.response)
<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_share(self, **kwargs): """ Create a new share. Takes a keyword argument. Input: * ``title`` optional share title (optional) Output: * A :py:mod:`pygett.shares.GettShare` object Example:: new_share = client.create_share( title="Example Title" ) """
params = None if 'title' in kwargs: params = {"title": kwargs['title']} response = GettRequest().post(("/shares/create?accesstoken=%s" % self.user.access_token()), params) if response.http_status == 200: return GettShare(self.user, **response.response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_file(self, **kwargs): """ Upload a file to the Gett service. Takes keyword arguments. Input: * ``filename`` the filename to use in the Gett service (required) * ``data`` the file contents to store in the Gett service (required) - must be a string * ``sharename`` the name of the share in which to store the data (optional); if not given, a new share will be created. * ``title`` the share title to use if a new share is created (optional) Output: * A :py:mod:`pygett.files.GettFile` object Example:: file = client.upload_file(filaname="foo", data=open("foo.txt").read()) """
params = None if 'filename' not in kwargs: raise AttributeError("Parameter 'filename' must be given") else: params = { "filename": kwargs['filename'] } if 'data' not in kwargs: raise AttributeError("Parameter 'data' must be given") sharename = None if 'sharename' not in kwargs: share = None if 'title' in kwargs: share = self.create_share(title=kwargs['title']) else: share = self.create_share() sharename = share.sharename else: sharename = kwargs['sharename'] response = GettRequest().post("/files/%s/create?accesstoken=%s" % (sharename, self.user.access_token()), params) f = None if response.http_status == 200: if 'sharename' not in response.response: response.response['sharename'] = sharename f = GettFile(self.user, **response.response) if f.send_data(data=kwargs['data']): return 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 samdb_connect(): """ Open and return a SamDB connection """
with root(): lp = samba.param.LoadParm() lp.load("/etc/samba/smb.conf") creds = Credentials() creds.guess(lp) session = system_session() samdb = SamDB("/var/lib/samba/private/sam.ldb", session_info=session, credentials=creds, lp=lp) return samdb