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...
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, sel...
<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: 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 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 priv...
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,...
<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 ...
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 acti...
<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 ...
#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 comple...
<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...
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._na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, file_parser, section_name): """The current element is loaded from the configuration file, all constraints and requirements are checked. Then eleme...
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. Thi...
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: ...
<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 ...
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 **paramete...
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 ``<botocor...
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 :t...
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 f...
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') : ...
<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 dat...
# 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...
<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 r...
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_po...
<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, ...
<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...
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: ...
<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: ...
<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, li...
<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 :...
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...
<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...
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() e...
<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...
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() ...
<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: :rt...
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 th...
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] = v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 nam...
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): ...
<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 :retu...
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: :...
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 insta...
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', hos...
<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 ...
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...
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: ...
<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...
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 ...
<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, clo...
<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: retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 ...
<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 s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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_hexd...
<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 ...
<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(): ...
<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 observation...
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 outp...
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(...
<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 ...
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] ==...
<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 m...
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: ...
<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_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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", req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 co...
<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 co...
<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: ...
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(ener...
<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(), propert...
<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....
<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.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 '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: ...
<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()) ...
<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.te...
<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)): ...
<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 ...
<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_...
<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` obj...
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...
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:`pyget...
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 (r...
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 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 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) ...