text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Function creates a tree_view with model <END_TASK> <USER_TASK:> Description: def create_tree_view(self, model=None): """ Function creates a tree_view with model """
tree_view = Gtk.TreeView() if model is not None: tree_view.set_model(model) return tree_view
<SYSTEM_TASK:> Function creates a CellRendererText with title <END_TASK> <USER_TASK:> Description: def create_cell_renderer_text(self, tree_view, title="title", assign=0, editable=False): """ Function creates a CellRendererText with title """
renderer = Gtk.CellRendererText() renderer.set_property('editable', editable) column = Gtk.TreeViewColumn(title, renderer, text=assign) tree_view.append_column(column)
<SYSTEM_TASK:> Function creates a CellRendererCombo with title, model <END_TASK> <USER_TASK:> Description: def create_cell_renderer_combo(self, tree_view, title="title", assign=0, editable=False, model=None, function=None): """' Function creates a CellRendererCombo with title, model """
renderer_combo = Gtk.CellRendererCombo() renderer_combo.set_property('editable', editable) if model: renderer_combo.set_property('model', model) if function: renderer_combo.connect("edited", function) renderer_combo.set_property("text-column", 0) renderer_combo.set_property("has-entry", False) column = Gtk.TreeViewColumn(title, renderer_combo, text=assign) tree_view.append_column(column)
<SYSTEM_TASK:> Returns True if user agrees, False otherwise <END_TASK> <USER_TASK:> Description: def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options): """Returns True if user agrees, False otherwise"""
return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message)
<SYSTEM_TASK:> Ask user for written input with prompt <END_TASK> <USER_TASK:> Description: def ask_for_input_with_prompt(cls, ui, prompt='', **options): """Ask user for written input with prompt"""
return cls.get_appropriate_helper(ui).ask_for_input_with_prompt(prompt=prompt, **options)
<SYSTEM_TASK:> Used by cli to add this as an argument to argparse parser. <END_TASK> <USER_TASK:> Description: def add_argument_to(self, parser): """Used by cli to add this as an argument to argparse parser. Args: parser: parser to add this argument to """
from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory if isinstance(self.kwargs.get('action', ''), list): # see documentation of DefaultIffUsedActionFactory to see why this is necessary if self.kwargs['action'][0] == 'default_iff_used': self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action( self.kwargs['action'][1]) # In cli 'preserved' is not supported. # It needs to be removed because it is unknown for argparse. self.kwargs.pop('preserved', None) try: parser.add_argument(*self.flags, **self.kwargs) except Exception as ex: problem = "Error while adding argument '{name}': {error}".\ format(name=self.name, error=repr(ex)) raise exceptions.ExecutionException(problem)
<SYSTEM_TASK:> Return list of instantiated subassistants. <END_TASK> <USER_TASK:> Description: def get_subassistants(self): """Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants """
if not hasattr(self, '_subassistants'): self._subassistants = [] # we want to know, if type(self) defines 'get_subassistant_classes', # we don't want to inherit it from superclass (would cause recursion) if 'get_subassistant_classes' in vars(type(self)): for a in self.get_subassistant_classes(): self._subassistants.append(a()) return self._subassistants
<SYSTEM_TASK:> Returns a tree-like structure representing the assistant hierarchy going down <END_TASK> <USER_TASK:> Description: def get_subassistant_tree(self): """Returns a tree-like structure representing the assistant hierarchy going down from this assistant to leaf assistants. For example: [(<This Assistant>, [(<Subassistant 1>, [...]), (<Subassistant 2>, [...])] )] Returns: a tree-like structure (see above) representing assistant hierarchy going down from this assistant to leaf assistants """
if '_tree' not in dir(self): subassistant_tree = [] subassistants = self.get_subassistants() for subassistant in subassistants: subassistant_tree.append(subassistant.get_subassistant_tree()) self._tree = (self, subassistant_tree) return self._tree
<SYSTEM_TASK:> Returns True if this assistant was run as last in path, False otherwise. <END_TASK> <USER_TASK:> Description: def is_run_as_leaf(self, **kwargs): """Returns True if this assistant was run as last in path, False otherwise."""
# find the last subassistant_N i = 0 while i < len(kwargs): # len(kwargs) is maximum of subassistant_N keys if settings.SUBASSISTANT_N_STRING.format(i) in kwargs: leaf_name = kwargs[settings.SUBASSISTANT_N_STRING.format(i)] i += 1 return self.name == leaf_name
<SYSTEM_TASK:> Loads yaml files from all given directories. <END_TASK> <USER_TASK:> Description: def load_all_yamls(cls, directories): """Loads yaml files from all given directories. Args: directories: list of directories to search Returns: dict of {fullpath: loaded_yaml_structure} """
yaml_files = [] loaded_yamls = {} for d in directories: if d.startswith('/home') and not os.path.exists(d): os.makedirs(d) for dirname, subdirs, files in os.walk(d): yaml_files.extend(map(lambda x: os.path.join(dirname, x), filter(lambda x: x.endswith('.yaml'), files))) for f in yaml_files: loaded_yamls[f] = cls.load_yaml_by_path(f) return loaded_yamls
<SYSTEM_TASK:> Load a yaml file with path that is relative to one of given directories. <END_TASK> <USER_TASK:> Description: def load_yaml_by_relpath(cls, directories, rel_path, log_debug=False): """Load a yaml file with path that is relative to one of given directories. Args: directories: list of directories to search name: relative path of the yaml file to load log_debug: log all messages as debug Returns: tuple (fullpath, loaded yaml structure) or None if not found """
for d in directories: if d.startswith(os.path.expanduser('~')) and not os.path.exists(d): os.makedirs(d) possible_path = os.path.join(d, rel_path) if os.path.exists(possible_path): loaded = cls.load_yaml_by_path(possible_path, log_debug=log_debug) if loaded is not None: return (possible_path, cls.load_yaml_by_path(possible_path)) return None
<SYSTEM_TASK:> Load a yaml file that is at given path, <END_TASK> <USER_TASK:> Description: def load_yaml_by_path(cls, path, log_debug=False): """Load a yaml file that is at given path, if the path is not a string, it is assumed it's a file-like object"""
try: if isinstance(path, six.string_types): return yaml.load(open(path, 'r'), Loader=Loader) or {} else: return yaml.load(path, Loader=Loader) or {} except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: log_level = logging.DEBUG if log_debug else logging.WARNING logger.log(log_level, 'Yaml error in {path} (line {ln}, column {col}): {err}'. format(path=path, ln=e.problem_mark.line, col=e.problem_mark.column, err=e.problem)) return None
<SYSTEM_TASK:> Load all configuration from file <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: if len(line) == 2: key, value = line self.config_dict[key] = value else: self.config_dict = dict() self.logger.warning("Malformed configuration file {0}, ignoring it.". format(self.config_file)) return except (OSError, IOError) as e: self.logger.warning("Could not load configuration file: {0}".\ format(utils.exc_as_decoded_string(e)))
<SYSTEM_TASK:> Save all configuration into file <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 not make directory for configuration file: {0}". format(utils.exc_as_decoded_string(e))) return try: with open(self.config_file, 'w') as file: csvwriter = csv.writer(file, delimiter='=', escapechar='\\', lineterminator='\n', quoting=csv.QUOTE_NONE) for key, value in self.config_dict.items(): csvwriter.writerow([key, value]) self.config_changed = False except (OSError, IOError) as e: self.logger.warning("Could not save configuration file: {0}".\ format(utils.exc_as_decoded_string(e)))
<SYSTEM_TASK:> Set configuration value with given name. <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: self.config_changed = True self.config_dict[name] = value
<SYSTEM_TASK:> The function is used for setting tooltip on menus and submenus <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:> Hides this window and opens path window. <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:> Function serves for getting full assistant path and <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 self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self._open_path_window()
<SYSTEM_TASK:> Function return current assistant <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:> Function is used for case that assistant does not have any <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:> Function is used for showing Popup menu <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:> Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded <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 it first time a publicly callable method is used. """
@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 inner
<SYSTEM_TASK:> Returns default path to icon of this assistant. <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 in [png, svg]: 1) Take the path of this assistant and strip it of load path (=> "crt/python/django.yaml") 2) Substitute its extension for <image format> (=> "crt/python/django.<image format>") 3) Prepend self.load_path + 'icons' (=> "/foo/icons/crt/python/django.<image format>") 4) If file from 3) exists, return it Return empty string if no icon found. """
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) if os.path.exists(icon_fullpath): return icon_fullpath return ''
<SYSTEM_TASK:> Returns all dependencies of this assistant with regards to specified kwargs. <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, this method returns list of mappings of dependency types to actual dependencies (keeps order, types can repeat), e.g. Example: [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam']}, ...] If expand_only == True, this method returns a structure that can be used as "dependencies" section and has all the "use: foo" commands expanded (but conditions are left untouched and variables are not substituted). """
# 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_to_use(kwargs) deps = [] for sect in sections: if expand_only: deps.extend(lang.expand_dependencies_section(sect, kwargs)) else: deps.extend(lang.dependencies_section(sect, kwargs, runner=self)) return deps
<SYSTEM_TASK:> Try to detect a package manager used in a current Gentoo system. <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 return GentooPackageManager.PALUDIS except ImportError: # TODO Environment tells that paludis must be used, but # it seems latter was build w/o USE=python... # Need to report an error!!?? cls._debug_doesnt_work('can\'t import paludis', name='PaludisPackageManager') return None elif pm == 'portage': # Fallback to default: portage pass else: # ATTENTION Some unknown package manager?! Which one? return None # Try to import portage module try: import portage return GentooPackageManager.PORTAGE except ImportError: cls._debug_doesnt_work('can\'t import portage', name='EmergePackageManager') return None
<SYSTEM_TASK:> Returns True if this package manager is usable, False otherwise. <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:> Choose proper package manager and return it. <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: mgrs_nice = ', '.join([mgr.__name__ for mgr in mgrs]) err = 'No working package manager for "{dep_t}" in: {mgrs}'.format(dep_t=dep_t, mgrs=mgrs_nice) raise exceptions.NoPackageManagerOperationalException(err)
<SYSTEM_TASK:> Return True if user wants to install packages, False otherwise <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:> Checks if assistant needs refresh. <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: - stored source file is different than given source file - stored assistant ctime is lower than current source file ctime - stored list of subassistants is different than given list of subassistants - stored ctime of any of the snippets that this assistant uses to compose args is lower than current ctime of that snippet Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts) """
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_name, snip_ctime in cached_ass['snippets'].items(): if self._get_snippet_ctime(snip_name) > snip_ctime: return True return False
<SYSTEM_TASK:> Completely refreshes cached assistant from file. <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 format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts) """
# 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'] cached_ass['ctime'] = os.path.getctime(file_ass['source']) cached_ass['attrs'] = {} cached_ass['snippets'] = {} # only cache these attributes if they're actually found in assistant # we do this to specify the default values for them just in one place # which is currently YamlAssistant.parsed_yaml property setter for a in ['fullname', 'description', 'icon_path']: if a in attrs: cached_ass['attrs'][a] = attrs.get(a) # args have different processing, we can't just take them from assistant if 'args' in attrs: cached_ass['attrs']['args'] = {} for argname, argparams in attrs.get('args', {}).items(): if 'use' in argparams or 'snippet' in argparams: snippet_name = argparams.pop('use', None) or argparams.pop('snippet') snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(snippet_name) cached_ass['attrs']['args'][argname] = snippet.get_arg_by_name(argname) cached_ass['attrs']['args'][argname].update(argparams) cached_ass['snippets'][snippet.name] = self._get_snippet_ctime(snippet.name) else: cached_ass['attrs']['args'][argname] = argparams
<SYSTEM_TASK:> Returns a completely new cache hierarchy for given assistant file. <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 hierarchy to create cache hierarchy for (for format see what refresh_role accepts) Returns: the newly created cache hierarchy """
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'].items(): ret_struct['subhierarchy'][name] = self._new_ass_hierarchy(subhierarchy) return ret_struct
<SYSTEM_TASK:> Returns tuple that consists of control variable name and iterable that is result <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 expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')]) """
# 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 expand {t} to two control variables.'. format(t=type(eval_expression))) else: iterval = list(eval_expression.items()) elif isinstance(eval_expression, six.string_types): if iter_type == 'word_in': iterval = eval_expression.split() else: iterval = eval_expression else: iterval = eval_expression return control_vars, iterval
<SYSTEM_TASK:> Adds symbol 'id' to symbol_table if it does not exist already, <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 symbol class """
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:> Advance to next token, optionally check that current token is 'id' <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:> A decorator - adds the decorated method to symbol 'symbol_name' <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:> If given relative path exists in one of DevAssistant load paths, <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.g. "assitants/crt/test.yaml" Returns: absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml or None if file is not found """
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:> Function that behaves exactly like Python's atexit, but runs atexit functions <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:> Strip the prefix from the string <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 prefix.startswith('^'): prefix = '^({s})'.format(s=prefix) return _strip(string, prefix)
<SYSTEM_TASK:> Strip the suffix from the string. <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 suffix.endswith('$'): suffix = '({s})$'.format(s=suffix) return _strip(string, suffix)
<SYSTEM_TASK:> Return complement of pattern in string <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:> Historically, we had "devassistant" binary, but we chose to go with <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", but we recommend using "da". """
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:> Function returns a full dir name <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:> Function opens the run Window who executes the <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]: preserve_key = arg_dict['arg'].kwargs['preserved'] # preserve entry text (string value) if 'entry' in arg_dict: if self.arg_is_selected(arg_dict): config_manager.set_config_value(preserve_key, arg_dict['entry'].get_text()) # preserve if checkbox is ticked (boolean value) else: config_manager.set_config_value(preserve_key, self.arg_is_selected(arg_dict)) # save configuration into file config_manager.save_configuration_file() # get project directory and name project_dir = self.dir_name.get_text() full_name = self.get_full_dir_name() # check whether project directory and name is properly set if not deps_only and self.current_main_assistant.name == 'crt': if project_dir == "": return self.gui_helper.execute_dialog("Specify directory for project") else: # check whether directory is existing if not os.path.isdir(project_dir): response = self.gui_helper.create_question_dialog( "Directory {0} does not exists".format(project_dir), "Do you want to create them?" ) if response == Gtk.ResponseType.NO: # User do not want to create a directory return else: # Create directory try: os.makedirs(project_dir) except OSError as os_err: return self.gui_helper.execute_dialog("{0}".format(os_err)) elif os.path.isdir(full_name): return self.check_for_directory(full_name) if not self._build_flags(): return if not deps_only and self.current_main_assistant.name == 'crt': self.kwargs['name'] = full_name self.kwargs['__ui__'] = 'gui_gtk+' self.data['kwargs'] = self.kwargs self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.current_main_assistant self.parent.run_window.open_window(widget, self.data) self.path_window.hide()
<SYSTEM_TASK:> Function builds kwargs variable for run_window <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'])) return False # Check for active CheckButtons for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'entry' in arg_dict: self.kwargs[arg_name] = arg_dict['entry'].get_text() else: if arg_dict['arg'].get_gui_hint('type') == 'const': self.kwargs[arg_name] = arg_dict['arg'].kwargs['const'] else: self.kwargs[arg_name] = True # Check for non active CheckButtons but with defaults flag for arg_dict in [x for x in self.args.values() if not self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'default' in arg_dict['arg'].kwargs: self.kwargs[arg_name] = arg_dict['arg'].get_gui_hint('default') elif arg_name in self.kwargs: del self.kwargs[arg_name] return True
<SYSTEM_TASK:> Function manipulates with entries and buttons. <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:> Function deactivate options in case of deps_only and opposite <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:> Function opens the file chooser dialog for settings project dir <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:> Function sets the directory to entry <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:> Function controls whether run button is enabled <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:> Function is used for controlling <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 configuration manager """
config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) self.update_full_label()
<SYSTEM_TASK:> Checks whether loaded yaml is well-formed according to syntax defined for <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 meaningful message) when the loaded Yaml is not well formed """
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) self._check_description(self.sourcefile) self._check_section_names(self.sourcefile) self._check_project_type(self.sourcefile) self._check_args(self.sourcefile) self._check_files(self.sourcefile) self._check_dependencies(self.sourcefile) self._check_run(self.sourcefile)
<SYSTEM_TASK:> Asserts that given structure is of any of given types. <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 to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list/tuple of types that are allowed for given struct path: list with a source file as a first element and previous names (as in name argument to this method) as other elements extra_info: extra information to print if error is found (e.g. hint how to fix this) Raises: YamlTypeError: if given struct is not of any given type; error message contains source file and a "path" (e.g. args -> somearg -> flags) specifying where the problem is """
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): err = [] if path: err.append(self._format_error_path(path + [name])) err.append(' Expected {w} value for "{n}", got value of type {a}: "{v}"'. format(w=wanted_yaml_typenames, n=name, a=actual_yaml_typename, v=struct)) if extra_info: err.append('Tip: ' + extra_info) raise exceptions.YamlTypeError('\n'.join(err))
<SYSTEM_TASK:> Generates argument parser for given assistant tree and actions. <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 devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (devassistant.actions.Action subclasses) to their subaction dicts Returns: instance of devassistant_argparse.ArgumentParser (subclass of argparse.ArgumentParser) """
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) # add any arguments of the top assistant for arg in cur_as.args: arg.add_argument_to(parser) if cur_subas or actions: # then add the subassistants as arguments subparsers = cls._add_subparsers_required(parser, dest=settings.SUBASSISTANT_N_STRING.format('0')) for subas in sorted(cur_subas, key=lambda x: x[0].name): for alias in [subas[0].name] + getattr(subas[0], 'aliases', []): cls.add_subassistants_to(subparsers, subas, level=1, alias=alias) for action, subactions in sorted(actions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, action, subactions, level=1) return parser
<SYSTEM_TASK:> Adds assistant from given part of assistant tree and all its subassistants to <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 given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of assistant tree (see generate_argument_parser doc) level: level of subassistants that given assistant is at """
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(assistant_tuple[1]) > 0: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=cls.subparsers_desc) for subas_tuple in sorted(assistant_tuple[1], key=lambda x: x[0].name): cls.add_subassistants_to(subparsers, subas_tuple, level + 1) elif level == 1: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=devassistant_argparse.ArgumentParser.no_assistants_msg)
<SYSTEM_TASK:> Adds given action to given parser <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 action: devassistant.actions.Action subclass subactions: dict with subactions - {SubA: {SubB: {}}, SubC: {}} """
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, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subactions_str, description=cls.subactions_desc) for subact, subsubacts in sorted(subactions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, subact, subsubacts, level + 1)
<SYSTEM_TASK:> Format a log entry according to its level and context <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:> Functions switches the cursor to cursor type <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:> Function opens the run window <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: self.debug_btn.set_label('Debug logs') else: self.debug_btn.set_label('Info logs') self.store.clear() self.debug_logs = dict() self.debug_logs['logs'] = list() self.thread = threading.Thread(target=self.dev_assistant_start) # We need only project name for github project_name = self.parent.path_window.get_data()[1] if self.kwargs.get('github'): self.link = self.gui_helper.create_link_button( "Link to project on Github", "http://www.github.com/{0}/{1}".format(self.kwargs.get('github'), project_name)) self.link.set_border_width(6) self.link.set_sensitive(False) self.info_box.pack_start(self.link, False, False, 12) self.run_list_view.connect('size-allocate', self.list_view_changed) # We need to be in /home directory before each project creations os.chdir(os.path.expanduser('~')) self.run_window.show_all() self.disable_buttons() self.thread.start()
<SYSTEM_TASK:> Function removes link button from Run Window <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:> Event cancels the project creation <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 response == Gtk.ResponseType.YES: if self.thread.isAlive(): self.info_label.set_label('<span color="#FFA500">Cancelling...</span>') self.dev_assistant_runner.stop() self.project_canceled = True else: self.info_label.set_label('<span color="#008000">Done</span>') self.allow_close_window() dlg.destroy() return True else: return False
<SYSTEM_TASK:> Function shows last rows. <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:> Function allows buttons <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:> Event in case that debug button is pressed. <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:> Function copies logs to clipboard. <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', ''): if not record.event_type.startswith("dep_"): _clipboard_text.append(format_entry(record)) else: _clipboard_text.append(format_entry(record)) self.gui_helper.create_clipboard(_clipboard_text)
<SYSTEM_TASK:> Event for back button. <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:> Button switches to Dev Assistant GUI main window <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:> Function opens the firefox window with relevant link <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:> Create an authorization for a GitHub user using two-factor <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 counterpart, this method does not traverse the available authentications as they are not visible until the user logs in. Please note: cls._user's attributes are not accessible until the authorization is created due to the way (py)github works. """
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 = cls._user.create_authorization(scopes=['repo', 'user', 'admin:public_key'], note="DevAssistant", onetime_password=onetime_pw) cls._user = cls._gh_module.Github(login_or_token=auth.token).get_user() logger.debug('Two-factor authorization for user "{0}" created'.format(cls._user.login)) cls._github_store_authorization(cls._user, auth) logger.debug('Two-factor authorization token stored') except cls._gh_exceptions.GithubException as e: logger.warning('Creating two-factor authorization failed: {0}'.format(e))
<SYSTEM_TASK:> Create a GitHub authorization for the given user in case they don't <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'], note="DevAssistant") cls._github_store_authorization(cls._user, auth) except cls._gh_exceptions.GithubException as e: logger.warning('Creating authorization failed: {0}'.format(e))
<SYSTEM_TASK:> Store an authorization token for the given GitHub user in the git <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:> Starts ssh-agent and returns the environment variables related to it <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: env[parts[0]] = parts[1] return env
<SYSTEM_TASK:> Creates a local ssh key, if it doesn't exist already, and uploads it to Github. <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_path): ClHelper.run_command('ssh-keygen -t rsa -f {pkey_path}\ -N \"\" -C \"DevAssistant\"'. format(pkey_path=pkey_path)) try: ClHelper.run_command('ssh-add {pkey_path}'.format(pkey_path=pkey_path)) except exceptions.ClException: # ssh agent might not be running env = cls._start_ssh_agent() ClHelper.run_command('ssh-add {pkey_path}'.format(pkey_path=pkey_path), env=env) public_key = ClHelper.run_command('cat {pkey_path}.pub'.format(pkey_path=pkey_path)) cls._user.create_key("DevAssistant", public_key) except exceptions.ClException as e: msg = 'Couldn\'t create a new ssh key: {0}'.format(e) raise exceptions.CommandException(msg)
<SYSTEM_TASK:> Returns True if any key on Github matches a local key, else False. <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 PyGithub 1.23.0, remote key is an object, not string rkval = rk if isinstance(rk, six.string_types) else rk.value # don't use "==" because we have comments etc added in public_key if rkval in local_key: found = True break return found
<SYSTEM_TASK:> Fills self._assistants with loaded YamlAssistant instances of requested roles. <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/created if needed). If cache is unusable, it falls back to loading all assistants. Args: roles: list of required assistant roles """
# 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.join(d, tl) for d in cls.assistants_dirs] file_hierarchy = cls.get_assistants_file_hierarchy(dirs) # load all if we're not using cache or if we fail to load it load_all = not settings.USE_CACHE if settings.USE_CACHE: try: cch = cache.Cache() cch.refresh_role(tl, file_hierarchy) _assistants[tl] = cls.get_assistants_from_cache_hierarchy(cch.cache[tl], superas_dict[tl], role=tl) except BaseException as e: logger.debug('Failed to use DevAssistant cachefile {0}: {1}'.format( settings.CACHE_FILE, e)) load_all = True if load_all: _assistants[tl] = cls.get_assistants_from_file_hierarchy(file_hierarchy, superas_dict[tl], role=tl) return _assistants
<SYSTEM_TASK:> Accepts file_hierarch as returned by cls.get_assistant_file_hierarchy and returns <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.get_assistant_file_hierarchy and returns instances of YamlAssistant for loaded files Args: file_hierarchy: structure as described in cls.get_assistants_file_hierarchy role: role of all assistants in this hierarchy (we could find this out dynamically but it's not worth the pain) Returns: list of top level assistants from given hierarchy; these assistants contain references to instances of their subassistants (and their subassistants, ...) """
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 logger.warning(warn_msg.format(source=attrs['source'])) continue try: ass = cls.assistant_from_yaml(attrs['source'], loaded_yaml, superassistant, role=role) except exceptions.YamlError as e: logger.warning(e) continue ass._subassistants = cls.get_assistants_from_file_hierarchy(attrs['subhierarchy'], ass, role=role) result.append(ass) return result
<SYSTEM_TASK:> Constructs instance of YamlAssistant loaded from given structure y, loaded <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 from given structure y, loaded from source file source. Args: source: path to assistant source file y: loaded yaml structure superassistant: superassistant of this assistant Returns: YamlAssistant instance constructed from y with source file source Raises: YamlError: if the assistant is malformed """
# 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, y) assistant = yaml_assistant.YamlAssistant(name, y, source, superassistant, fully_loaded=fully_loaded, role=role) return assistant
<SYSTEM_TASK:> legend needs to be a list, tuple or None <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:> Sets legend position. Default is 'r'. <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 - At the bottom of the chart, legend entries in a vertical column. t - At the top of the chart, legend entries in a horizontal row. tv - At the top of the chart, legend entries in a vertical column. r - To the right of the chart, legend entries in a vertical column. l - To the left of the chart, legend entries in a vertical column. """
if legend_position: self.legend_position = quote(legend_position) else: self.legend_position = None
<SYSTEM_TASK:> Return a 2-tuple giving the minimum and maximum x-axis <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']) return (lower, upper) except ValueError: return None
<SYSTEM_TASK:> 5.4.3 Datatype Constraints <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 per XPath Functions 3.1 section 19 Casting[xpath-functions]." """
# 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:> 5.4.5 XML Schema Numberic Facet Constraints <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 from xsd:decimal fail. """
return len(str(abs(int(n.value)))) + fraction_digits(n) if is_numeric(n) and n.value is not None else None
<SYSTEM_TASK:> 5.4.5 XML Schema Numeric Facet Constraints <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 number of digits to the right of the decimal place in the XML Schema canonical form[xmlschema-2] of the value of n, ignoring trailing zeros. """
# 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] == '0' \ else len(str(int(str(n.value).split('.')[1][::-1])))
<SYSTEM_TASK:> Comment any lines that start with import in the .pth file <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.append(line) try: os.unlink('%s.tmp' % vext_pth) except: pass with open('%s.tmp' % vext_pth, mode='w+') as f: f.writelines(_lines) try: os.unlink('%s~' % vext_pth) except: pass os.rename(vext_pth, '%s~' % vext_pth) os.rename('%s.tmp' % vext_pth, vext_pth) except IOError as e: if e.errno == 2: # file didn't exist == disabled return
<SYSTEM_TASK:> Attempt to import everything in the 'test-imports' section of specified <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), '*' matches all. :return: True if test_imports was successful from all files """
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 file." % fn, file=sys.stderr) if unknown_specs: return False check_passed = True for fn in [join(vext.gatekeeper.spec_dir(), fn) for fn in vext_files]: f = open_spec(open(fn)) modules = f.get('test_import', []) for success, module in vext.gatekeeper.test_imports(modules): if not success: check_passed = False line = "import %s: %s" % (module, '[success]' if success else '[failed]') print(line) print('') return check_passed
<SYSTEM_TASK:> Convert path pointing subdirectory of virtualenv site-packages <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. >>> fix_path('C:\\some-venv\\Lib\\site-packages\\gnome') 'C:\\Python27\\lib\\site-packages\\gnome' """
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:> Fixup paths added in .pth file that point to the virtualenv <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, which might manipulate the PATH or sys.path :return: """
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(set(original_paths)) # rebuild PATH env var fixed_paths = [] for path in current_paths: if path in changed_paths: fixed_paths.append(env_t(fix_path(path))) else: fixed_paths.append(env_t(path)) os.environ['PATH'] = os.pathsep.join(fixed_paths) # Fix added_dirs if added_dirs != original_dirs: for path in set(added_dirs.difference(original_dirs)): fixed_path = fix_path(path) if fixed_path != path: print("Fix %s >> %s" % (path, fixed_path)) added_dirs.remove(path) added_dirs.add(fixed_path) i = sys.path.index(path) # not efficient... but shouldn't happen often sys.path[i] = fixed_path if env_t(fixed_path) not in os.environ['PATH']: os.environ['PATH'].append(os.pathsep + env_t(fixed_path))
<SYSTEM_TASK:> Wrapper for site.addpackage <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 known_dirs set :param sys_sitedir: system site-packages directory :param pthfile: path file to add :param known_dirs: set of known directories """
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()) continue else: p_rel = join(sys_sitedir, line) p_abs = abspath(line) if isdir(p_rel): os.environ['PATH'] += env_t(os.pathsep + p_rel) sys.path.append(p_rel) added_dirs.add(p_rel) elif isdir(p_abs): os.environ['PATH'] += env_t(os.pathsep + p_abs) sys.path.append(p_abs) added_dirs.add(p_abs) if isfile(pthfile): site.addpackage(sys_sitedir, pthfile, known_dirs) else: logging.debug("pth file '%s' not found")
<SYSTEM_TASK:> Add any new modules that are directories to the PATH <END_TASK> <USER_TASK:> Description: def init_path(): """ Add any new modules that are directories to the PATH """
sitedirs = getsyssitepackages() for sitedir in sitedirs: env_path = os.environ['PATH'].split(os.pathsep) for module in allowed_modules: p = join(sitedir, module) if isdir(p) and not p in env_path: os.environ['PATH'] += env_t(os.pathsep + p)
<SYSTEM_TASK:> If in a virtualenv then load spec files to decide which <END_TASK> <USER_TASK:> Description: def install_importer(): """ If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """
logging.debug('install_importer') if not in_venv(): logging.debug('No virtualenv active py:[%s]', sys.executable) return False if disable_vext: logging.debug('Vext disabled by environment variable') return False if GatekeeperFinder.PATH_TRIGGER not in sys.path: try: load_specs() sys.path.append(GatekeeperFinder.PATH_TRIGGER) sys.path_hooks.append(GatekeeperFinder) except Exception as e: """ Dont kill other programmes because of a vext error """ logger.info(str(e)) if logger.getEffectiveLevel() == logging.DEBUG: raise logging.debug("importer installed") return True
<SYSTEM_TASK:> Only lets modules in allowed_modules be loaded, others <END_TASK> <USER_TASK:> Description: def load_module(self, name): """ Only lets modules in allowed_modules be loaded, others will get an ImportError """
# Get the name relative to SITEDIR .. filepath = self.module_info[1] fullname = splitext( \ relpath(filepath, self.sitedir) \ )[0].replace(os.sep, '.') modulename = filename_to_module(fullname) if modulename not in allowed_modules: if remember_blocks: blocked_imports.add(fullname) if log_blocks: raise ImportError("Vext blocked import of '%s'" % modulename) else: # Standard error message raise ImportError("No module named %s" % modulename) if name not in sys.modules: try: logger.debug("load_module %s %s", name, self.module_info) module = imp.load_module(name, *self.module_info) except Exception as e: logger.debug(e) raise sys.modules[fullname] = module return sys.modules[fullname]
<SYSTEM_TASK:> Evaluate focus node `focus` in graph `g` against shape `shape` in ShEx schema `schema` <END_TASK> <USER_TASK:> Description: def evaluate(g: Graph, schema: Union[str, ShExJ.Schema], focus: Optional[Union[str, URIRef, IRIREF]], start: Optional[Union[str, URIRef, IRIREF, START, START_TYPE]]=None, debug_trace: bool = False) -> Tuple[bool, Optional[str]]: """ Evaluate focus node `focus` in graph `g` against shape `shape` in ShEx schema `schema` :param g: Graph containing RDF :param schema: ShEx Schema -- if str, it will be parsed :param focus: focus node in g. If not specified, all URI subjects in G will be evaluated. :param start: Starting shape. If omitted, the Schema start shape is used :param debug_trace: Turn on debug tracing :return: None if success or failure reason if failure """
if isinstance(schema, str): schema = SchemaLoader().loads(schema) if schema is None: return False, "Error parsing schema" if not isinstance(focus, URIRef): focus = URIRef(str(focus)) if start is None: start = str(schema.start) if schema.start else None if start is None: return False, "No starting shape" if not isinstance(start, IRIREF) and start is not START and start is not START_TYPE: start = IRIREF(str(start)) cntxt = Context(g, schema) cntxt.debug_context.debug = debug_trace map_ = FixedShapeMap() map_.add(ShapeAssociation(focus, start)) test_result, reasons = isValid(cntxt, map_) return test_result, '\n'.join(reasons)
<SYSTEM_TASK:> Check that imports in 'test_imports' succeed <END_TASK> <USER_TASK:> Description: def check_sysdeps(vext_files): """ Check that imports in 'test_imports' succeed otherwise display message in 'install_hints' """
@run_in_syspy def run(*modules): result = {} for m in modules: if m: try: __import__(m) result[m] = True except ImportError: result[m] = False return result success = True for vext_file in vext_files: with open(vext_file) as f: vext = open_spec(f) install_hint = " ".join(vext.get('install_hints', ['System dependencies not found'])) modules = vext.get('test_import', '') logger.debug("%s test imports of: %s", vext_file, modules) result = run(*modules) if logging.getLogger().getEffectiveLevel() == logging.DEBUG: for k, v in result.items(): logger.debug("%s: %s", k, v) if not all(result.values()): success = False print(install_hint) return success
<SYSTEM_TASK:> Return the turtle representation of subj as a collection <END_TASK> <USER_TASK:> Description: def format_collection(g: Graph, subj: Union[URIRef, BNode], max_entries: int = None, nentries: int = 0) -> Optional[List[str]]: """ Return the turtle representation of subj as a collection :param g: Graph containing subj :param subj: subject of list :param max_entries: maximum number of list elements to return, None means all :param nentries: used for recursion :return: List of formatted entries if subj heads a well formed collection else None """
if subj == RDF.nil: return [')'] if max_entries is not None and nentries >= max_entries: return [' ...', ')'] cadr = cdr = None for p, o in g.predicate_objects(subj): if p == RDF.first and cadr is None: cadr = o elif p == RDF.rest and cdr is None: cdr = o else: return None # technically this can't happen but it doesn't hurt to address it if cadr == RDF.nil and cdr is None: return [] elif cadr is not None and cdr is not None: return [(' ' if nentries else '(') + cadr.n3(g.namespace_manager)] + format_collection(g, cdr, max_entries, nentries+1) else: return None
<SYSTEM_TASK:> setuptools 12.2 can trigger a really nasty bug <END_TASK> <USER_TASK:> Description: def upgrade_setuptools(): """ setuptools 12.2 can trigger a really nasty bug that eats all memory, so upgrade it to 18.8, which is known to be good. """
# Note - I tried including the higher version in # setup_requires, but was still able to trigger # the bug. - stu.axon global MIN_SETUPTOOLS r = None try: r = pkg_resources.require(["setuptools"])[0] except DistributionNotFound: # ok, setuptools will be installed later return if StrictVersion(r.version) >= StrictVersion(MIN_SETUPTOOLS): return else: print("Upgrading setuptools...") subprocess.call("%s -mpip install 'setuptools>=%s'" % (sys.executable, MIN_SETUPTOOLS), shell=True)
<SYSTEM_TASK:> Need to find any pre-existing vext contained in dependent packages <END_TASK> <USER_TASK:> Description: def run(self): """ Need to find any pre-existing vext contained in dependent packages and install them example: you create a setup.py with install_requires["vext.gi"]: - vext.gi gets installed using bdist_egg - vext itself is now called with bdist_egg and we end up here Vext now needs to find and install .vext files in vext.gi [or any other files that depend on vext] :return: """
logger.debug("vext InstallLib [started]") # Find packages that depend on vext and check for .vext files... logger.debug("find_vext_files") vext_files = self.find_vext_files() logger.debug("manually_install_vext: ", vext_files) self.manually_install_vext(vext_files) logger.debug("enable vext") self.enable_vext() logger.debug("install_lib.run") install_lib.run(self) logger.debug("vext InstallLib [finished]")
<SYSTEM_TASK:> Iter to a list of servers and instantiate Protocol class. <END_TASK> <USER_TASK:> Description: def set_servers(self, servers): """ Iter to a list of servers and instantiate Protocol class. :param servers: A list of servers :type servers: list :return: Returns nothing :rtype: None """
if isinstance(servers, six.string_types): servers = [servers] assert servers, "No memcached servers supplied" self._servers = [Protocol( server=server, username=self.username, password=self.password, compression=self.compression, socket_timeout=self.socket_timeout, pickle_protocol=self.pickle_protocol, pickler=self.pickler, unpickler=self.unpickler, ) for server in servers]
<SYSTEM_TASK:> Decorator to run a function in the system python <END_TASK> <USER_TASK:> Description: def run_in_syspy(f): """ Decorator to run a function in the system python :param f: :return: """
fname = f.__name__ code_lines = inspect.getsource(f).splitlines() code = dedent("\n".join(code_lines[1:])) # strip this decorator # add call to the function and print it's result code += dedent("""\n import sys args = sys.argv[1:] result = {fname}(*args) print("%r" % result) """).format(fname=fname) env = os.environ python = findsyspy() logger.debug("Create function for system python\n%s" % code) def call_f(*args): cmd = [python, '-c', code] + list(args) output = subprocess.check_output(cmd, env=env).decode('utf-8') result = ast.literal_eval(output) return result return call_f
<SYSTEM_TASK:> Set a value for a key on server if its CAS value matches cas. <END_TASK> <USER_TASK:> Description: def cas(self, key, value, cas, time=0, compress_level=-1): """ Set a value for a key on server if its CAS value matches cas. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param cas: The CAS value previously obtained from a call to get*. :type cas: int :param time: Time in seconds that your key will expire. :type time: int :param compress_level: How much to compress. 0 = no compression, 1 = fastest, 9 = slowest but best, -1 = default compression level. :type compress_level: int :return: True in case of success and False in case of failure :rtype: bool """
server = self._get_server(key) return server.cas(key, value, cas, time, compress_level)
<SYSTEM_TASK:> Evaluate cardinality expression <END_TASK> <USER_TASK:> Description: def matchesCardinality(cntxt: Context, T: RDFGraph, expr: Union[ShExJ.tripleExpr, ShExJ.tripleExprLabel], c: DebugContext) -> bool: """ Evaluate cardinality expression expr has a cardinality of min and/or max not equal to 1, where a max of -1 is treated as unbounded, and T can be partitioned into k subsets T1, T2,…Tk such that min ≤ k ≤ max and for each Tn, matches(Tn, expr, m) by the remaining rules in this list. """
# TODO: Cardinality defaults into spec min_ = expr.min if expr.min is not None else 1 max_ = expr.max if expr.max is not None else 1 cardinality_text = f"{{{min_},{'*' if max_ == -1 else max_}}}" if c.debug and (min_ != 0 or len(T) != 0): print(f"{cardinality_text} matching {len(T)} triples") if min_ == 0 and len(T) == 0: return True if isinstance(expr, ShExJ.TripleConstraint): if len(T) < min_: if len(T) > 0: _fail_triples(cntxt, T) cntxt.fail_reason = f" {len(T)} triples less than {cardinality_text}" else: cntxt.fail_reason = f" No matching triples found for predicate {cntxt.n3_mapper.n3(expr.predicate)}" return False elif 0 <= max_ < len(T): _fail_triples(cntxt, T) cntxt.fail_reason = f" {len(T)} triples exceeds max {cardinality_text}" return False else: return all(matchesTripleConstraint(cntxt, t, expr) for t in T) else: for partition in _partitions(T, min_, max_): if all(matchesExpr(cntxt, part, expr) for part in partition): return True if min_ != 1 or max_ != 1: _fail_triples(cntxt, T) cntxt.fail_reason = f" {len(T)} triples cannot be partitioned into {cardinality_text} passing groups" return False
<SYSTEM_TASK:> Get a key from server. <END_TASK> <USER_TASK:> Description: def get(self, key, get_cas=False): """ Get a key from server. :param key: Key's name :type key: six.string_types :param get_cas: If true, return (value, cas), where cas is the new CAS value. :type get_cas: boolean :return: Returns a key data from server. :rtype: object """
for server in self.servers: value, cas = server.get(key) if value is not None: if get_cas: return value, cas else: return value if get_cas: return None, None