INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
get joined base filter and current active filter for query
def _get_list_widget( self, filters, actions=None, order_column="", order_direction="", page=None, page_size=None, widgets=None, **args ): """ get joined base filter and current active filter for query """ widgets = widgets or ...
list function logic, override to implement different logic returns list and search widget
def _list(self): """ list function logic, override to implement different logic returns list and search widget """ if get_order_args().get(self.__class__.__name__): order_column, order_direction = get_order_args().get( self.__class__.__name__ ...
show function logic, override to implement different logic returns show and related list widget
def _show(self, pk): """ show function logic, override to implement different logic returns show and related list widget """ pages = get_page_args() page_sizes = get_page_size_args() orders = get_order_args() item = self.datamodel.get(pk, self._ba...
Add function logic, override to implement different logic returns add widget or None
def _add(self): """ Add function logic, override to implement different logic returns add widget or None """ is_valid_form = True get_filter_args(self._filters) exclude_cols = self._filters.get_relation_cols() form = self.add_form.refresh() ...
Edit function logic, override to implement different logic returns Edit widget and related list or None
def _edit(self, pk): """ Edit function logic, override to implement different logic returns Edit widget and related list or None """ is_valid_form = True pages = get_page_args() page_sizes = get_page_size_args() orders = get_order_args() ge...
Delete function logic, override to implement different logic deletes the record with primary_key = pk :param pk: record primary key to delete
def _delete(self, pk): """ Delete function logic, override to implement different logic deletes the record with primary_key = pk :param pk: record primary key to delete """ item = self.datamodel.get(pk, self._base_filters) if not item:...
fill the form with the suppressed cols, generated from exclude_cols
def _fill_form_exclude_cols(self, exclude_cols, form): """ fill the form with the suppressed cols, generated from exclude_cols """ for filter_key in exclude_cols: filter_value = self._filters.get_filter_value(filter_key) rel_obj = self.datamodel.get_related_ob...
Download a file from the current connection to the local filesystem. :param str remote: Remote file to download. May be absolute, or relative to the remote working directory. .. note:: Most SFTP servers set the remote working directory to the ...
def get(self, remote, local=None, preserve_mode=True): """ Download a file from the current connection to the local filesystem. :param str remote: Remote file to download. May be absolute, or relative to the remote working directory. .. note:: ...
Upload a file from the local filesystem to the current connection. :param local: Local path of file to upload, or a file-like object. **If a string is given**, it should be a path to a local (regular) file (not a directory). .. note:: When deali...
def put(self, local, remote=None, preserve_mode=True): """ Upload a file from the local filesystem to the current connection. :param local: Local path of file to upload, or a file-like object. **If a string is given**, it should be a path to a local (regular) ...
Load SSH config file(s) from disk. Also (beforehand) ensures that Invoke-level config re: runtime SSH config file paths, is accounted for. .. versionadded:: 2.0
def load_ssh_config(self): """ Load SSH config file(s) from disk. Also (beforehand) ensures that Invoke-level config re: runtime SSH config file paths, is accounted for. .. versionadded:: 2.0 """ # Update the runtime SSH config path (assumes enough regular confi...
Trigger loading of configured SSH config file paths. Expects that ``base_ssh_config`` has already been set to an `~paramiko.config.SSHConfig` object. :returns: ``None``.
def _load_ssh_files(self): """ Trigger loading of configured SSH config file paths. Expects that ``base_ssh_config`` has already been set to an `~paramiko.config.SSHConfig` object. :returns: ``None``. """ # TODO: does this want to more closely ape the behavior o...
Attempt to open and parse an SSH config file at ``path``. Does nothing if ``path`` is not a path to a valid file. :returns: ``None``.
def _load_ssh_file(self, path): """ Attempt to open and parse an SSH config file at ``path``. Does nothing if ``path`` is not a path to a valid file. :returns: ``None``. """ if os.path.isfile(path): old_rules = len(self.base_ssh_config._config) w...
Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtrees controlling behavior of ``run``...
def global_defaults(): """ Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtr...
Read ``chunk_size`` from ``reader``, writing result to ``writer``. Returns ``None`` if successful, or ``True`` if the read was empty. .. versionadded:: 2.0
def read_and_write(self, reader, writer, chunk_size): """ Read ``chunk_size`` from ``reader``, writing result to ``writer``. Returns ``None`` if successful, or ``True`` if the read was empty. .. versionadded:: 2.0 """ data = reader.recv(chunk_size) if len(data) ...
Return the local executing username, or ``None`` if one can't be found. .. versionadded:: 2.0
def get_local_user(): """ Return the local executing username, or ``None`` if one can't be found. .. versionadded:: 2.0 """ # TODO: I don't understand why these lines were added outside the # try/except, since presumably it means the attempt at catching ImportError # wouldn't work. However,...
Parameterize a Call with its Context set to a per-host Config.
def parameterize(self, call, host): """ Parameterize a Call with its Context set to a per-host Config. """ debug("Parameterizing {!r} for host {!r}".format(call, host)) # Generate a custom ConnectionCall that knows how to yield a Connection # in its make_context(), specif...
Run command truly locally, and over SSH via localhost
def mixed_use_of_local_and_run(self): """ Run command truly locally, and over SSH via localhost """ cxn = Connection("localhost") result = cxn.local("echo foo", hide=True) assert result.stdout == "foo\n" assert not cxn.is_connected # meh way of proving it didn't ...
Initiate an SSH connection to the host/port this object is bound to. This may include activating the configured gateway connection, if one is set. Also saves a handle to the now-set Transport object for easier access. Various connect-time settings (and/or their corresponding :ref:`SSH...
def open(self): """ Initiate an SSH connection to the host/port this object is bound to. This may include activating the configured gateway connection, if one is set. Also saves a handle to the now-set Transport object for easier access. Various connect-time settings (...
Obtain a socket-like object from `gateway`. :returns: A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a `.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway` was a string. .. versionadded:: 2.0
def open_gateway(self): """ Obtain a socket-like object from `gateway`. :returns: A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a `.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway` was a string. .. versionadded:: 2.0 ...
Terminate the network connection to the remote end, if open. If no connection is open, this method does nothing. .. versionadded:: 2.0
def close(self): """ Terminate the network connection to the remote end, if open. If no connection is open, this method does nothing. .. versionadded:: 2.0 """ if self.is_connected: self.client.close() if self.forward_agent and self._agent_handle...
Execute a shell command on the remote end of this connection. This method wraps an SSH-capable implementation of `invoke.runners.Runner.run`; see its documentation for details. .. warning:: There are a few spots where Fabric departs from Invoke's default settings/behavi...
def run(self, command, **kwargs): """ Execute a shell command on the remote end of this connection. This method wraps an SSH-capable implementation of `invoke.runners.Runner.run`; see its documentation for details. .. warning:: There are a few spots where Fabric dep...
Execute a shell command, via ``sudo``, on the remote end. This method is identical to `invoke.context.Context.sudo` in every way, except in that -- like `run` -- it honors per-host/per-connection configuration overrides in addition to the generic/global ones. Thus, for example, per-host...
def sudo(self, command, **kwargs): """ Execute a shell command, via ``sudo``, on the remote end. This method is identical to `invoke.context.Context.sudo` in every way, except in that -- like `run` -- it honors per-host/per-connection configuration overrides in addition to the g...
Execute a shell command on the local system. This method is effectively a wrapper of `invoke.run`; see its docs for details and call signature. .. versionadded:: 2.0
def local(self, *args, **kwargs): """ Execute a shell command on the local system. This method is effectively a wrapper of `invoke.run`; see its docs for details and call signature. .. versionadded:: 2.0 """ # Superclass run() uses runners.local, so we can liter...
Return a `~paramiko.sftp_client.SFTPClient` object. If called more than one time, memoizes the first result; thus, any given `.Connection` instance will only ever have a single SFTP client, and state (such as that managed by `~paramiko.sftp_client.SFTPClient.chdir`) will be preserved. ...
def sftp(self): """ Return a `~paramiko.sftp_client.SFTPClient` object. If called more than one time, memoizes the first result; thus, any given `.Connection` instance will only ever have a single SFTP client, and state (such as that managed by `~paramiko.sftp_client.SFT...
Open a tunnel connecting ``local_port`` to the server's environment. For example, say you want to connect to a remote PostgreSQL database which is locked down and only accessible via the system it's running on. You have SSH access to this server, so you can temporarily make port 5432 on...
def forward_local( self, local_port, remote_port=None, remote_host="localhost", local_host="localhost", ): """ Open a tunnel connecting ``local_port`` to the server's environment. For example, say you want to connect to a remote PostgreSQL database ...
Open a tunnel connecting ``remote_port`` to the local environment. For example, say you're running a daemon in development mode on your workstation at port 8080, and want to funnel traffic to it from a production or staging environment. In most situations this isn't possible as your of...
def forward_remote( self, remote_port, local_port=None, remote_host="127.0.0.1", local_host="localhost", ): """ Open a tunnel connecting ``remote_port`` to the local environment. For example, say you're running a daemon in development mode on your ...
Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
Parses sentence 's' using CNF grammar 'g'.
def _parse(s, g): """Parses sentence 's' using CNF grammar 'g'.""" # The CYK table. Indexed with a 2-tuple: (start pos, end pos) table = defaultdict(set) # Top-level structure is similar to the CYK table. Each cell is a dict from # rule name to the best (lightest) tree for that rule. trees = def...
Returns a non-terminal unit rule from 'g', or None if there is none.
def get_any_nt_unit_rule(g): """Returns a non-terminal unit rule from 'g', or None if there is none.""" for rule in g.rules: if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT): return rule return None
Removes 'rule' from 'g' without changing the langugage produced by 'g'.
def _remove_unit_rule(g, rule): """Removes 'rule' from 'g' without changing the langugage produced by 'g'.""" new_rules = [x for x in g.rules if x != rule] refs = [x for x in g.rules if x.lhs == rule.rhs[0]] new_rules += [build_unit_skiprule(rule, ref) for ref in refs] return Grammar(new_rules)
Splits a rule whose len(rhs) > 2 into shorter rules.
def _split(rule): """Splits a rule whose len(rhs) > 2 into shorter rules.""" rule_str = str(rule.lhs) + '__' + '_'.join(str(x) for x in rule.rhs) rule_name = '__SP_%s' % (rule_str) + '_%d' yield Rule(rule.lhs, [rule.rhs[0], NT(rule_name % 1)], weight=rule.weight, alias=rule.alias) for i in xrange(1,...
Applies the TERM rule on 'g' (see top comment).
def _term(g): """Applies the TERM rule on 'g' (see top comment).""" all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)} t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t} new_rules = [] for rule in g.rules: if len(rule.rhs) > 1 and any(is...
Applies the BIN rule to 'g' (see top comment).
def _bin(g): """Applies the BIN rule to 'g' (see top comment).""" new_rules = [] for rule in g.rules: if len(rule.rhs) > 2: new_rules += _split(rule) else: new_rules.append(rule) return Grammar(new_rules)
Applies the UNIT rule to 'g' (see top comment).
def _unit(g): """Applies the UNIT rule to 'g' (see top comment).""" nt_unit_rule = get_any_nt_unit_rule(g) while nt_unit_rule: g = _remove_unit_rule(g, nt_unit_rule) nt_unit_rule = get_any_nt_unit_rule(g) return g
Reverts a parse tree (RuleNode) to its original non-CNF form (Node).
def revert_cnf(node): """Reverts a parse tree (RuleNode) to its original non-CNF form (Node).""" if isinstance(node, T): return node # Reverts TERM rule. if node.rule.lhs.name.startswith('__T_'): return node.children[0] else: children = [] for child in map(revert_cnf,...
Converts a lark rule, (lhs, rhs, callback, options), to a Rule.
def _to_rule(self, lark_rule): """Converts a lark rule, (lhs, rhs, callback, options), to a Rule.""" assert isinstance(lark_rule.origin, NT) assert all(isinstance(x, Symbol) for x in lark_rule.expansion) return Rule( lark_rule.origin, lark_rule.expansion, weight=l...
Parses input, which is a list of tokens.
def parse(self, tokenized): # pylint: disable=invalid-name """Parses input, which is a list of tokens.""" table, trees = _parse(tokenized, self.grammar) # Check if the parse succeeded. if all(r.lhs != self.start for r in table[(0, len(tokenized) - 1)]): raise ParseError('Par...
Converts a RuleNode parse tree to a lark Tree.
def _to_tree(self, rule_node): """Converts a RuleNode parse tree to a lark Tree.""" orig_rule = self.orig_rules[rule_node.rule.alias] children = [] for child in rule_node.children: if isinstance(child, RuleNode): children.append(self._to_tree(child)) ...
Creates a colorful image that represents the tree (data+children, without meta) Possible values for `rankdir` are "TB", "LR", "BT", "RL", corresponding to directed graphs drawn from top to bottom, from left to right, from bottom to top, and from right to left, respectively. See: https://www.graphviz.or...
def pydot__tree_to_png(tree, filename, rankdir="LR"): """Creates a colorful image that represents the tree (data+children, without meta) Possible values for `rankdir` are "TB", "LR", "BT", "RL", corresponding to directed graphs drawn from top to bottom, from left to right, from bottom to top, and from ...
Expand (inline) children at the given indices
def expand_kids_by_index(self, *indices): "Expand (inline) children at the given indices" for i in sorted(indices, reverse=True): # reverse so that changing tail won't affect indices kid = self.children[i] self.children[i:i+1] = kid.children
See Interpreter
def visit_children_decor(func): "See Interpreter" @wraps(func) def inner(cls, tree): values = cls.visit_children(tree) return func(cls, values) return inner
A convenience decorator factory, for modifying the behavior of user-supplied visitor methods
def v_args(inline=False, meta=False, tree=False): "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods" if [tree, meta, inline].count(True) > 1: raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.") de...
Given a parser instance and a dictionary mapping some label with some malformed syntax examples, it'll return the label for the example that bests matches the current error.
def match_examples(self, parse_fn, examples): """ Given a parser instance and a dictionary mapping some label with some malformed syntax examples, it'll return the label for the example that bests matches the current error. """ assert self.state is not None, "Not supporte...
Consume a token and calculate the new line & column. As an optional optimization, set test_newline=False is token doesn't contain a newline.
def feed(self, token, test_newline=True): """Consume a token and calculate the new line & column. As an optional optimization, set test_newline=False is token doesn't contain a newline. """ if test_newline: newlines = token.count(self.newline_char) if newlines: ...
Create an instance of Lark with the grammar given by its filename If rel_to is provided, the function will find the grammar filename in relation to it. Example: >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr") Lark(...)
def open(cls, grammar_filename, rel_to=None, **options): """Create an instance of Lark with the grammar given by its filename If rel_to is provided, the function will find the grammar filename in relation to it. Example: >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="...
Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard
def lex(self, text): "Only lex (and postlex) the text, without parsing it. Only relevant when lexer='standard'" if not hasattr(self, 'lexer'): self.lexer = self._build_lexer() stream = self.lexer.lex(text) if self.options.postlex: return self.options.postlex.proce...
Calculate FOLLOW sets. Adapted from: http://lara.epfl.ch/w/cc09:algorithm_for_first_and_follow_sets
def calculate_sets(rules): """Calculate FOLLOW sets. Adapted from: http://lara.epfl.ch/w/cc09:algorithm_for_first_and_follow_sets""" symbols = {sym for rule in rules for sym in rule.expansion} | {rule.origin for rule in rules} # foreach grammar rule X ::= Y(1) ... Y(k) # if k=0 or {Y(1),...,Y(k)} ...
Returns all rules and terminals of grammar, prepended with a 'namespace' prefix, except for those which are aliased.
def import_from_grammar_into_namespace(grammar, namespace, aliases): """Returns all rules and terminals of grammar, prepended with a 'namespace' prefix, except for those which are aliased. """ imported_terms = dict(grammar.term_defs) imported_rules = {n:(n,deepcopy(t),o) for n,t,o in grammar.rule_d...
Parse grammar_text, verify, and create Grammar object. Display nice messages on error.
def load_grammar(self, grammar_text, grammar_name='<?>'): "Parse grammar_text, verify, and create Grammar object. Display nice messages on error." try: tree = self.canonize_tree.transform( self.parser.parse(grammar_text+'\n') ) except UnexpectedCharacters as e: context =...
Conditionally disabled/enables form fields based on the current section in the radio group
def applyStyleRules(self): """ Conditionally disabled/enables form fields based on the current section in the radio group """ for button, widget in zip(self.radioButtons, self.widgets): if isinstance(widget, CheckBox): widget.hideInput() ...
Checkboxes are hidden when inside of a RadioGroup as a selection of the Radio button is an implicit selection of the Checkbox. As such, we have to manually "check" any checkbox as needed.
def handleImplicitCheck(self): """ Checkboxes are hidden when inside of a RadioGroup as a selection of the Radio button is an implicit selection of the Checkbox. As such, we have to manually "check" any checkbox as needed. """ for button, widget in zip(self.radioBut...
Instantiate the Gooey Widgets that are used within the RadioGroup
def createWidgets(self): """ Instantiate the Gooey Widgets that are used within the RadioGroup """ from gooey.gui.components import widgets return [getattr(widgets, item['type'])(self, item) for item in getin(self.widgetInfo, ['data', 'widgets'], [])]
Verify user input and kick off the client's program if valid
def onStart(self, *args, **kwarg): """ Verify user input and kick off the client's program if valid """ with transactUI(self): config = self.navbar.getActiveConfig() config.resetErrors() if config.isValid(): self.clientRunner.ru...
Return the user to the settings screen for further editing
def onEdit(self): """Return the user to the settings screen for further editing""" with transactUI(self): if self.buildSpec['poll_external_updates']: self.fetchExternalUpdates() self.showSettings()
Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program
def buildCliString(self): """ Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program """ config = self.navbar.getActiveConfig() group = self.buildSpec['widgets'][self.navbar.getSelectedGro...
Display the appropriate screen based on the success/fail of the host program
def onComplete(self, *args, **kwargs): """ Display the appropriate screen based on the success/fail of the host program """ with transactUI(self): if self.clientRunner.was_success(): if self.buildSpec.get('return_to_config', False): ...
!Experimental! Calls out to the client code requesting seed values to use in the UI !Experimental!
def fetchExternalUpdates(self): """ !Experimental! Calls out to the client code requesting seed values to use in the UI !Experimental! """ seeds = seeder.fetchDynamicProperties( self.buildSpec['target'], self.buildSpec['encoding'] ...
Chooses the appropriate layout navigation component based on user prefs
def buildNavigation(self): """ Chooses the appropriate layout navigation component based on user prefs """ if self.buildSpec['navigation'] == constants.TABBED: navigation = Tabbar(self, self.buildSpec, self.configs) else: navigation = Sidebar(self, ...
Choose the best font face available given the user options
def getFontFace(self): """Choose the best font face available given the user options""" userFace = self.buildSpec['terminal_font_family'] or self.defaultFont.GetFaceName() return ('' if self.buildSpec['monospace_display'] else userFace)
Reads the stdout of `process` and forwards lines and progress to any interested subscribers
def _forward_stdout(self, process): ''' Reads the stdout of `process` and forwards lines and progress to any interested subscribers ''' while True: line = process.stdout.readline() if not line: break pub.send_message(ev...
Finds progress information in the text using the user-supplied regex and calculation instructions
def _extract_progress(self, text): ''' Finds progress information in the text using the user-supplied regex and calculation instructions ''' # monad-ish dispatch to avoid the if/else soup find = partial(re.search, string=text.strip().decode(self.encoding)) ...
Calculates the final progress value found by the regex
def _calculate_progress(self, match): ''' Calculates the final progress value found by the regex ''' if not self.progress_expr: return safe_float(match.group(1)) else: return self._eval_progress(match)
Runs the user-supplied progress calculation rule
def _eval_progress(self, match): ''' Runs the user-supplied progress calculation rule ''' _locals = {k: safe_float(v) for k, v in match.groupdict().items()} if "x" not in _locals: _locals["x"] = [safe_float(x) for x in match.groups()] try: ...
Hide/show configuration panels based on the currently selected option in the sidebar
def swapConfigPanels(self, event): """Hide/show configuration panels based on the currently selected option in the sidebar """ for id, panel in enumerate(self.configPanels): panel.Hide() self.activeSelection = event.Selection self.configPanels[event.Selection]....
value, disable_animation=False :param args: :param kwargs: :return:
def updateProgressBar(self, *args, **kwargs): ''' value, disable_animation=False :param args: :param kwargs: :return: ''' value = kwargs.get('progress') pb = self.progress_bar if value is None: return if value < 0: ...
Decorator for client code's main function. Serializes argparse data to JSON for use with the Gooey front end
def Gooey(f=None, advanced=True, language='english', auto_start=False, # TODO: add this to the docs. Used to be `show_config=True` target=None, program_name=None, program_description=None, default_size=(610, 530), use_legacy_titles...
Sends a gooey-seed-ui request to the client program it retrieve dynamically generated defaults with which to seed the UI
def fetchDynamicProperties(target, encoding): """ Sends a gooey-seed-ui request to the client program it retrieve dynamically generated defaults with which to seed the UI """ cmd = '{} {}'.format(target, 'gooey-seed-ui --ignore-gooey') proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, s...
Messily builds the (potentially) nested and grouped layout Note! Mutates `self.reifiedWidgets` in place with the widgets as they're instantiated! I cannot figure out how to split out the creation of the widgets from their styling without WxPython violently exploding TODO: sort ou...
def makeGroup(self, parent, thissizer, group, *args): ''' Messily builds the (potentially) nested and grouped layout Note! Mutates `self.reifiedWidgets` in place with the widgets as they're instantiated! I cannot figure out how to split out the creation of the widgets from...
chunk the widgets up into groups based on their sizing hints
def chunkWidgets(self, group): ''' chunk the widgets up into groups based on their sizing hints ''' ui_groups = [] subgroup = [] for index, item in enumerate(group['items']): if getin(item, ['options', 'full_width'], False): ui_groups.append(subgroup) ...
Convert a JSON description of a widget into a WxObject
def reifyWidget(self, parent, item): ''' Convert a JSON description of a widget into a WxObject ''' from gooey.gui.components import widgets widgetClass = getattr(widgets, item['type']) return widgetClass(parent, item)
Recursively extract argument groups and associated actions from ParserGroup objects
def extract_groups(action_group): ''' Recursively extract argument groups and associated actions from ParserGroup objects ''' return { 'name': action_group.title, 'description': action_group.description, 'items': [action for action in action_group._group_actions ...
_actions possessing the `required` flag and not implicitly optional through `nargs` being '*' or '?'
def is_required(action): ''' _actions possessing the `required` flag and not implicitly optional through `nargs` being '*' or '?' ''' return not isinstance(action, _SubParsersAction) and ( action.required == True and action.nargs not in ['*', '?'])
actions which are general "store" instructions. e.g. anything which has an argument style like: $ script.py -f myfilename.txt
def is_standard(action): """ actions which are general "store" instructions. e.g. anything which has an argument style like: $ script.py -f myfilename.txt """ boolean_actions = ( _StoreConstAction, _StoreFalseAction, _StoreTrueAction ) return (not action.choices ...
_actions which are either storeconst, store_bool, etc..
def is_flag(action): """ _actions which are either storeconst, store_bool, etc.. """ action_types = [_StoreTrueAction, _StoreFalseAction, _StoreConstAction] return any(list(map(lambda Action: isinstance(action, Action), action_types)))
Returns str(option_string * DropDown Value) e.g. -vvvvv
def counter(metatdata, value): ''' Returns str(option_string * DropDown Value) e.g. -vvvvv ''' if not str(value).isdigit(): return None arg = str(metatdata['commands'][0]).replace('-', '') repeated_args = arg * int(value) return '-' + repeated_args
Open and return the supplied json file
def load(language_dir, filename, encoding): ''' Open and return the supplied json file ''' global _DICTIONARY try: json_file = filename + '.json' with io.open(os.path.join(language_dir, json_file), 'r', encoding=encoding) as f: _DICTIONARY = json.load(f) except IOError: raise IOError('...
returns the value in a nested dict
def getin(m, path, default=None): """returns the value in a nested dict""" keynotfound = ':com.gooey-project/not-found' result = reduce(lambda acc, val: acc.get(val, {keynotfound: None}), path, m) # falsey values like 0 would incorrectly trigger the default to be returned # so the keynotfound v...
Copy-on-write associates a value in a dict
def assoc(m, key, val): """Copy-on-write associates a value in a dict""" cpy = deepcopy(m) cpy[key] = val return cpy
Copy-on-write associates a value in a nested dict
def associn(m, path, value): """ Copy-on-write associates a value in a nested dict """ def assoc_recursively(m, path, value): if not path: return value p = path[0] return assoc(m, p, assoc_recursively(m.get(p,{}), path[1:], value)) return assoc_recursively(m, path,...
Merge all maps left to right
def merge(*maps): """Merge all maps left to right""" copies = map(deepcopy, maps) return reduce(lambda acc, val: acc.update(val) or acc, copies)
Return first occurrence matching f, otherwise None
def findfirst(f, coll): """Return first occurrence matching f, otherwise None""" result = list(dropwhile(f, coll)) return result[0] if result else None
Generates the `input_tensor` that minimizes the weighted `losses`. This function is intended for advanced use cases where a custom loss is desired. Args: input_tensor: An input tensor of shape: `(samples, channels, image_dims...)` if `image_data_format= channels_first` or `(samples, image_d...
def visualize_activation_with_losses(input_tensor, losses, wrt_tensor=None, seed_input=None, input_range=(0, 255), **optimizer_params): """Generates the `input_tensor` that minimizes the weighted `losses`. This function is intended for advanc...
Generates the model input that maximizes the output of all `filter_indices` in the given `layer_idx`. Args: model: The `keras.models.Model` instance. The model input shape must be: `(samples, channels, image_dims...)` if `image_data_format=channels_first` or `(samples, image_dims..., channels)`...
def visualize_activation(model, layer_idx, filter_indices=None, wrt_tensor=None, seed_input=None, input_range=(0, 255), backprop_modifier=None, grad_modifier=None, act_max_weight=1, lp_norm_weight=10, tv_weight=10, **opt...
Uses RMSProp to compute step from gradients. Args: grads: numpy array of gradients. cache: numpy array of same shape as `grads` as RMSProp cache decay_rate: How fast to decay cache Returns: A tuple of step: numpy array of the same shape a...
def _rmsprop(self, grads, cache=None, decay_rate=0.95): """Uses RMSProp to compute step from gradients. Args: grads: numpy array of gradients. cache: numpy array of same shape as `grads` as RMSProp cache decay_rate: How fast to decay cache Returns: ...
Creates a random `seed_input` if None. Otherwise: - Ensures batch_size dim on provided `seed_input`. - Shuffle axis according to expected `image_data_format`.
def _get_seed_input(self, seed_input): """Creates a random `seed_input` if None. Otherwise: - Ensures batch_size dim on provided `seed_input`. - Shuffle axis according to expected `image_data_format`. """ desired_shape = (1, ) + K.int_shape(self.input_tensor)[1:] ...
Performs gradient descent on the input image with respect to defined losses. Args: seed_input: An N-dim numpy array of shape: `(samples, channels, image_dims...)` if `image_data_format= channels_first` or `(samples, image_dims..., channels)` if `image_data_format=channels_last`. ...
def minimize(self, seed_input=None, max_iter=200, input_modifiers=None, grad_modifier=None, callbacks=None, verbose=True): """Performs gradient descent on the input image with respect to defined losses. Args: seed_input: An N-dim numpy array of shape: `(sam...
Orders the set of `objs` by `line_nos`
def order_by_line_nos(objs, line_nos): """Orders the set of `objs` by `line_nos` """ ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__) return [objs[i] for i in ordering]
Import a module path and create an api doc from it Args: string (str): string with line breaks to write to file. filename (str): filename without the .md out_path (str): The output directory
def to_md_file(string, filename, out_path="."): """Import a module path and create an api doc from it Args: string (str): string with line breaks to write to file. filename (str): filename without the .md out_path (str): The output directory """ md_file = "%s.md" % filename ...
Creates a src path string with line info for use as markdown link.
def get_src_path(self, obj, append_base=True): """Creates a src path string with line info for use as markdown link. """ path = getsourcefile(obj) if self.src_root not in path: # this can happen with e.g. # inlinefunc-wrapped functions if hasattr(obj, ...
Parse docstring (parsed with getdoc) according to Google-style formatting and convert to markdown. We support the following Google style syntax: Args, Kwargs: argname (type): text freeform text Returns, Yields: retname (type): text freefor...
def doc2md(self, func): """Parse docstring (parsed with getdoc) according to Google-style formatting and convert to markdown. We support the following Google style syntax: Args, Kwargs: argname (type): text freeform text Returns, Yields: retna...
Takes a function (or method) and documents it. Args: clsname (str, optional): class name to prepend to funcname. depth (int, optional): number of ### to append to function name
def func2md(self, func, clsname=None, names=None, depth=3): """Takes a function (or method) and documents it. Args: clsname (str, optional): class name to prepend to funcname. depth (int, optional): number of ### to append to function name """ section = "#" * de...
Takes a class and creates markdown text to document its methods and variables.
def class2md(self, cls, depth=2): """Takes a class and creates markdown text to document its methods and variables. """ section = "#" * depth subsection = "#" * (depth + 2) clsname = cls.__name__ modname = cls.__module__ header = clsname path = self.get_s...
Takes an imported module object and create a Markdown string containing functions and classes.
def module2md(self, module): """Takes an imported module object and create a Markdown string containing functions and classes. """ modname = module.__name__ path = self.get_src_path(module, append_base=False) path = "[{}]({})".format(path, os.path.join(self.github_link, path)) ...
Searches for the nearest penultimate `Conv` or `Pooling` layer. Args: model: The `keras.models.Model` instance. layer_idx: The layer index within `model.layers`. penultimate_layer_idx: The pre-layer to `layer_idx`. If set to None, the nearest penultimate `Conv` or `Pooling` laye...
def _find_penultimate_layer(model, layer_idx, penultimate_layer_idx): """Searches for the nearest penultimate `Conv` or `Pooling` layer. Args: model: The `keras.models.Model` instance. layer_idx: The layer index within `model.layers`. penultimate_layer_idx: The pre-layer to `layer_idx`....
Generates an attention heatmap over the `seed_input` by using positive gradients of `input_tensor` with respect to weighted `losses`. This function is intended for advanced use cases where a custom loss is desired. For common use cases, refer to `visualize_class_saliency` or `visualize_regression_saliency`...
def visualize_saliency_with_losses(input_tensor, losses, seed_input, wrt_tensor=None, grad_modifier='absolute', keepdims=False): """Generates an attention heatmap over the `seed_input` by using positive gradients of `input_tensor` with respect to weighted `losses`. This function is intended for advanced us...
Generates an attention heatmap over the `seed_input` for maximizing `filter_indices` output in the given `layer_idx`. Args: model: The `keras.models.Model` instance. The model input shape must be: `(samples, channels, image_dims...)` if `image_data_format=channels_first` or `(samples, image...
def visualize_saliency(model, layer_idx, filter_indices, seed_input, wrt_tensor=None, backprop_modifier=None, grad_modifier='absolute', keepdims=False): """Generates an attention heatmap over the `seed_input` for maximizing `filter_indices` output in the given `layer_idx`. Args: ...
Generates a gradient based class activation map (CAM) by using positive gradients of `input_tensor` with respect to weighted `losses`. For details on grad-CAM, see the paper: [Grad-CAM: Why did you say that? Visual Explanations from Deep Networks via Gradient-based Localization] (https://arxiv.org/pdf/...
def visualize_cam_with_losses(input_tensor, losses, seed_input, penultimate_layer, grad_modifier=None): """Generates a gradient based class activation map (CAM) by using positive gradients of `input_tensor` with respect to weighted `losses`. For details on grad-CAM, see the paper: [Grad-CAM: Why did yo...
Generates a gradient based class activation map (grad-CAM) that maximizes the outputs of `filter_indices` in `layer_idx`. Args: model: The `keras.models.Model` instance. The model input shape must be: `(samples, channels, image_dims...)` if `image_data_format=channels_first` or `(samples, i...
def visualize_cam(model, layer_idx, filter_indices, seed_input, penultimate_layer_idx=None, backprop_modifier=None, grad_modifier=None): """Generates a gradient based class activation map (grad-CAM) that maximizes the outputs of `filter_indices` in `layer_idx`. Args: ...
Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior. Args: model: The `keras.models.Model` instance. backprop_modifier: One of `{'guided', 'rectified'}` Returns: A copy of model with modified activations for backwards pass.
def modify_model_backprop(model, backprop_modifier): """Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior. Args: model: The `keras.models.Model` instance. backprop_modifier: One of `{'guided', 'rectified'}` Returns: A copy of m...
Normalizes the `output_tensor` with respect to `input_tensor` dimensions. This makes regularizer weight factor more or less uniform across various input image dimensions. Args: input_tensor: An tensor of shape: `(samples, channels, image_dims...)` if `image_data_format= channels_first` ...
def normalize(input_tensor, output_tensor): """Normalizes the `output_tensor` with respect to `input_tensor` dimensions. This makes regularizer weight factor more or less uniform across various input image dimensions. Args: input_tensor: An tensor of shape: `(samples, channels, image_dims...)` if `...