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 icons(self, strip_ext=False): '''Get all icons in this DAP, optionally strip extensions''' result = [f for f in self._stripped_files if self._icons_pattern.match(f)] if strip_ext: result = [strip_suffix(f, '\.({ext})'.format(ext=self._icons_ext), regex=True) for f in 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 _find_bad_meta(self): '''Fill self._badmeta with meta datatypes that are invalid''' self._badmeta = dict() for datatype in self.meta: for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): if datatype not in self._badme...
<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, path, prepend=False): '''Extracts a file from dap to a file-like object''' if prepend: path = os.path.join(self._dirname(), path) extracted = self._tar.extractfile(path) if extracted: return extracted raise DapFileError(('Could not 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_meta(self, meta): '''Load data from meta.yaml to a dictionary''' meta = yaml.load(meta, Loader=Loader) # Versions are often specified in a format that is convertible to an # int or a float, so we want to make sure it is interpreted as a str. # Fix for the bug #300. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _report_problem(self, problem, level=logging.ERROR): '''Report a given problem''' problem = self.basename + ': ' + problem if self._logger.isEnabledFor(level): self._problematic = True if self._check_raises: raise DapInvalid(problem) self._logger.log(l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _isvalid(self, datatype): '''Checks if the given datatype is valid in meta''' if datatype in self.meta: return bool(Dap._meta_valid[datatype].match(self.meta[datatype])) else: return datatype in Dap._optional_meta
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _is_dir(self, f): '''Check if the given in-dap file is a directory''' return self._tar.getmember(f).type == tarfile.DIRTYPE
<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_emptydirs(self, files): '''Find empty directories and return them Only works for actual files in dap''' emptydirs = [] for f in files: if self._is_dir(f): empty = True for ff in files: if ff.startswith(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 load_configuration_file(self): """ Load all configuration from file """
if not os.path.exists(self.config_file): return try: with open(self.config_file, 'r') as file: csvreader = csv.reader(file, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE) for line in csvreader: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_configuration_file(self): """ Save all configuration into file Only if config file does not yet exist or configuration was changed """
if os.path.exists(self.config_file) and not self.config_changed: return dirname = os.path.dirname(self.config_file) try: if not os.path.exists(dirname): os.makedirs(dirname) except (OSError, IOError) as e: self.logger.warning("Could no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_config_value(self, name, value): """ Set configuration value with given name. Value can be string or boolean type. """
if value is True: value = "True" elif value is False: if name in self.config_dict: del self.config_dict[name] self.config_changed = True return if name not in self.config_dict or self.config_dict[name] != value: 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 tooltip_queries(self, item, x_coord, y_coord, key_mode, tooltip, text): """ The function is used for setting tooltip on menus and submenus """
tooltip.set_text(text) 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 _open_path_window(self): """ Hides this window and opens path window. Passes all needed data and kwargs. """
self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.get_current_main_assistant() self.data['kwargs'] = self.kwargs self.path_window.open_window(self.data) self.main_win.hide()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub_menu_pressed(self, widget, event): """ Function serves for getting full assistant path and collects the information from GUI """
for index, data in enumerate(self.dev_assistant_path): index += 1 if settings.SUBASSISTANT_N_STRING.format(index) in self.kwargs: del self.kwargs[settings.SUBASSISTANT_N_STRING.format(index)] self.kwargs[settings.SUBASSISTANT_N_STRING.format(index)] = 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_current_main_assistant(self): """ Function return current assistant """
current_page = self.notebook.get_nth_page(self.notebook.get_current_page()) return current_page.main_assistant
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def btn_clicked(self, widget, data=None): """ Function is used for case that assistant does not have any subassistants """
self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self.kwargs['subassistant_1'] = data if 'subassistant_2' in self.kwargs: del self.kwargs['subassistant_2'] self._open_path_window()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def btn_press_event(self, widget, event): """ Function is used for showing Popup menu """
if event.type == Gdk.EventType.BUTTON_PRESS: if event.button.button == 1: widget.popup(None, None, None, None, event.button.button, event.time) return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_gui(): """ Function for running DevAssistant GUI """
try: from gi.repository import Gtk except ImportError as ie: pass except RuntimeError as e: sys.stderr.write(GUI_MESSAGE) sys.stderr.write("%s: %r" % (e.__class__.__name__, utils.exc_as_decoded_string(e))) sys.stderr.flush() sys.exit(1) if not os.environ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def needs_fully_loaded(method): """Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded from cache, this decorator will fully load i...
@functools.wraps(method) def inner(self, *args, **kwargs): if not self.fully_loaded: loaded_yaml = yaml_loader.YamlLoader.load_yaml_by_path(self.path) self.parsed_yaml = loaded_yaml self.fully_loaded = True return method(self, *args, **kwargs) return inn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_icon_path(self): """Returns default path to icon of this assistant. Assuming self.path == "/foo/assistants/crt/python/django.yaml" For image format i...
supported_exts = ['.png', '.svg'] stripped = self.path.replace(os.path.join(self.load_path, 'assistants'), '').strip(os.sep) for ext in supported_exts: icon_with_ext = os.path.splitext(stripped)[0] + ext icon_fullpath = os.path.join(self.load_path, 'icons', icon_with_ext...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dependencies(self, kwargs=None, expand_only=False): """Returns all dependencies of this assistant with regards to specified kwargs. If expand_only == False, ...
# we can't use {} as a default for kwargs, as that initializes the dict only once in Python # and uses the same dict in all subsequent calls of this method if not kwargs: kwargs = {} self.proper_kwargs('dependencies', kwargs) sections = self._get_dependency_sections...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _try_get_current_manager(cls): """ Try to detect a package manager used in a current Gentoo system. """
if utils.get_distro_name().find('gentoo') == -1: return None if 'PACKAGE_MANAGER' in os.environ: pm = os.environ['PACKAGE_MANAGER'] if pm == 'paludis': # Try to import paludis module try: import paludis ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_current_manager_equals_to(cls, pm): """Returns True if this package manager is usable, False otherwise."""
if hasattr(cls, 'works_result'): return cls.works_result is_ok = bool(cls._try_get_current_manager() == pm) setattr(cls, 'works_result', is_ok) return is_ok
<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_package_manager(self, dep_t): """Choose proper package manager and return it."""
mgrs = managers.get(dep_t, []) for manager in mgrs: if manager.works(): return manager if not mgrs: err = 'No package manager for dependency type "{dep_t}"'.format(dep_t=dep_t) raise exceptions.NoPackageManagerException(err) 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 _ask_to_confirm(self, ui, pac_man, *to_install): """ Return True if user wants to install packages, False otherwise """
ret = DialogHelper.ask_for_package_list_confirm( ui, prompt=pac_man.get_perm_prompt(to_install), package_list=to_install, ) return bool(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 _install_dependencies(self, ui, debug): """Install missing dependencies"""
for dep_t, dep_l in self.dependencies: if not dep_l: continue pkg_mgr = self.get_package_manager(dep_t) pkg_mgr.works() to_resolve = [] for dep in dep_l: if not pkg_mgr.is_pkg_installed(dep): to_reso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ass_needs_refresh(self, cached_ass, file_ass): """Checks if assistant needs refresh. Assistant needs refresh iff any of following conditions is True: - stor...
if cached_ass['source'] != file_ass['source']: return True if os.path.getctime(file_ass['source']) > cached_ass.get('ctime', 0.0): return True if set(cached_ass['subhierarchy'].keys()) != set(set(file_ass['subhierarchy'].keys())): return True for snip...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ass_refresh_attrs(self, cached_ass, file_ass): """Completely refreshes cached assistant from file. Args: cached_ass: an assistant from cache hierarchy (for ...
# we need to process assistant in custom way to see unexpanded args, etc. loaded_ass = yaml_loader.YamlLoader.load_yaml_by_path(file_ass['source'], log_debug=True) attrs = loaded_ass yaml_checker.check(file_ass['source'], attrs) cached_ass['source'] = file_ass['source'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _new_ass_hierarchy(self, file_ass): """Returns a completely new cache hierarchy for given assistant file. Args: file_ass: the assistant from filesystem hiera...
ret_struct = {'source': '', 'subhierarchy': {}, 'attrs': {}, 'snippets': {}} ret_struct['source'] = file_ass['source'] self._ass_refresh_attrs(ret_struct, file_ass) for name, subhierarchy in file_ass['subhierarchy'].item...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_for_control_var_and_eval_expr(comm_type, kwargs): """Returns tuple that consists of control variable name and iterable that is result of evaluated expres...
# let possible exceptions bubble up control_vars, iter_type, expression = parse_for(comm_type) eval_expression = evaluate_expression(expression, kwargs)[1] iterval = [] if len(control_vars) == 2: if not isinstance(eval_expression, dict): raise exceptions.YamlSyntaxError('Can\'t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbol(self, id, bp=0): """ Adds symbol 'id' to symbol_table if it does not exist already, if it does it merely updates its binding power and returns it's sy...
try: s = self.symbol_table[id] except KeyError: class s(self.symbol_base): pass s.id = id s.lbp = bp self.symbol_table[id] = s else: s.lbp = max(bp, s.lbp) return 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 advance(self, id=None): """ Advance to next token, optionally check that current token is 'id' """
if id and self.token.id != id: raise SyntaxError("Expected {0}".format(id)) self.token = self.next()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def method(self, symbol_name): """ A decorator - adds the decorated method to symbol 'symbol_name' """
s = self.symbol(symbol_name) def bind(fn): setattr(s, fn.__name__, fn) return bind
<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_platforms_set(): '''Returns set of all possible platforms''' # arch and mageia are not in Py2 _supported_dists, so we add them manually # Ubuntu adds itself to the list on Ubuntu platforms = set([x.lower() for x in platform._supported_dists]) platforms |= set(['darwin', 'arch', 'mageia', 'ub...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_file_in_load_dirs(relpath): """If given relative path exists in one of DevAssistant load paths, return its full path. Args: relpath: a relative path, e....
if relpath.startswith(os.path.sep): relpath = relpath.lstrip(os.path.sep) for ld in settings.DATA_DIRECTORIES: possible_path = os.path.join(ld, relpath) if os.path.exists(possible_path): return possible_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 run_exitfuncs(): """Function that behaves exactly like Python's atexit, but runs atexit functions in the order in which they were registered, not reversed. "...
exc_info = None for func, targs, kargs in _exithandlers: try: func(*targs, **kargs) except SystemExit: exc_info = sys.exc_info() except: exc_info = sys.exc_info() if exc_info is not None: six.reraise(exc_info[0], exc_info[1], exc_info[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 strip_prefix(string, prefix, regex=False): """Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression."""
if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types): msg = 'Arguments to strip_prefix must be string types. Are: {s}, {p}'\ .format(s=type(string), p=type(prefix)) raise TypeError(msg) if not regex: prefix = re.escape(prefix) if not...
<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_suffix(string, suffix, regex=False): """Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression."""
if not isinstance(string, six.string_types) or not isinstance(suffix, six.string_types): msg = 'Arguments to strip_suffix must be string types. Are: {s}, {p}'\ .format(s=type(string), p=type(suffix)) raise TypeError(msg) if not regex: suffix = re.escape(suffix) if not...
<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(string, pattern): """Return complement of pattern in string"""
m = re.compile(pattern).search(string) if m: return string[0:m.start()] + string[m.end():len(string)] else: return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_console_logging_handler(cls, lgr, level=logging.INFO): """Registers console logging handler to given logger."""
console_handler = logger.DevassistantClHandler(sys.stdout) if console_handler.stream.isatty(): console_handler.setFormatter(logger.DevassistantClColorFormatter()) else: console_handler.setFormatter(logger.DevassistantClFormatter()) console_handler.setLevel(level)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inform_of_short_bin_name(cls, binary): """Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassistant", bu...
binary = os.path.splitext(os.path.basename(binary))[0] if binary != 'da': msg = '"da" is the preffered way of running "{binary}".'.format(binary=binary) logger.logger.info('*' * len(msg)) logger.logger.info(msg) logger.logger.info('*' * len(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_full_dir_name(self): """ Function returns a full dir name """
return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_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 next_window(self, widget, data=None): """ Function opens the run Window who executes the assistant project creation """
# check whether deps-only is selected deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active()) # preserve argument value if it is needed to be preserved for arg_dict in [x for x in self.args.values() if 'preserved' in x['arg'].kwargs]: pres...
<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_flags(self): """ Function builds kwargs variable for run_window """
# Check if all entries for selected arguments are nonempty for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: if 'entry' in arg_dict and not arg_dict['entry'].get_text(): self.gui_helper.execute_dialog("Entry {0} is empty".format(arg_dict['label'])) ...
<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_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """
active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' in self.args[arg_name]: self.args[arg_name]['browse_btn'].set_sensitive(active) self.path_window.show_all(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deps_only_toggled(self, widget, data=None): """ Function deactivate options in case of deps_only and opposite """
active = widget.get_active() self.dir_name.set_sensitive(not active) self.entry_project_name.set_sensitive(not active) self.dir_name_browse_btn.set_sensitive(not active) self.run_btn.set_sensitive(active or not self.project_name_shown or self.entry_project_name.get_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 prev_window(self, widget, data=None): """ Function returns to Main Window """
self.path_window.hide() self.parent.open_window(widget, self.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 browse_path(self, window): """ Function opens the file chooser dialog for settings project dir """
text = self.gui_helper.create_file_chooser_dialog("Choose project directory", self.path_window, name="Select") if text is not None: self.dir_name.set_text(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 browse_clicked(self, widget, data=None): """ Function sets the directory to entry """
text = self.gui_helper.create_file_chooser_dialog("Please select directory", self.path_window) if text is not None: data.set_text(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 project_name_changed(self, widget, data=None): """ Function controls whether run button is enabled """
if widget.get_text() != "": self.run_btn.set_sensitive(True) else: self.run_btn.set_sensitive(False) self.update_full_label()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing current project directory in co...
config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) self.update_full_label()
<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(self): """Checks whether loaded yaml is well-formed according to syntax defined for version 0.9.0 and later. Raises: YamlError: (containing a meaningfu...
if not isinstance(self.parsed_yaml, dict): msg = 'In {0}:\n'.format(self.sourcefile) msg += 'Assistants and snippets must be Yaml mappings, not "{0}"!'.\ format(self.parsed_yaml) raise exceptions.YamlTypeError(msg) self._check_fullname(self.sourcefile...
<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_args(self, source): '''Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). ''' path = [source] args = self.parsed_yaml.get('args', {}) self._assert_struct_type(args, 'args', (dict, list), path) path.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _assert_struct_type(self, struct, name, types, path=None, extra_info=None): """Asserts that given structure is of any of given types. Args: struct: structure...
wanted_yaml_typenames = set() for t in types: wanted_yaml_typenames.add(self._get_yaml_typename(t)) wanted_yaml_typenames = ' or '.join(wanted_yaml_typenames) actual_yaml_typename = self._get_yaml_typename(type(struct)) if not isinstance(struct, types): 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 _split_license(license): '''Returns all individual licenses in the input''' return (x.strip() for x in (l for l in _regex.split(license) if l))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def match(license): '''Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp.''' if license not in VALID_LICENSES: for l1 in _split_license(license): if l1 in VALID_LICENSES: continue for l2 in _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 _cut(ver): '''Cuts the version to array, excepts valid version''' ver = ver.split('.') for i, part in enumerate(ver): try: ver[i] = int(part) except: if part[-len('dev'):] == 'dev': ver[i] = int(part[:-len('dev')]) ver.append(-3) ...
<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_argument_parser(cls, tree, actions={}): """Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by...
cur_as, cur_subas = tree parser = devassistant_argparse.ArgumentParser(argument_default=argparse.SUPPRESS, usage=argparse.SUPPRESS, add_help=False) cls.add_default_arguments_to(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 add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): """Adds assistant from given part of assistant tree and all its subassistants to a giv...
name = alias or assistant_tuple[0].name p = parser.add_parser(name, description=assistant_tuple[0].description, argument_default=argparse.SUPPRESS) for arg in assistant_tuple[0].args: arg.add_argument_to(p) if len(...
<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_action_to(cls, parser, action, subactions, level): """Adds given action to given parser Args: parser: instance of devassistant_argparse.ArgumentParser ac...
p = parser.add_parser(action.name, description=action.description, argument_default=argparse.SUPPRESS) for arg in action.args: arg.add_argument_to(p) if subactions: subparsers = cls._add_subparsers_required(p, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_entry(record, show_level=False, colorize=False): """ Format a log entry according to its level and context """
if show_level: log_str = u'{}: {}'.format(record.levelname, record.getMessage()) else: log_str = record.getMessage() if colorize and record.levelname in LOG_COLORS: log_str = u'<span color="{}">'.format(LOG_COLORS[record.levelname]) + log_str + u'</span>' return log_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_cursor(cursor_type, parent_window): """ Functions switches the cursor to cursor type """
watch = Gdk.Cursor(cursor_type) window = parent_window.get_root_window() window.set_cursor(watch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit(self, record): """ Function inserts log messages to list_view """
msg = record.getMessage() list_store = self.list_view.get_model() Gdk.threads_enter() if msg: # Underline URLs in the record message msg = replace_markup_chars(record.getMessage()) record.msg = URL_FINDER.sub(r'<u>\1</u>', msg) self.parent...
<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_window(self, widget, data=None): """ Function opens the run window """
if data is not None: self.kwargs = data.get('kwargs', None) self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.debugging = data.get('debugging', False) if not self.debugging...
<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_link_button(self): """ Function removes link button from Run Window """
if self.link is not None: self.info_box.remove(self.link) self.link.destroy() self.link = 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 delete_event(self, widget, event, data=None): """ Event cancels the project creation """
if not self.close_win: if self.thread.isAlive(): dlg = self.gui_helper.create_message_dialog("Do you want to cancel project creation?", buttons=Gtk.ButtonsType.YES_NO) response = dlg.run() if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_view_changed(self, widget, event, data=None): """ Function shows last rows. """
adj = self.scrolled_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_buttons(self): """ Function disables buttons """
self.main_btn.set_sensitive(False) self.back_btn.hide() self.info_label.set_label('<span color="#FFA500">In progress...</span>') self.disable_close_window() if self.link is not None: self.link.hide()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allow_buttons(self, message="", link=True, back=True): """ Function allows buttons """
self.info_label.set_label(message) self.allow_close_window() if link and self.link is not None: self.link.set_sensitive(True) self.link.show_all() if back: self.back_btn.show() self.main_btn.set_sensitive(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 dev_assistant_start(self): """ Thread executes devassistant API. """
#logger_gui.info("Thread run") path = self.top_assistant.get_selected_subassistant_path(**self.kwargs) kwargs_decoded = dict() for k, v in self.kwargs.items(): kwargs_decoded[k] = \ v.decode(utils.defenc) if not six.PY3 and isinstance(v, str) else v 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 debug_btn_clicked(self, widget, data=None): """ Event in case that debug button is pressed. """
self.store.clear() self.thread = threading.Thread(target=self.logs_update) self.thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logs_update(self): """ Function updates logs. """
Gdk.threads_enter() if not self.debugging: self.debugging = True self.debug_btn.set_label('Info logs') else: self.debugging = False self.debug_btn.set_label('Debug logs') for record in self.debug_logs['logs']: if self.debugging...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clipboard_btn_clicked(self, widget, data=None): """ Function copies logs to clipboard. """
_clipboard_text = [] for record in self.debug_logs['logs']: if self.debugging: _clipboard_text.append(format_entry(record, show_level=True)) else: if int(record.levelno) > 10: if getattr(record, 'event_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 back_btn_clicked(self, widget, data=None): """ Event for back button. This occurs in case of devassistant fail. """
self.remove_link_button() self.run_window.hide() self.parent.path_window.path_window.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main_btn_clicked(self, widget, data=None): """ Button switches to Dev Assistant GUI main window """
self.remove_link_button() data = dict() data['debugging'] = self.debugging self.run_window.hide() self.parent.open_window(widget, 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 list_view_row_clicked(self, list_view, path, view_column): """ Function opens the firefox window with relevant link """
model = list_view.get_model() text = model[path][0] match = URL_FINDER.search(text) if match is not None: url = match.group(1) import webbrowser webbrowser.open(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _github_create_twofactor_authorization(cls, ui): """Create an authorization for a GitHub user using two-factor authentication. Unlike its non-two-factor coun...
try: try: # This is necessary to trigger sending a 2FA key to the user auth = cls._user.create_authorization() except cls._gh_exceptions.GithubException: onetime_pw = DialogHelper.ask_for_password(ui, prompt='Your one time password:') auth...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _github_create_simple_authorization(cls): """Create a GitHub authorization for the given user in case they don't already have one. """
try: auth = None for a in cls._user.get_authorizations(): if a.note == 'DevAssistant': auth = a if not auth: auth = cls._user.create_authorization( scopes=['repo', 'user', 'admin:public_key'], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _github_store_authorization(cls, user, auth): """Store an authorization token for the given GitHub user in the git global config file. """
ClHelper.run_command("git config --global github.token.{login} {token}".format( login=user.login, token=auth.token), log_secret=True) ClHelper.run_command("git config --global github.user.{login} {login}".format( login=user.login))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start_ssh_agent(cls): """Starts ssh-agent and returns the environment variables related to it"""
env = dict() stdout = ClHelper.run_command('ssh-agent -s') lines = stdout.split('\n') for line in lines: if not line or line.startswith('echo '): continue line = line.split(';')[0] parts = line.split('=') if len(parts) == 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 _github_create_ssh_key(cls): """Creates a local ssh key, if it doesn't exist already, and uploads it to Github."""
try: login = cls._user.login pkey_path = '{home}/.ssh/{keyname}'.format( home=os.path.expanduser('~'), keyname=settings.GITHUB_SSH_KEYNAME.format(login=login)) # generate ssh key only if it doesn't exist if not os.path.exists(pkey_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _github_ssh_key_exists(cls): """Returns True if any key on Github matches a local key, else False."""
remote_keys = map(lambda k: k._key, cls._user.get_keys()) found = False pubkey_files = glob.glob(os.path.expanduser('~/.ssh/*.pub')) for rk in remote_keys: for pkf in pubkey_files: local_key = io.open(pkf, encoding='utf-8').read() # in PyGithu...
<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_all_assistants(cls, superassistants): """Fills self._assistants with loaded YamlAssistant instances of requested roles. Tries to use cache (updated/crea...
# mapping of assistant roles to lists of top-level assistant instances _assistants = {} # {'crt': CreatorAssistant, ...} superas_dict = dict(map(lambda a: (a.name, a), superassistants)) to_load = set(superas_dict.keys()) for tl in to_load: dirs = [os.path.joi...
<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_assistants_from_file_hierarchy(cls, file_hierarchy, superassistant, role=settings.DEFAULT_ASSISTANT_ROLE): """Accepts file_hierarch as returned by cls.ge...
result = [] warn_msg = 'Failed to load assistant {source}, skipping subassistants.' for name, attrs in file_hierarchy.items(): loaded_yaml = yaml_loader.YamlLoader.load_yaml_by_path(attrs['source']) if loaded_yaml is None: # there was an error parsing yaml ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assistant_from_yaml(cls, source, y, superassistant, fully_loaded=True, role=settings.DEFAULT_ASSISTANT_ROLE): """Constructs instance of YamlAssistant loaded ...
# In pre-0.9.0, we required assistant to be a mapping of {name: assistant_attributes} # now we allow that, but we also allow omitting the assistant name and putting # the attributes to top_level, too. name = os.path.splitext(os.path.basename(source))[0] yaml_checker.check(source...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_legend(self, legend): """legend needs to be a list, tuple or None"""
assert(isinstance(legend, list) or isinstance(legend, tuple) or legend is None) if legend: self.legend = [quote(a) for a in legend] else: self.legend = 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 set_legend_position(self, legend_position): """Sets legend position. Default is 'r'. b - At the bottom of the chart, legend entries in a horizontal row. bv -...
if legend_position: self.legend_position = quote(legend_position) else: self.legend_position = 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 data_x_range(self): """Return a 2-tuple giving the minimum and maximum x-axis data range. """
try: lower = min([min(self._filter_none(s)) for type, s in self.annotated_data() if type == 'x']) upper = max([max(self._filter_none(s)) for type, s in self.annotated_data() if type == 'x...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_codes(self, codes): '''Set the country code map for the data. Codes given in a list. i.e. DE - Germany AT - Austria US - United States ''' codemap = '' for cc in codes: cc = cc.upper() if cc in self.__cc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_geo_area(self, area): '''Sets the geo area for the map. * africa * asia * europe * middle_east * south_america * usa * world ''' if area in self.__areas: self.geo_area = area else: raise Unk...
<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_data_dict(self, datadict): '''Sets the data and country codes via a dictionary. i.e. {'DE': 50, 'GB': 30, 'AT': 70} ''' self.set_codes(list(datadict.keys())) self.add_data(list(datadict.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 can_cast_to(v: Literal, dt: str) -> bool: """ 5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v ...
# TODO: rdflib doesn't appear to pay any attention to lengths (e.g. 257 is a valid XSD.byte) return v.value is not None and Literal(str(v), datatype=dt).value is not 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 total_digits(n: Literal) -> Optional[int]: """ 5.4.5 XML Schema Numberic Facet Constraints totaldigits and fractiondigits constraints on values not derived fr...
return len(str(abs(int(n.value)))) + fraction_digits(n) if is_numeric(n) and n.value is not None else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fraction_digits(n: Literal) -> Optional[int]: """ 5.4.5 XML Schema Numeric Facet Constraints for "fractiondigits" constraints, v is less than or equals the nu...
# Note - the last expression below isolates the fractional portion, reverses it (e.g. 017320 --> 023710) and # converts it to an integer and back to a string return None if not is_numeric(n) or n.value is None \ else 0 if is_integer(n) or '.' not in str(n.value) or str(n.value).split('.')[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 do_disable(): """ Comment any lines that start with import in the .pth file """
from vext import vext_pth try: _lines = [] with open(vext_pth, mode='r') as f: for line in f.readlines(): if not line.startswith('#') and line.startswith('import '): _lines.append('# %s' % line) else: _lines.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_check(vext_files): """ Attempt to import everything in the 'test-imports' section of specified vext_files :param: list of vext filenames (without paths), ...
import vext # not efficient ... but then there shouldn't be many of these all_specs = set(vext.gatekeeper.spec_files_flat()) if vext_files == ['*']: vext_files = all_specs unknown_specs = set(vext_files) - all_specs for fn in unknown_specs: print("%s is not an installed vext fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_path(p): """ Convert path pointing subdirectory of virtualenv site-packages to system site-packages. Destination directory must exist for this to work. '...
venv_lib = get_python_lib() if p.startswith(venv_lib): subdir = p[len(venv_lib) + 1:] for sitedir in getsyssitepackages(): fixed_path = join(sitedir, subdir) if isdir(fixed_path): return fixed_path return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixup_paths(): """ Fixup paths added in .pth file that point to the virtualenv instead of the system site packages. In depth: .PTH can execute arbitrary code...
original_paths = os.environ.get('PATH', "").split(os.path.pathsep) original_dirs = set(added_dirs) yield # Fix PATH environment variable current_paths = os.environ.get('PATH', "").split(os.path.pathsep) if original_paths != current_paths: changed_paths = set(current_paths).difference(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 addpackage(sys_sitedir, pthfile, known_dirs): """ Wrapper for site.addpackage Try and work out which directories are added by the .pth and add them to the kn...
with open(join(sys_sitedir, pthfile)) as f: for n, line in enumerate(f): if line.startswith("#"): continue line = line.rstrip() if line: if line.startswith(("import ", "import\t")): exec (line, globals(), locals()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filename_to_module(filename): """ convert a filename like html5lib-0.999.egg-info to html5lib """
find = re.compile(r"^[^.|-]*") name = re.search(find, filename).group(0) return name