INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a completely new cache hierarchy for given assistant file.
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: ...
Returns and remembers ( during this DevAssistant invocation ) last ctime of given snippet.
def _get_snippet_ctime(self, snip_name): """Returns and remembers (during this DevAssistant invocation) last ctime of given snippet. Calling ctime costs lost of time and some snippets, like common_args, are used widely, so we don't want to call ctime bazillion times on them during one i...
Expands dependency section e. g. substitues use: foo for its contents but doesn t evaluate conditions nor substitue variables.
def expand_dependencies_section(section, kwargs): """Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue variables.""" deps = [] for dep in section: for dep_type, dep_list in dep.items(): if dep_type in ['call', 'use...
Returns name of loop control variable ( s ) iteration type ( in/ word_in ) and expression to iterate on.
def parse_for(control_line): """Returns name of loop control variable(s), iteration type (in/word_in) and expression to iterate on. For example: - given "for $i in $foo", returns (['i'], '$foo') - given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)') - given "for $k, $v in $foo", return...
Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop.
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'...
Returns section that should be used from given if/ else sections by evaluating given condition.
def get_section_from_condition(if_section, else_section, kwargs): """Returns section that should be used from given if/else sections by evaluating given condition. Args: if_section - section with if clause else_section - section that *may* be else clause (just next section after if_section,...
Returns 2 - tuple with names of catch control vars e. g. for catch $was_exc $exc it returns ( was_exc err ).
def get_catch_vars(catch): """Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc" it returns ('was_exc', 'err'). Args: catch: the whole catch line Returns: 2-tuple with names of catch control variables Raises: exceptions.YamlSyntaxError if the...
Assigns given result ( resp. logical result and result ) to a variable ( resp. to two variables ). log_res and res are already computed result of an exec/ input section. For example:
def assign_variable(variable, log_res, res, kwargs): """Assigns given result (resp. logical result and result) to a variable (resp. to two variables). log_res and res are already computed result of an exec/input section. For example: $foo~: $spam and $eggs $log_res, $foo~: $spam and $eggs $foo...
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
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.sy...
Advance to next token optionally check that current token is id
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()
A decorator - adds the decorated method to symbol symbol_name
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
Evaluates expression and returns it s value ( s )
def parse(self, expression): """ Evaluates 'expression' and returns it's value(s) """ if isinstance(expression, (list, dict)): return (True if expression else False, expression) if sys.version_info[0] > 2: self.next = self.tokenize(expression).__next__ ...
Returns set of all possible platforms
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...
If given relative path exists in one of DevAssistant load paths return its full path.
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 ...
Function that behaves exactly like Python s atexit but runs atexit functions in the order in which they were registered not reversed.
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: ...
Strip the prefix from the string
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...
Strip the suffix from the string.
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 type...
Return complement of pattern in string
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
Registers console logging handler to given logger.
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...
Runs the whole cli:
def run(cls): """Runs the whole cli: 1. Registers console logging handler 2. Creates argparser from all assistants and actions 3. Parses args and decides what to run 4. Runs a proper assistant or action """ sigint_handler.override() # set settings.USE_CAC...
Historically we had devassistant binary but we chose to go with shorter da. We still allow devassistant but we recommend using da.
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': ms...
Function returns a full dir name
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())
Function opens the run Window who executes the assistant project creation
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...
Function builds kwargs variable for run_window
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_t...
Function opens the Options dialog
def open_window(self, data=None): """ Function opens the Options dialog """ self.args = dict() if data is not None: self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self...
Function manipulates with entries and buttons.
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' ...
Function deactivate options in case of deps_only and opposite
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.s...
Function returns to Main Window
def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data)
Function opens the file chooser dialog for settings project dir
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)
Function adds options to a grid
def _add_table_row(self, arg, number, row): """ Function adds options to a grid """ self.args[arg.name] = dict() self.args[arg.name]['arg'] = arg check_box_title = arg.flags[number][2:].title() self.args[arg.name]['label'] = check_box_title align = self.gu...
Function sets the directory to entry
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)
Function controls whether run button is enabled
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()
Function is used for controlling label Full Directory project name and storing current project directory in configuration manager
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()) ...
Checks whether loaded yaml is well - formed according to syntax defined for version 0. 9. 0 and later.
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,...
Validate the argument section.
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...
Checks whether struct is a command dict ( e. g. it s a dict and has 1 key - value pair.
def _assert_command_dict(self, struct, name, path=None, extra_info=None): """Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair.""" self._assert_dict(struct, name, path, extra_info) if len(struct) != 1: err = [self._format_error_path(path + [name])] ...
Asserts that given structure is of any of given types.
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...
Returns all individual licenses in the input
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))
Returns True if given license field is correct Taken from rpmlint.
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...
Decorator that registers a command runner. Accepts either:
def register_command_runner(arg): """Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String prefix to register a command runner under (returning a decorator) """ if isinstance(arg, str): def inner(command_runner): command_runners.setdefau...
Version comparing returns 0 if are the same returns > 0 if first is bigger <0 if first is smaller excepts valid version
def compare(ver1, ver2): '''Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version''' if ver1 == ver2: return 0 ver1 = _cut(ver1) ver2 = _cut(ver2) # magic multiplier m = 1 # if the first one is shorter, repl...
Cuts the version to array excepts valid version
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) ...
Generates argument parser for given assistant tree and actions.
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 (deva...
Adds assistant from given part of assistant tree and all its subassistants to a given argument parser.
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 as...
Adds given action to given parser
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: {}}...
Format a log entry according to its level and context
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_...
Functions switches the cursor to cursor type
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)
Function inserts log messages to list_view
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(recor...
Function opens the run window
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_assist...
Function removes link button from Run Window
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
Event cancels the project creation
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?", ...
Function shows last rows.
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())
Function disables buttons
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: ...
Function allows buttons
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...
Thread executes devassistant API.
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] =...
Event in case that debug button is pressed.
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()
Function updates logs.
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')...
Function copies logs to clipboard.
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...
Event for back button. This occurs in case of devassistant fail.
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()
Button switches to Dev Assistant GUI main window
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)
Function opens the firefox window with relevant link
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) ...
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.
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. ...
Create a GitHub authorization for the given user in case they don t already have one.
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': ...
Store an authorization token for the given GitHub user in the git global config file.
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=Tr...
Starts ssh - agent and returns the environment variables related to it
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 '): cont...
Creates a local ssh key if it doesn t exist already and uploads it to Github.
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_SS...
Returns True if any key on Github matches a local key else False.
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 pk...
Does user authentication creates SSH keys if needed and injects _user attribute into class/ object bound to the decorated function. Don t call any other methods of this class manually this should be everything you need.
def github_authenticated(cls, func): """Does user authentication, creates SSH keys if needed and injects "_user" attribute into class/object bound to the decorated function. Don't call any other methods of this class manually, this should be everything you need. """ def inner(fun...
Returns list of assistants that are subassistants of given superassistants ( I love this docstring ).
def get_assistants(cls, superassistants): """Returns list of assistants that are subassistants of given superassistants (I love this docstring). Args: roles: list of names of roles, defaults to all roles Returns: list of YamlAssistant instances with specified rol...
Fills self. _assistants with loaded YamlAssistant instances of requested roles.
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 assi...
Accepts cache_hierarch as described in devassistant. cache and returns instances of YamlAssistant ( only with cached attributes ) for loaded files
def get_assistants_from_cache_hierarchy(cls, cache_hierarchy, superassistant, role=settings.DEFAULT_ASSISTANT_ROLE): """Accepts cache_hierarch as described in devassistant.cache and returns instances of YamlAssistant (only with cached attributes) for loaded fi...
Accepts file_hierarch as returned by cls. get_assistant_file_hierarchy and returns instances of YamlAssistant for loaded files
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: ...
Returns assistants file hierarchy structure ( see below ) representing assistant hierarchy in given directories.
def get_assistants_file_hierarchy(cls, dirs): """Returns assistants file hierarchy structure (see below) representing assistant hierarchy in given directories. It works like this: 1. It goes through all *.yaml files in all given directories and adds them into hierarchy (if th...
Constructs instance of YamlAssistant loaded from given structure y loaded from source file source.
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...
name is in dotted format e. g. topsnippet. something. wantedsnippet
def get_snippet_by_name(cls, name): """name is in dotted format, e.g. topsnippet.something.wantedsnippet""" name_with_dir_separators = name.replace('.', os.path.sep) loaded = yaml_loader.YamlLoader.load_yaml_by_relpath(cls.snippets_dirs, ...
5. 6. 1 Schema Validation Requirement <http:// shex. io/ shex - semantics/ #validation - requirement > _ A graph G is said to conform with a schema S with a ShapeMap m when:
def conforms(cntxt: Context, n: Node, S: ShExJ.Shape) -> bool: """ `5.6.1 Schema Validation Requirement <http://shex.io/shex-semantics/#validation-requirement>`_ A graph G is said to conform with a schema S with a ShapeMap m when: Every, SemAct in the startActs of S has a successful evaluation of semA...
legend needs to be a list tuple or None
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
Sets legend position. Default is r.
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 ...
Determines the appropriate data encoding type to give satisfactory resolution ( http:// code. google. com/ apis/ chart/ #chart_data ).
def data_class_detection(self, data): """Determines the appropriate data encoding type to give satisfactory resolution (http://code.google.com/apis/chart/#chart_data). """ assert(isinstance(data, list) or isinstance(data, tuple)) if not isinstance(self, (LineChart, BarChart, Scat...
Return a 2 - tuple giving the minimum and maximum x - axis data range.
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(s...
Scale self. data as appropriate for the given data encoding ( data_class ) and return it.
def scaled_data(self, data_class, x_range=None, y_range=None): """Scale `self.data` as appropriate for the given data encoding (data_class) and return it. An optional `y_range` -- a 2-tuple (lower, upper) -- can be given to specify the y-axis bounds. If not given, the range is i...
Set the country code map for the data. Codes given in a list.
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...
Sets the geo area for the map.
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...
Sets the data and country codes via a dictionary.
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()))
5. 4. 3 Datatype Constraints
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...
5. 4. 5 XML Schema Numberic Facet Constraints
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
5. 4. 5 XML Schema Numeric Facet Constraints
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. ""...
Map 5. 6. 2 Flags <https:// www. w3. org/ TR/ xpath - functions - 31/ #flags > _ to python
def _map_xpath_flags_to_re(expr: str, xpath_flags: str) -> Tuple[int, str]: """ Map `5.6.2 Flags <https://www.w3.org/TR/xpath-functions-31/#flags>`_ to python :param expr: match pattern :param xpath_flags: xpath flags :returns: python flags / modified match pattern """ python_flags: int = 0 ...
PyShEx. jsg <https:// github. com/ hsolbrig/ ShExJSG/ ShExJSG/ ShExJ. jsg > _ does not add identifying types to ObjectLiterals. This routine re - identifies the types
def map_object_literal(v: Union[str, jsonasobj.JsonObj]) -> ShExJ.ObjectLiteral: """ `PyShEx.jsg <https://github.com/hsolbrig/ShExJSG/ShExJSG/ShExJ.jsg>`_ does not add identifying types to ObjectLiterals. This routine re-identifies the types """ # TODO: isinstance(v, JSGString) should work here, but it...
Uncomment any lines that start with #import in the. pth file
def do_enable(): """ Uncomment any lines that start with #import in the .pth file """ try: _lines = [] with open(vext_pth, mode='r') as f: for line in f.readlines(): if line.startswith('#') and line[1:].lstrip().startswith('import '): _line...
Comment any lines that start with import in the. pth file
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 '): ...
Attempt to import everything in the test - imports section of specified vext_files
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 ther...
Convert path pointing subdirectory of virtualenv site - packages to system site - packages.
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_l...
Fixup paths added in. pth file that point to the virtualenv instead of the system site packages.
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...
Wrapper for site. addpackage
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 ...
convert a filename like html5lib - 0. 999. egg - info to html5lib
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
Add any new modules that are directories to the PATH
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 ...
If in a virtualenv then load spec files to decide which modules can be imported from system site - packages and install path hook.
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) r...
Only lets modules in allowed_modules be loaded others will get an ImportError
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) \ ...
: return: extra paths
def extra_paths(): """ :return: extra paths """ # TODO - this is only tested on Ubuntu for now # there must be a better way of getting # the sip directory. dirs = {} try: @vext.env.run_in_syspy def run(*args): import sipconfig config ...