INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Use the requests library to make a request. Using this method is like doing:
def request(self, method, url, **kwargs): '''Use the requests library to make a request. Using this method is like doing: requests.request(method, url, auth=client.auth()) ''' # TODO should we raise an exception if auth or cookies are explicitly # mentioned in kwargs...
Try to resolve the given error which should be a response to the given URL by discharging any macaroon contained in it. That is if error. code is ERR_DISCHARGE_REQUIRED then it will try to discharge err. info. macaroon. If the discharge succeeds the discharged macaroon will be saved to the client s cookie jar otherwise...
def handle_error(self, error, url): '''Try to resolve the given error, which should be a response to the given URL, by discharging any macaroon contained in it. That is, if error.code is ERR_DISCHARGE_REQUIRED then it will try to discharge err.info.macaroon. If the discharge succ...
Request a discharge macaroon from the caveat location as an HTTP URL.
def acquire_discharge(self, cav, payload): ''' Request a discharge macaroon from the caveat location as an HTTP URL. @param cav Third party {pymacaroons.Caveat} to be discharged. @param payload External caveat data {bytes}. @return The acquired macaroon {macaroonbakery.Macaroon} ...
Gathers a macaroon by directing the user to interact with a web page. The error_info argument holds the interaction - required error response.
def _interact(self, location, error_info, payload): '''Gathers a macaroon by directing the user to interact with a web page. The error_info argument holds the interaction-required error response. @return DischargeToken, bakery.Macaroon ''' if (self._interaction_methods is...
Generates a random secret exponent.
def random_secret_exponent(curve_order): """ Generates a random secret exponent. """ # run a rejection sampling algorithm to ensure the random int is less # than the curve order while True: # generate a random 256 bit hex string random_hex = hexlify(dev_urandom_entropy(32)) rando...
Convert a single BibTeX entry dict to a BibTeX string.
def dict2bibtex(data): """ Convert a single BibTeX entry dict to a BibTeX string. :param data: A dict representing BibTeX entry, as the ones from \ ``bibtexparser.BibDatabase.entries`` output. :return: A formatted BibTeX string. """ bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'...
Create a new BibTeX file.
def write(filename, data): """ Create a new BibTeX file. :param filename: The name of the BibTeX file to write. :param data: A ``bibtexparser.BibDatabase`` object. """ with open(filename, 'w') as fh: fh.write(bibdatabase2bibtex(data))
Update an entry in a BibTeX file.
def edit(filename, identifier, data): """ Update an entry in a BibTeX file. :param filename: The name of the BibTeX file to edit. :param identifier: The id of the entry to update, in the BibTeX file. :param data: A dict associating fields and updated values. Fields present \ in the BibT...
Delete an entry in a BibTeX file.
def delete(filename, identifier): """ Delete an entry in a BibTeX file. :param filename: The name of the BibTeX file to edit. :param identifier: The id of the entry to delete, in the BibTeX file. """ # Get current bibtex with open(filename, 'r') as fh: bibtex = bibtexparser.load(fh)...
Get all entries from a BibTeX file.
def get(filename, ignore_fields=None): """ Get all entries from a BibTeX file. :param filename: The name of the BibTeX file. :param ignore_fields: An optional list of fields to strip from the BibTeX \ file. :returns: A ``bibtexparser.BibDatabase`` object representing the fetched \ ...
Get an entry from a BibTeX file.
def get_entry_by_filter(filename, filter_function, ignore_fields=None): """ Get an entry from a BibTeX file. .. note :: Returns the first matching entry. :param filename: The name of the BibTeX file. :param filter_function: A function returning ``True`` or ``False`` \ whether ...
Get an entry from a BibTeX file.
def get_entry(filename, identifier, ignore_fields=None): """ Get an entry from a BibTeX file. :param filename: The name of the BibTeX file. :param identifier: An id of the entry to fetch, in the BibTeX file. :param ignore_fields: An optional list of fields to strip from the BibTeX \ fil...
Convert a bibtex entry to a formatted filename according to a given mask.
def to_filename(data, mask=DEFAULT_PAPERS_FILENAME_MASK, extra_formatters=None): """ Convert a bibtex entry to a formatted filename according to a given mask. .. note :: Available formatters out of the box are: - ``journal`` - ``title`` ...
Constant - width integer serialization: param reader:: param width:: return:
async def load_uint(reader, width): """ Constant-width integer serialization :param reader: :param width: :return: """ buffer = _UINT_BUFFER result = 0 shift = 0 for _ in range(width): await reader.areadinto(buffer) result += buffer[0] << shift shift += 8 ...
Constant - width integer serialization: param writer:: param n:: param width:: return:
async def dump_uint(writer, n, width): """ Constant-width integer serialization :param writer: :param n: :param width: :return: """ buffer = _UINT_BUFFER for _ in range(width): buffer[0] = n & 0xff await writer.awrite(buffer) n >>= 8
Variable int deserialization synchronous from buffer.: param buffer:: return:
def load_uvarint_b(buffer): """ Variable int deserialization, synchronous from buffer. :param buffer: :return: """ result = 0 idx = 0 byte = 0x80 while byte & 0x80: byte = buffer[idx] result += (byte & 0x7F) << (7 * idx) idx += 1 return result
Serializes n as variable size integer to the provided buffer. Buffer has to ha: param n:: param buffer:: param offset:: return:
def dump_uvarint_b_into(n, buffer, offset=0): """ Serializes n as variable size integer to the provided buffer. Buffer has to ha :param n: :param buffer: :param offset: :return: """ shifted = True while shifted: shifted = n >> 7 buffer[offset] = (n & 0x7F) | (0x80...
Loads fixed size integer from the buffer: param buffer:: return:
def load_uint_b(buffer, width): """ Loads fixed size integer from the buffer :param buffer: :return: """ result = 0 for idx in range(width): result += buffer[idx] << (8 * idx) return result
Serializes fixed size integer to the buffer: param n:: param width:: return:
def dump_uint_b_into(n, width, buffer, offset=0): """ Serializes fixed size integer to the buffer :param n: :param width: :return: """ for idx in range(width): buffer[idx + offset] = n & 0xff n >>= 8 return buffer
Bind field to its name in model class.
def bind_name(self, name): """Bind field to its name in model class.""" if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', se...
Bind field to model class.
def bind_model_cls(self, model_cls): """Bind field to model class.""" if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls))...
Init model with field.
def init_model(self, model, value): """Init model with field. :param DomainModel model: :param object value: """ if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value)
Return field s value.
def get_value(self, model, default=None): """Return field's value. :param DomainModel model: :param object default: :rtype object: """ if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return...
Set field s value.
def set_value(self, model, value): """Set field's value. :param DomainModel model: :param object value: """ if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) ...
Convert dict into object of class of passed model.
def _get_model_instance(model_cls, data): """Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel: """ if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of...
Convert raw input value of the field.
def _converter(self, value): """Convert raw input value of the field.""" if not isinstance(value, datetime.date): raise TypeError('{0} is not valid date'.format(value)) return value
Convert raw input value of the field.
def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ if type(value) is not self.related_model_cls.Collection: value = self.related_model_cls.Collection([ self._get_model_instance(self.related_mo...
Return built - in type representation of Collection.
def get_builtin_type(self, model): """Return built-in type representation of Collection. :param DomainModel model: :rtype list: """ return [item.get_data() if isinstance(item, self.related_model_cls) else item for item in self.get_value(model)]
Parse the docstring into its components.
def parse(text): """ Parse the docstring into its components. :returns: parsed docstring """ ret = Docstring() if not text: return ret text = inspect.cleandoc(text) match = re.search('^:', text, flags=re.M) if match: desc_chunk = text[:match.start()] meta_ch...
Copy DocstringMeta from another instance.
def from_meta(cls, meta, meta_all=None): """Copy DocstringMeta from another instance.""" if len(meta.args) == 2: name = meta.args[1] meta_type = None for x in meta_all: if x.args[1] == name and x.args[0] == 'type': meta_type = x.des...
Return argument name associated with given param.
def arg_name(self): """Return argument name associated with given param.""" if len(self.args) > 2: return self.args[2] elif len(self.args) > 1: return self.args[1] return None
Return list of: param meta.
def params(self): """Return list of :param meta.""" return [ DocstringParam.from_meta(meta, self.meta) for meta in self.meta if meta.args[0] in { 'param', 'parameter', 'arg', 'argument', 'key', 'keyword' } ]
Return list of: raises meta.
def raises(self): """Return list of :raises meta.""" return [ DocstringRaises.from_meta(meta) for meta in self.meta if meta.args[0] in {'raises', 'raise', 'except', 'exception'} ]
Getter function to retrieve objects from a given object dictionary.
def gw_get(object_dict, name=None, plugin=None): """ Getter function to retrieve objects from a given object dictionary. Used mainly to provide get() inside patterns. :param object_dict: objects, which must have 'name' and 'plugin' as attribute :type object_dict: dictionary :param name: name o...
Handles a discharge request as received by the/ discharge endpoint.
def discharge(ctx, content, key, locator, checker): '''Handles a discharge request as received by the /discharge endpoint. @param ctx The context passed to the checker {checkers.AuthContext} @param content URL and form parameters {dict} @param locator Locator used to add third party caveats returned...
Handle 404 errors returned by the API server
def http_error_handler(f): """Handle 404 errors returned by the API server """ def hrefs_to_resources(hrefs): for href in hrefs.replace(',', '').split(): type, uuid = href.split('/')[-2:] yield Resource(type, uuid=uuid) def hrefs_list_to_resources(hrefs_list): f...
Return URL of the resource
def href(self): """Return URL of the resource :rtype: str """ url = self.session.base_url + str(self.path) if self.path.is_collection and not self.path.is_root: return url + 's' return url
Add permanent filter on the collection
def filter(self, field_name, field_value): """Add permanent filter on the collection :param field_name: name of the field to filter on :type field_name: str :param field_value: value to filter on :rtype: Collection """ self.filters.append((field_name, field_valu...
Fetch collection from API server
def fetch(self, recursive=1, fields=None, detail=None, filters=None, parent_uuid=None, back_refs_uuid=None): """ Fetch collection from API server :param recursive: level of recursion :type recursive: int :param fields: fetch only listed fields. ...
Check that the resource exists.
def check(self): """Check that the resource exists. :raises ResourceNotFound: if the resource doesn't exists """ if self.fq_name: self['uuid'] = self._check_fq_name(self.fq_name) elif self.uuid: self['fq_name'] = self._check_uuid(self.uuid) return...
Return FQDN of the resource
def fq_name(self): """Return FQDN of the resource :rtype: FQName """ return self.get('fq_name', self.get('to', super(Resource, self).fq_name))
Return parent resource
def parent(self): """Return parent resource :rtype: Resource :raises ResourceNotFound: parent resource doesn't exists :raises ResourceMissing: parent resource is not defined """ try: return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True) ...
Set parent resource
def parent(self, resource): """Set parent resource :param resource: parent resource :type resource: Resource :raises ResourceNotFound: resource not found on the API """ resource.check() self['parent_type'] = resource.type self['parent_uuid'] = resource.u...
Return creation date
def created(self): """Return creation date :rtype: datetime :raises ResourceNotFound: resource not found on the API """ if 'id_perms' not in self: self.fetch() created = self['id_perms']['created'] return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S....
Save the resource to the API server
def save(self): """Save the resource to the API server If the resource doesn't have a uuid the resource will be created. If uuid is present the resource is updated. :rtype: Resource """ if self.path.is_collection: self.session.post_json(self.href, ...
Delete resource from the API server
def delete(self): """Delete resource from the API server """ res = self.session.delete(self.href) self.emit('deleted', self) return res
Fetch resource from the API server
def fetch(self, recursive=1, exclude_children=False, exclude_back_refs=False): """Fetch resource from the API server :param recursive: level of recursion for fetching resources :type recursive: int :param exclude_children: don't get children references :type exclude_children: bo...
Populate the resource from a python dict
def from_dict(self, data, recursive=1): """Populate the resource from a python dict :param recursive: level of recursion for fetching resources :type recursive: int """ # Find other linked resources data = self._encode_resource(data, recursive=recursive) self.dat...
Remove reference from self to ref
def remove_ref(self, ref): """Remove reference from self to ref >>> iip = Resource('instance-ip', uuid='30213cf9-4b03-4afc-b8f9-c9971a216978', fetch=True) >>> for vmi in iip['virtual_machine_interface_refs']: iip.remove_ref(v...
Set reference to resource
def set_ref(self, ref, attr=None): """Set reference to resource Can be used to set references on a resource that is not already created. :param ref: reference to add :type ref: Resource :rtype: Resource """ ref_attr = '%s_refs' % ref.type.replace('-', '...
Add reference to resource
def add_ref(self, ref, attr=None): """Add reference to resource :param ref: reference to add :type ref: Resource :rtype: Resource """ self.session.add_ref(self, ref, attr) return self.fetch()
Add reference from back_ref to self
def add_back_ref(self, back_ref, attr=None): """Add reference from back_ref to self :param back_ref: back_ref to add :type back_ref: Resource :rtype: Resource """ back_ref.add_ref(self, attr) return self.fetch()
Search in cache
def _search(self, trie, strings, limit=None): """Search in cache :param strings: list of strings to get from the cache :type strings: str list :param limit: limit search results :type limit: int :rtype: [Resource | Collection] """ results = [trie.has_key...
Registers a new signal.
def register(self, signal, plugin, description=""): """ Registers a new signal. :param signal: Unique name of the signal :param plugin: Plugin, which registers the new signal :param description: Description of the reason or use case, why this signal is needed. ...
Unregisters an existing signal
def unregister(self, signal): """ Unregisters an existing signal :param signal: Name of the signal """ if signal in self.signals.keys(): del(self.signals[signal]) self.__log.debug("Signal %s unregisterd" % signal) else: self.__log.debu...
Connect a receiver to a signal
def connect(self, receiver, signal, function, plugin, 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 :para...
Disconnect a receiver from a signal. Signal and receiver must exist otherwise an exception is thrown.
def disconnect(self, receiver): """ Disconnect a receiver from a signal. Signal and receiver must exist, otherwise an exception is thrown. :param receiver: Name of the receiver """ if receiver not in self.receivers.keys(): raise Exception("No receiver %s was ...
Sends a signal for the given plugin.
def send(self, signal, plugin, **kwargs): """ Sends a signal for the given plugin. :param signal: Name of the signal :type signal: str :param plugin: Plugin object, under which the signals where registered :type plugin: GwBasePattern """ if signal not in ...
Get one or more signals.
def get(self, signal=None, plugin=None): """ Get one or more signals. :param signal: Name of the signal :type signal: str :param plugin: Plugin object, under which the signals where registered :type plugin: GwBasePattern """ if plugin is not None: ...
Get one or more receivers.
def get_receiver(self, receiver=None, plugin=None): """ Get one or more receivers. :param receiver: Name of the signal :type receiver: str :param plugin: Plugin object, under which the signals where registered :type plugin: GwBasePattern """ if plugin is ...
Starts the listener with incoming and outgoing queues.
def start(inqueue, outqueue=None): """Starts the listener with incoming and outgoing queues.""" conf.init(), db.init(conf.DbPath) Listener(inqueue, outqueue).run()
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:
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.
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.
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.
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.
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: ...
Serialize the transaction: param ar:: type ar: x. Archive: return:
async def serialize_archive(self, ar, version=None): """ Serialize the transaction :param ar: :type ar: x.Archive :return: """ # Transaction prefix serialization first. await ar.message(self, TransactionPrefix) if self.version == 1: aw...
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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.
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.
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...