INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Entry point for stand-alone execution.
def main(): """Entry point for stand-alone execution.""" conf.init(), db.init(conf.DbPath) inqueue = LineQueue(sys.stdin).queue outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})() if "--quiet" in sys.argv: outqueue = None if conf.MouseEnabled: inqueue.put("mou...
Windows key event handler.
def _handle_windows(self, event): """Windows key event handler.""" vkey = self._keyname(event.GetKey()) if event.Message in self.KEYS_UP + self.KEYS_DOWN: if vkey in self.MODIFIERNAMES: self._realmodifiers[vkey] = event.Message in self.KEYS_DOWN ...
Mac key event handler
def _handle_mac(self, keycode): """Mac key event handler""" key = self._keyname(unichr(keycode)) self._output(type="keys", key=key, realkey=key)
Linux key event handler.
def _handle_linux(self, keycode, character, press): """Linux key event handler.""" if character is None: return key = self._keyname(character, keycode) if key in self.MODIFIERNAMES: self._modifiers[self.MODIFIERNAMES[key]] = press self._realmodifiers[key] = ...
Activates GwDocumentsInfo by registering: * 2 commands (doc, doc_list) * 1 document (documents_overview)
def activate(self): """ Activates GwDocumentsInfo by registering: * 2 commands (doc, doc_list) * 1 document (documents_overview) """ self.commands.register("doc_list", "List all documents", self._list_documents) self.commands.register("doc", "Shows the documentat...
Stores all documents on the file system. Target location is **path**. File name is the lowercase name of the document + .rst.
def _store_documentation(self, path, html, overwrite, quiet): """ Stores all documents on the file system. Target location is **path**. File name is the lowercase name of the document + .rst. """ echo("Storing groundwork application documents\n") echo("Application: %s" ...
Shows all documents of the current groundwork app in the console. Documents are sorted bei its names, except "main", which gets set to the beginning.
def _show_documentation(self): """ Shows all documents of the current groundwork app in the console. Documents are sorted bei its names, except "main", which gets set to the beginning. """ documents = [] for key, document in self.app.documents.get().items(): ...
Execute several cleanup tasks as part of the cleanup. REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks. :param ctx: Context object for the tasks. :param cleanup_tasks: Collection of cleanup tasks (as Collection). :param dry_run: Indicates dry-run mode (bool)
def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False): """Execute several cleanup tasks as part of the cleanup. REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks. :param ctx: Context object for the tasks. :param cleanup_tasks: Collection of cleanup tasks (as Colle...
Remove directories (and their contents) recursively. Skips removal if directories does not exist. :param patterns: Directory name patterns, like "**/tmp*" (as list). :param dry_run: Dry-run mode indicator (as bool). :param workdir: Current work directory (default=".")
def cleanup_dirs(patterns, dry_run=False, workdir="."): """Remove directories (and their contents) recursively. Skips removal if directories does not exist. :param patterns: Directory name patterns, like "**/tmp*" (as list). :param dry_run: Dry-run mode indicator (as bool). :param workdir: ...
Returns a signature size for the input :param msg: :return:
def get_signature_size(msg): """ Returns a signature size for the input :param msg: :return: """ if isinstance(msg, (TxinGen, TxinToScript, TxinToScriptHash)): return 0 elif isinstance(msg, TxinToKey): return len(msg.key_offsets) else: raise ValueError('Unknown tx...
Custom serialization :param ar: :type ar: x.Archive :return:
async def serialize_rctsig_base(self, ar, inputs, outputs): """ Custom serialization :param ar: :type ar: x.Archive :return: """ await self._msg_field(ar, idx=0) if self.type == RctType.Null: return if self.type != RctType.Full and self...
Serialize rct sig :param ar: :type ar: x.Archive :param type: :param inputs: :param outputs: :param mixin: :return:
async def serialize_rctsig_prunable(self, ar, type, inputs, outputs, mixin): """ Serialize rct sig :param ar: :type ar: x.Archive :param type: :param inputs: :param outputs: :param mixin: :return: """ if type == RctType.Null: ...
Get ScaleIO StoragePool object by its name :param name: Name of StoragePool :return: ScaleIO StoragePool object :raise KeyError: No StoragePool with specified name found :rtype: StoragePool object
def get_storage_pool_by_name(self, name): """ Get ScaleIO StoragePool object by its name :param name: Name of StoragePool :return: ScaleIO StoragePool object :raise KeyError: No StoragePool with specified name found :rtype: StoragePool object """ for stora...
Get ScaleIO SDS ofbject by its id :param name: Name of StoragePool :return: ScaleIO StoraegPool object :raise KeyError: No StoragePool with specified id found :rtype: StoragePool object
def get_storage_pool_by_id(self, id): """ Get ScaleIO SDS ofbject by its id :param name: Name of StoragePool :return: ScaleIO StoraegPool object :raise KeyError: No StoragePool with specified id found :rtype: StoragePool object """ for storage_pool in self...
Returns the Entry Point for a given Entry Point section. :param str section: The section name in the entry point collection :returns: A dictionary of (Name, Class) pairs stored in the entry point collection.
def entrypoints(section): """ Returns the Entry Point for a given Entry Point section. :param str section: The section name in the entry point collection :returns: A dictionary of (Name, Class) pairs stored in the entry point collection. """ return {ep.name: ep.load() for ep in pkg_resources.i...
Returns the the entry point object given a section, option pair. :param str section: The section name in the entry point collection :param str option: The option name in the entry point collection :return: The entry point object if available.
def entrypoint(section, option): """ Returns the the entry point object given a section, option pair. :param str section: The section name in the entry point collection :param str option: The option name in the entry point collection :return: The entry point object if available. """ try: ...
Retrieves any declared information from the given macaroons and returns it as a key-value map. Information is declared with a first party caveat as created by declared_caveat. If there are two caveats that declare the same key with different values, the information is omitted from the map. When the...
def infer_declared(ms, namespace=None): '''Retrieves any declared information from the given macaroons and returns it as a key-value map. Information is declared with a first party caveat as created by declared_caveat. If there are two caveats that declare the same key with different values, th...
like infer_declared except that it is passed a set of first party caveat conditions as a list of string rather than a set of macaroons.
def infer_declared_from_conditions(conds, namespace=None): ''' like infer_declared except that it is passed a set of first party caveat conditions as a list of string rather than a set of macaroons. ''' conflicts = [] # If we can't resolve that standard namespace, then we'll look for # just bare...
Unescape Monero json encoded string /monero/external/rapidjson/reader.h :param st: :return:
def unescape_json_str(st): """ Unescape Monero json encoded string /monero/external/rapidjson/reader.h :param st: :return: """ c = 0 ln = len(st) escape_chmap = { b'b': b'\b', b'f': b'\f', b'n': b'\n', b'r': b'\r', b't': b'\t', b'\\': ...
Escaping string for json /Users/dusanklinec/workspace/monero/external/rapidjson/writer.h :param st: :return:
def escape_string_json(st): """ Escaping string for json /Users/dusanklinec/workspace/monero/external/rapidjson/writer.h :param st: :return: """ ret = [] c = 0 ln = len(st) escape_chmap = { b'\b': b'b', b'\f': b'f', b'\n': b'n', b'\r': b'r', ...
Injects functions before the activation routine of child classes gets called
def _pre_activate_injection(self): """ Injects functions before the activation routine of child classes gets called """ # Let's be sure that this plugins class is registered and available on application level under # application.plugins.classes. This allows to reuse this class fo...
Injects functions after the activation routine of child classes got called :return: None
def _post_activate_injection(self): """ Injects functions after the activation routine of child classes got called :return: None """ self.active = True self.app.signals.send("plugin_activate_post", self)
Injects functions after the deactivation routine of child classes got called :return: None
def _post_deactivate_injection(self): """ Injects functions after the deactivation routine of child classes got called :return: None """ # Lets be sure that active is really set to false. self.active = False self.app.signals.send("plugin_deactivate_post", self) ...
Checks if this plugins needs other plugins to work and tries to activate them :return: True, if all needed plugins are or got activated. Otherwise False
def _load_needed_plugins(self): """ Checks if this plugins needs other plugins to work and tries to activate them :return: True, if all needed plugins are or got activated. Otherwise False """ global plugin_recursive_store if "plugin_recursive_store" not in globals(): ...
Registers a new signal. Only registered signals are allowed to be send. :param signal: Unique name of the signal :param description: Description of the reason or use case, why this signal is needed. Used for documentation.
def register(self, signal, description): """ Registers a new signal. Only registered signals are allowed to be send. :param signal: Unique name of the signal :param description: Description of the reason or use case, why this signal is needed. Used fo...
Connect a receiver to a signal :param receiver: Name of the receiver :type receiver: str :param signal: Name of the signal. Must already be registered! :type signal: str :param function: Callable functions, which shall be executed, of signal is send. :param description: ...
def connect(self, receiver, signal, function, description, sender=None): """ Connect a receiver to a signal :param receiver: Name of the receiver :type receiver: str :param signal: Name of the signal. Must already be registered! :type signal: str :param function:...
Sends a signal for the given plugin. :param signal: Name of the signal :type signal: str
def send(self, signal, **kwargs): """ Sends a signal for the given plugin. :param signal: Name of the signal :type signal: str """ return self.__app.signals.send(signal, plugin=self._plugin, **kwargs)
Returns a single signal or a dictionary of signals for this plugin.
def get(self, signal=None): """ Returns a single signal or a dictionary of signals for this plugin. """ return self.__app.signals.get(signal, self._plugin)
Returns a single receiver or a dictionary of receivers for this plugin.
def get_receiver(self, receiver=None): """ Returns a single receiver or a dictionary of receivers for this plugin. """ return self.__app.signals.get_receiver(receiver, self._plugin)
Check attributes.
def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes)
Check __model_cls__ attribute. :type attributes: dict
def check_model_cls(attributes): """Check __model_cls__ attribute. :type attributes: dict """ model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.D...
Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple
def get_prepared_include_exclude(attributes): """Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple """ attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in ...
Check __include__ and __exclude__ attributes. :type attributes: dict
def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise Type...
Return tuple of names of defined properties. :type attributes: dict :rtype: list
def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)]
Check whether intersections exist. :type attributes: dict
def check_properties(mcs, attributes): """Check whether intersections exist. :type attributes: dict """ include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersect...
Creates a configuration instance from class :class:`~groundwork.configuration.configmanager.Config` from all files in self.files and set the dictionary items as attributes of of this instance. :return: Instance of :class:`~groundwork.configuration.configmanager.Config`
def load(self, config_files): """ Creates a configuration instance from class :class:`~groundwork.configuration.configmanager.Config` from all files in self.files and set the dictionary items as attributes of of this instance. :return: Instance of :class:`~groundwork.configuration.confi...
Event Handler when a file is deleted
def on_deleted(self, event): """ Event Handler when a file is deleted """ key = 'filesystem:file_deleted' data = { 'filepath': event.src_path, 'is_directory': event.is_directory, 'dirpath': os.path.dirname(event.src_path) } bms...
Given a datetime.datetime object, return a string representing this date/time, formatted according to this dateformat.
def format(self, date): """ Given a datetime.datetime object, return a string representing this date/time, formatted according to this dateformat. """ context = {'date': date} for handler in self.format_chain: handler(self, date, context) return eval(s...
Loads agent authentication information from the specified content string, as read from an agents file. The returned information is suitable for passing as an argument to the AgentInteractor constructor. @param agent_file_content The agent file content (str) @return AuthInfo The authentication inform...
def read_auth_info(agent_file_content): '''Loads agent authentication information from the specified content string, as read from an agents file. The returned information is suitable for passing as an argument to the AgentInteractor constructor. @param agent_file_content The agent file content (str)...
Implement Interactor.interact by obtaining obtaining a macaroon from the discharger, discharging it with the local private key using the discharged macaroon as a discharge token
def interact(self, client, location, interaction_required_err): '''Implement Interactor.interact by obtaining obtaining a macaroon from the discharger, discharging it with the local private key using the discharged macaroon as a discharge token''' p = interaction_required_err.int...
Finds an appropriate agent entry for the given location. :return Agent
def _find_agent(self, location): ''' Finds an appropriate agent entry for the given location. :return Agent ''' for a in self._auth_info.agents: # Don't worry about trailing slashes if a.url.rstrip('/') == location.rstrip('/'): return a rai...
Implement LegacyInteractor.legacy_interact by obtaining the discharge macaroon using the client's private key
def legacy_interact(self, client, location, visit_url): '''Implement LegacyInteractor.legacy_interact by obtaining the discharge macaroon using the client's private key ''' agent = self._find_agent(location) # Shallow-copy the client so that we don't unexpectedly side-effect ...
Returns the minimum time of any time-before caveats found in the given macaroons or None if no such caveats were found. :param ns: a Namespace, used to resolve caveats. :param ms: a list of pymacaroons.Macaroon :return: datetime.DateTime or None.
def macaroons_expiry_time(ns, ms): ''' Returns the minimum time of any time-before caveats found in the given macaroons or None if no such caveats were found. :param ns: a Namespace, used to resolve caveats. :param ms: a list of pymacaroons.Macaroon :return: datetime.DateTime or None. ''' t ...
Returns the minimum time of any time-before caveats found in the given list or None if no such caveats were found. The ns parameter is :param ns: used to determine the standard namespace prefix - if the standard namespace is not found, the empty prefix is assumed. :param cavs: a list of pymacaroons...
def expiry_time(ns, cavs): ''' Returns the minimum time of any time-before caveats found in the given list or None if no such caveats were found. The ns parameter is :param ns: used to determine the standard namespace prefix - if the standard namespace is not found, the empty prefix is assumed. ...
Connect to the server. :param str url: server URL.
def connect(self, url): """Connect to the server. :param str url: server URL. """ headers = httputil.HTTPHeaders({'Content-Type': APPLICATION_JSON}) request = httpclient.HTTPRequest(url=url, connect_timeout=self.connect_timeout, ...
Send message to the server :param str data: message.
def send(self, data): """Send message to the server :param str data: message. """ if not self._ws_connection: raise RuntimeError('Web socket connection is closed.') self._ws_connection.write_message(json.dumps(data))
Replace multiple strings in a text. .. note:: Replacements are made successively, without any warranty on the order \ in which they are made. :param text: Text to replace in. :param replace_dict: Dictionary mapping strings to replace with their \ substitution. :returns: T...
def replace_all(text, replace_dict): """ Replace multiple strings in a text. .. note:: Replacements are made successively, without any warranty on the order \ in which they are made. :param text: Text to replace in. :param replace_dict: Dictionary mapping strings to replace with ...
Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The computed value or ``None``.
def map_or_apply(function, param): """ Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The computed value or ``None``. ...
Get items from a sequence a batch at a time. .. note: Adapted from https://code.activestate.com/recipes/303279-getting-items-in-batches/. .. note: All batches must be exhausted immediately. :params iterable: An iterable to get batches from. :params size: Size of the batches...
def batch(iterable, size): """ Get items from a sequence a batch at a time. .. note: Adapted from https://code.activestate.com/recipes/303279-getting-items-in-batches/. .. note: All batches must be exhausted immediately. :params iterable: An iterable to get batches from...
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens to have nice filenames. From Django's "django/template/defaultfilters.py". >>> slugify("El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su querido cachorro. ortez ce vieux ...
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens to have nice filenames. From Django's "django/template/defaultfilters.py". >>> slugify("El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su q...
Get the citations of a given preprint, in plain text. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in \ a c...
def get_plaintext_citations(arxiv_id): """ Get the citations of a given preprint, in plain text. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1...
Get the DOIs of the papers cited in a .bbl file. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in \ a canoni...
def get_cited_dois(arxiv_id): """ Get the DOIs of the papers cited in a .bbl file. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ...
Get subcommand options from global parsed arguments.
def get_subcommand_kwargs(mgr, name, namespace): """Get subcommand options from global parsed arguments. """ subcmd = mgr.get(name) subcmd_kwargs = {} for opt in list(subcmd.args.values()) + list(subcmd.options.values()): if hasattr(namespace, opt.dest): subcmd_kwargs[opt.des...
Parse a plaintext file to get a clean list of plaintext citations. The \ file should have one citation per line. :param file: Either the path to the plaintext file or the content of a \ plaintext file. :returns: A list of cleaned plaintext citations.
def get_plaintext_citations(file): """ Parse a plaintext file to get a clean list of plaintext citations. The \ file should have one citation per line. :param file: Either the path to the plaintext file or the content of a \ plaintext file. :returns: A list of cleaned plaintext...
Get the DOIs of the papers cited in a plaintext file. The file should \ have one citation per line. .. note:: This function is also used as a backend tool by most of the others \ citations processors, to factorize the code. :param file: Either the path to the plaintext file or the...
def get_cited_dois(file): """ Get the DOIs of the papers cited in a plaintext file. The file should \ have one citation per line. .. note:: This function is also used as a backend tool by most of the others \ citations processors, to factorize the code. :param file: Either...
Set name for SDC :param name: Name of SDC :param sdcObj: ScaleIO SDC object :return: POST request response :rtype: Requests POST response object
def set_sdc_name(self, name, sdcObj): """ Set name for SDC :param name: Name of SDC :param sdcObj: ScaleIO SDC object :return: POST request response :rtype: Requests POST response object """ # TODO: # Check if object parameters are the correct ones...
Get ScaleIO SDC object by its name :param name: Name of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified name found :rtype: SDC object
def get_sdc_by_name(self, name): """ Get ScaleIO SDC object by its name :param name: Name of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified name found :rtype: SDC object """ for sdc in self.sdc: if sdc.name == name: ...
Get ScaleIO SDC object by its id :param name: id of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified id found :rtype: SDC object
def get_sdc_by_id(self, id): """ Get ScaleIO SDC object by its id :param name: id of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified id found :rtype: SDC object """ for sdc in self.sdc: if sdc.id == id: re...
Get ScaleIO SDC object by its id :param name: guid of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified id found :rtype: SDC object
def get_sdc_by_guid(self, guid): """ Get ScaleIO SDC object by its id :param name: guid of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified id found :rtype: SDC object """ for sdc in self.sdc: if sdc.guid == guid: ...
Get ScaleIO SDC object by its ip :param name: IP address of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified IP found :rtype: SDC object
def get_sdc_by_ip(self, ip): """ Get ScaleIO SDC object by its ip :param name: IP address of SDC :return: ScaleIO SDC object :raise KeyError: No SDC with specified IP found :rtype: SDC object """ if self.conn.is_ip_addr(ip): for sdc in self.sdc...
Unregister SDC from MDM/SIO Cluster :param sdcObj: ScaleIO SDC object :return: POST request response :rtype: Requests POST response object
def unregisterSdc(self, sdcObj): """ Unregister SDC from MDM/SIO Cluster :param sdcObj: ScaleIO SDC object :return: POST request response :rtype: Requests POST response object """ # TODO: # Add code that unmap volume if mapped self.conn.connection....
Command execution.
def run(self): """Command execution.""" self.run_command('sdist') self.run_command('upload') os.system('git tag -a {0} -m \'version {0}\''.format(version)) os.system('git push --tags')
Check that a given string is a valid ISBN. :param isbn_id: the isbn to be checked. :returns: boolean indicating whether the isbn is valid or not. >>> is_valid("978-3-16-148410-0") True >>> is_valid("9783161484100") True >>> is_valid("9783161484100aa") False >>> is_valid("abcd") ...
def is_valid(isbn_id): """ Check that a given string is a valid ISBN. :param isbn_id: the isbn to be checked. :returns: boolean indicating whether the isbn is valid or not. >>> is_valid("978-3-16-148410-0") True >>> is_valid("9783161484100") True >>> is_valid("9783161484100aa") ...
Extract ISBNs from a text. :param text: Some text. :returns: A list of canonical ISBNs found in the text. >>> extract_from_text("978-3-16-148410-0 9783161484100 9783161484100aa abcd 0136091814 0136091812 9780136091817 123456789X") ['9783161484100', '9783161484100', '9783161484100', '0136091814', '1234...
def extract_from_text(text): """ Extract ISBNs from a text. :param text: Some text. :returns: A list of canonical ISBNs found in the text. >>> extract_from_text("978-3-16-148410-0 9783161484100 9783161484100aa abcd 0136091814 0136091812 9780136091817 123456789X") ['9783161484100', '97831614841...
Get a BibTeX string for the given ISBN. :param isbn_identifier: ISBN to fetch BibTeX entry for. :returns: A BibTeX string or ``None`` if could not fetch it. >>> get_bibtex('9783161484100') '@book{9783161484100,\\n title = {Berkeley, Oakland: Albany, Emeryville, Alameda, Kensington},\\n author =...
def get_bibtex(isbn_identifier): """ Get a BibTeX string for the given ISBN. :param isbn_identifier: ISBN to fetch BibTeX entry for. :returns: A BibTeX string or ``None`` if could not fetch it. >>> get_bibtex('9783161484100') '@book{9783161484100,\\n title = {Berkeley, Oakland: Albany, Eme...
Return options already used in the command line rtype: command.Option generator
def used_options(self): """Return options already used in the command line rtype: command.Option generator """ for option_str in filter(lambda c: c.startswith('-'), self.words): for option in list(self.cmd.options.values()): if option_str in option.op...
Return options that can be used given the current cmd line rtype: command.Option generator
def available_options(self): """Return options that can be used given the current cmd line rtype: command.Option generator """ for option in list(self.cmd.options.values()): if (option.is_multiple or option not in list(self.used_options)): ...
Return args already used in the command line rtype: command.Arg generator
def used_args(self): """Return args already used in the command line rtype: command.Arg generator """ # get all arguments values from the command line values = [] for idx, c in enumerate(self.words[1:]): if c.startswith('-'): continue ...
Return args that can be used given the current cmd line rtype: command.Arg generator
def available_args(self): """Return args that can be used given the current cmd line rtype: command.Arg generator """ used = list(self.used_args) logger.debug('Found used args: %s' % used) for arg in list(self.cmd.args.values()): if (arg.is_multiple o...
Returns true if the elem_ref is an element reference :param elem_ref: :return:
def is_elem_ref(elem_ref): """ Returns true if the elem_ref is an element reference :param elem_ref: :return: """ return ( elem_ref and isinstance(elem_ref, tuple) and len(elem_ref) == 3 and (elem_ref[0] == ElemRefObj or elem_ref[0] == ElemRefArr) )
Has element? :param elem_ref: :return:
def has_elem(elem_ref): """ Has element? :param elem_ref: :return: """ if not is_elem_ref(elem_ref): return False elif elem_ref[0] == ElemRefObj: return hasattr(elem_ref[1], elem_ref[2]) elif elem_ref[0] == ElemRefArr: return elem_ref[2] in elem_ref[1]
Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference. :param elem_ref: :param default: :return:
def get_elem(elem_ref, default=None): """ Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference. :param elem_ref: :param default: :return: """ if not is_elem_ref(elem_ref): return elem_ref elif elem_ref[0] == ElemRefObj: return g...
Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return:
def set_elem(elem_ref, elem): """ Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return: """ if elem_ref is None or elem_ref == elem or not is_elem_ref(elem_ref): return elem elif elem_ref[0] == ElemRefObj: setattr(elem_ref[1],...
Returns element reference :param obj: :param key: :param is_assoc: :return:
def eref(obj, key, is_assoc=None): """ Returns element reference :param obj: :param key: :param is_assoc: :return: """ if obj is None: return None if isinstance(key, int) or (is_assoc is not None and is_assoc): return ElemRefArr, get_elem(obj), key else: r...
Revise wording to match canonical and expected forms.
def _preprocess(inp): """Revise wording to match canonical and expected forms.""" inp = re.sub(r'(\b)a(\b)', r'\g<1>one\g<2>', inp) inp = re.sub(r'to the (.*) power', r'to \g<1>', inp) inp = re.sub(r'to the (.*?)(\b)', r'to \g<1>\g<2>', inp) inp = re.sub(r'log of', r'log', inp) ...
Calculates a final value given a set of numbers and symbols.
def _calculate(numbers, symbols): """Calculates a final value given a set of numbers and symbols.""" if len(numbers) is 1: return numbers[0] precedence = [[pow], [mul, div], [add, sub]] # Find most important operation for op_group in precedence: for i, o...
Solves the equation specified by the input string. Args: inp (str): An equation, specified in words, containing some combination of numbers, binary, and unary operations. Returns: The floating-point result of carrying out the computation.
def parseEquation(self, inp): """Solves the equation specified by the input string. Args: inp (str): An equation, specified in words, containing some combination of numbers, binary, and unary operations. Returns: The floating-point result of carrying out...
Registers a new command for a plugin. :param command: Name of the command :param description: Description of the command. Is used as help message on cli :param function: function reference, which gets invoked if command gets called. :param params: list of click options and arguments ...
def register(self, command, description, function, params=[]): """ Registers a new command for a plugin. :param command: Name of the command :param description: Description of the command. Is used as help message on cli :param function: function reference, which gets invoked if ...
Returns commands, which can be filtered by name. :param name: name of the command :type name: str :return: None, single command or dict of commands
def get(self, name=None): """ Returns commands, which can be filtered by name. :param name: name of the command :type name: str :return: None, single command or dict of commands """ return self.app.commands.get(name, self.plugin)
Returns commands, which can be filtered by name or plugin. :param name: name of the command :type name: str :param plugin: plugin object, which registers the commands :type plugin: instance of GwBasePattern :return: None, single command or dict of commands
def get(self, name=None, plugin=None): """ Returns commands, which can be filtered by name or plugin. :param name: name of the command :type name: str :param plugin: plugin object, which registers the commands :type plugin: instance of GwBasePattern :return: None...
Registers a new command, which can be used on a command line interface (cli). :param command: Name of the command :param description: Description of the command. Is used as help message on cli :param function: function reference, which gets invoked if command gets called. :param params:...
def register(self, command, description, function, params=[], plugin=None): """ Registers a new command, which can be used on a command line interface (cli). :param command: Name of the command :param description: Description of the command. Is used as help message on cli :param...
Unregisters an existing command, so that this command is no longer available on the command line interface. This function is mainly used during plugin deactivation. :param command: Name of the command
def unregister(self, command): """ Unregisters an existing command, so that this command is no longer available on the command line interface. This function is mainly used during plugin deactivation. :param command: Name of the command """ if command not in self._comman...
SMTP 'rcpt' command -- indicates 1 recipient for this mail.
def rcpt(self, recip, options=[]): """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" optionlist = '' if options and self.does_esmtp: optionlist = ' ' + ' '.join(options) code, msg = yield self.docmd(b"rcpt", ("TO:%s%s" % (smtplib.quoteaddr(recip), optionlist))...
SMTP 'DATA' command -- sends message data to server.
def data(self, msg): """SMTP 'DATA' command -- sends message data to server. """ (code, repl) = yield self.docmd(b"data") if code != 354: raise smtplib.SMTPDataError(code, repl) else: if isinstance(msg, str): msg = smtplib._fix_eols(msg).encode('...
Returns a "declared" caveat asserting that the given key is set to the given value. If a macaroon has exactly one first party caveat asserting the value of a particular key, then infer_declared will be able to infer the value, and then the check will allow the declared value if it has the value spe...
def declared_caveat(key, value): '''Returns a "declared" caveat asserting that the given key is set to the given value. If a macaroon has exactly one first party caveat asserting the value of a particular key, then infer_declared will be able to infer the value, and then the check will allow the de...
Helper for allow_caveat and deny_caveat. It checks that all operation names are valid before creating the caveat.
def _operation_caveat(cond, ops): ''' Helper for allow_caveat and deny_caveat. It checks that all operation names are valid before creating the caveat. ''' for op in ops: if op.find(' ') != -1: return error_caveat('invalid operation name "{}"'.format(op)) return _first_party(con...
Return a caveat that specifies that the time that it is checked at should be before t. :param t is a a UTC date in - use datetime.utcnow, not datetime.now
def time_before_caveat(t): '''Return a caveat that specifies that the time that it is checked at should be before t. :param t is a a UTC date in - use datetime.utcnow, not datetime.now ''' return _first_party(COND_TIME_BEFORE, pyrfc3339.generate(t, accept_naive=True, ...
Parses a caveat into an identifier, identifying the checker that should be used, and the argument to the checker (the rest of the string). The identifier is taken from all the characters before the first space character. :return two string, identifier and arg
def parse_caveat(cav): ''' Parses a caveat into an identifier, identifying the checker that should be used, and the argument to the checker (the rest of the string). The identifier is taken from all the characters before the first space character. :return two string, identifier and arg ''' ...
Return s as a bytes type, using utf-8 encoding if necessary. @param s string or bytes @return bytes
def to_bytes(s): '''Return s as a bytes type, using utf-8 encoding if necessary. @param s string or bytes @return bytes ''' if isinstance(s, six.binary_type): return s if isinstance(s, six.string_types): return s.encode('utf-8') raise TypeError('want string or bytes, got {}',...
Base64 decodes a base64-encoded string in URL-safe or normal format, with or without padding. The argument may be string or bytes. @param s bytes decode @return bytes decoded @raises ValueError on failure
def b64decode(s): '''Base64 decodes a base64-encoded string in URL-safe or normal format, with or without padding. The argument may be string or bytes. @param s bytes decode @return bytes decoded @raises ValueError on failure ''' # add padding if necessary. s = to_bytes(s) if no...
Base64 encode using URL-safe encoding with padding removed. @param b bytes to decode @return bytes decoded
def raw_urlsafe_b64encode(b): '''Base64 encode using URL-safe encoding with padding removed. @param b bytes to decode @return bytes decoded ''' b = to_bytes(b) b = base64.urlsafe_b64encode(b) b = b.rstrip(b'=') # strip padding return b
Return a new Cookie using a slightly more friendly API than that provided by six.moves.http_cookiejar @param name The cookie name {str} @param value The cookie value {str} @param url The URL path of the cookie {str} @param expires The expiry time of the cookie {datetime}. If provided, it mu...
def cookie( url, name, value, expires=None): '''Return a new Cookie using a slightly more friendly API than that provided by six.moves.http_cookiejar @param name The cookie name {str} @param value The cookie value {str} @param url The URL path of the cookie {str} ...
LOGIN CAN ONLY BE DONE BY POSTING TO A HTTP FORM. A COOKIE IS THEN USED FOR INTERACTING WITH THE API
def _login(self): """ LOGIN CAN ONLY BE DONE BY POSTING TO A HTTP FORM. A COOKIE IS THEN USED FOR INTERACTING WITH THE API """ self.logger.debug("Logging into " + "{}/{}".format(self._im_api_url, "j_spring_security_check")) self._im_session.headers.update({'Content-Type':...
Convinient method for GET requests Returns http request status value from a POST request
def _do_get(self, uri, **kwargs): """ Convinient method for GET requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_get_head...
Convinient method for POST requests Returns http request status value from a POST request
def _do_put(self, uri, **kwargs): """ Convinient method for POST requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_put_hea...
Convinient method for POST requests Returns http request status value from a POST request
def _do_post(self, url, **kwargs): """ Convinient method for POST requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_post_h...
Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST
def set_abort_pending(self, newstate): """ Method to set Abort state if something goes wrong during provisioning Method also used to finish provisioning process when all is completed Method: POST """ self.logger.debug("set_abort_pending(" + "{})".format(newstate)) ...
Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM) Method: POST Attach JSON cluster configuration as request payload (data). Add MDM and LIA passwords)
def push_cached_cluster_configuration(self, mdmPassword, liaPassword, noUpload = False, noInstall= False, noConfigure = False): """ Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM) Method: POST At...
Using IM this method create a 3-node ScaleIO cluster with 2xMDM, 1xTB, 3x SDS (using /dev/sdb), 3x SDC
def create_minimal_scaleio_cluster(self, mdmPassword, liaPassword): """ Using IM this method create a 3-node ScaleIO cluster with 2xMDM, 1xTB, 3x SDS (using /dev/sdb), 3x SDC """ """ self.read_cluster_config_from_disk("minimal-cluster.json") #self._cluster_config_cached.s...
Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM) Method: POST Attach JSON cluster configuration as request payload (data). Add MDM and LIA passwords)
def push_cluster_configuration(self, scaleioobj, noUpload = False, noInstall= False, noConfigure = False): """ Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM) Method: POST Attach JSON cluster con...