INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
A basic operation operating on a single value.
def _op(self, operation, other, *allowed): """A basic operation operating on a single value.""" f = self._field if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz). return reduce(self._combining, (q._op(operation, other, *allowed) for q in f)) # pylint:disable=pr...
An iterative operation operating on multiple values. Consumes iterators to construct a concrete list at time of execution.
def _iop(self, operation, other, *allowed): """An iterative operation operating on multiple values. Consumes iterators to construct a concrete list at time of execution. """ f = self._field if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz). return reduce(self....
Allow for the projection ( and update ) of nested values contained within the single match of an array. Projection operator: https:// docs. mongodb. com/ manual/ reference/ operator/ projection/ positional/ #proj. _S_ Array update operator: https:// docs. mongodb. com/ manual/ reference/ operator/ update/ positional/
def S(self): """Allow for the projection (and update) of nested values contained within the single match of an array. Projection operator: https://docs.mongodb.com/manual/reference/operator/projection/positional/#proj._S_ Array update operator: https://docs.mongodb.com/manual/reference/operator/update/position...
Matches string values against a regular expression compiled of individual parts. Document. field. re ( r ^ variable_part r \\. ) Regex operator: { $regex: value } Documentation: https:// docs. mongodb. com/ manual/ reference/ operator/ query/ regex/
def re(self, *parts): """Matches string values against a regular expression compiled of individual parts. Document.field.re(r'^', variable_part, r'\\.') Regex operator: {$regex: value} Documentation: https://docs.mongodb.com/manual/reference/operator/query/regex/ """ if self._combining: # We are ...
Selects documents if element in the array field matches all the specified conditions. Document. field. match (... ) Array operator: { $elemMatch: value } Documentation: https:// docs. mongodb. org/ manual/ reference/ operator/ query/ elemMatch/ #op. _S_elemMatch
def match(self, q): """Selects documents if element in the array field matches all the specified conditions. Document.field.match(...) Array operator: {$elemMatch: value} Documentation: https://docs.mongodb.org/manual/reference/operator/query/elemMatch/#op._S_elemMatch """ if self._combining: # W...
Matches values that are between a minimum and maximum value semi - inclusive. Document. field. range ( 4 12 ) This will find documents with a field whose value is greater than or equal to 4 and less than 12. Comparison operator: { $gte: gte $lt: lt }
def range(self, gte, lt): """Matches values that are between a minimum and maximum value, semi-inclusive. Document.field.range(4, 12) This will find documents with a field whose value is greater than or equal to 4, and less than 12. Comparison operator: {$gte: gte, $lt: lt} """ if self._combini...
Selects documents if the array field is a specified size. Document. field. size ( 5 ) Array operator: { $size: value } Documentation: https:// docs. mongodb. org/ manual/ reference/ operator/ query/ size/ #op. _S_size
def size(self, value): """Selects documents if the array field is a specified size. Document.field.size(5) Array operator: {$size: value} Documentation: https://docs.mongodb.org/manual/reference/operator/query/size/#op._S_size """ if self._combining: # We are a field-compound query fragment, e.g....
Selects documents if a field is of the correct type. Document. field. of_type () Document. field. of_type ( string ) Element operator: { $type: self. __foreign__ } Documentation: https:// docs. mongodb. org/ manual/ reference/ operator/ query/ type/ #op. _S_type
def of_type(self, *kinds): """Selects documents if a field is of the correct type. Document.field.of_type() Document.field.of_type('string') Element operator: {$type: self.__foreign__} Documentation: https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type """ if self._combinin...
Order results by their distance from the given point optionally with range limits in meters. Geospatial operator: { $near: {... }} Documentation: https:// docs. mongodb. com/ manual/ reference/ operator/ query/ near/ #op. _S_near { $near: { $geometry: <center ; Point or ( long lat ) > $minDistance: <min ; distance in m...
def near(self, center, sphere=False, min=None, max=None): """Order results by their distance from the given point, optionally with range limits in meters. Geospatial operator: {$near: {...}} Documentation: https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near { $near: { $geom...
Select geometries within a bounding GeoJSON geometry. Documentation: https:// docs. mongodb. com/ manual/ reference/ operator/ query/ geoWithin/ #op. _S_geoWithin Geospatial operator: { $geoWithin: { $geometry:... }}} Documentation: https:// docs. mongodb. com/ manual/ reference/ operator/ query/ geometry/ #op. _S_geom...
def within(self, geometry=None, center=None, sphere=None, radius=None, box=None, polygon=None, crs=None): """Select geometries within a bounding GeoJSON geometry. Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/#op._S_geoWithin Geospatial operator: {$geoWithin: {$geometry: ...
Select geometries that intersect with a GeoJSON geometry. Geospatial operator: { $geoIntersects: {... }} Documentation: https:// docs. mongodb. com/ manual/ reference/ operator/ query/ geoIntersects/ #op. _S_geoIntersects { $geoIntersects: { $geometry: <geometry ; a GeoJSON object > } }
def intersects(self, geometry, crs=None): """Select geometries that intersect with a GeoJSON geometry. Geospatial operator: {$geoIntersects: {...}} Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects { $geoIntersects: { $geometry: <geometry; a Ge...
we recursively run dfs on each vertices in free_vertex
def __dfs(self, v, index, layers): """ we recursively run dfs on each vertices in free_vertex, :param v: vertices in free_vertex :return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k) and false otherwise. """ if in...
Gets ( and create if not exists ) as named symbol.
def symbol(self, ident, bp=0): ''' Gets (and create if not exists) as named symbol. Optionally, you can specify a binding power (bp) value, which will be used to control operator presedence; the higher the value, the tighter a token binds to the tokens that follow. ''' ...
Symbol decorator.
def method(self, symbol): ''' Symbol decorator. ''' assert issubclass(symbol, SymbolBase) def wrapped(fn): setattr(symbol, fn.__name__, fn) return wrapped
Simple date parsing function
def _simpleparsefun(date): """Simple date parsing function""" if hasattr(date, 'year'): return date try: date = datetime.datetime.strptime(date, '%Y-%m-%d') except ValueError: date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') return date
Check if a given date is a work date ignoring holidays. Args: date ( date datetime or str ): Date to be checked. Returns: bool: True if the date is a work date False otherwise.
def isworkday(self, date): """ Check if a given date is a work date, ignoring holidays. Args: date (date, datetime or str): Date to be checked. Returns: bool: True if the date is a work date, False otherwise. """ date = parsefun(date) ...
Check if a given date is a holiday. Args: date ( date datetime or str ): Date to be checked. Returns: bool: True if the date is a holiday False otherwise.
def isholiday(self, date): """ Check if a given date is a holiday. Args: date (date, datetime or str): Date to be checked. Returns: bool: True if the date is a holiday, False otherwise. """ date = parsefun(date) if self.holiday...
Adjust the date to the closest work date. Args: date ( date datetime or str ): Date to be adjusted. mode ( integer ): FOLLOWING PREVIOUS or MODIFIEDFOLLOWING. Note: If date is already a business date than it is returned unchanged. How to use the adjustment constants: ** FOLLOWING **: Adjust to the next business date. *...
def adjust(self, date, mode): """ Adjust the date to the closest work date. Args: date (date, datetime or str): Date to be adjusted. mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING. Note: If date is already a business date than it i...
Add work days to a given date ignoring holidays. Note: By definition a zero offset causes the function to return the initial date even it is not a work date. An offset of 1 represents the next work date regardless of date being a work date or not. Args: date ( date datetime or str ): Date to be incremented. offset ( in...
def addworkdays(self, date, offset): """ Add work days to a given date, ignoring holidays. Note: By definition, a zero offset causes the function to return the initial date, even it is not a work date. An offset of 1 represents the next work date, rega...
Add business days to a given date taking holidays into consideration. Note: By definition a zero offset causes the function to return the initial date even it is not a business date. An offset of 1 represents the next business date regardless of date being a business date or not. Args: date ( date datetime or str ): Da...
def addbusdays(self, date, offset): """ Add business days to a given date, taking holidays into consideration. Note: By definition, a zero offset causes the function to return the initial date, even it is not a business date. An offset of 1 represents ...
( PRIVATE ) Count work days between two dates ignoring holidays.
def _workdaycount(self, date1, date2): """ (PRIVATE) Count work days between two dates, ignoring holidays. """ assert date2 >= date1 date1wd = date1.weekday() date2wd = date2.weekday() if not self.weekdaymap[date2wd].isworkday: date2 += datetim...
Count work days between two dates ignoring holidays. Args: date1 ( date datetime or str ): Date start of interval. date2 ( date datetime or str ): Date end of interval. Note: The adopted notation is COB to COB so effectively date1 is not included in the calculation result. Example: >>> cal = Calendar () >>> date1 = dat...
def workdaycount(self, date1, date2): """ Count work days between two dates, ignoring holidays. Args: date1 (date, datetime or str): Date start of interval. date2 (date, datetime or str): Date end of interval. Note: The adopted notation is C...
Count business days between two dates ( private ) taking holidays into consideration. Args: date1 ( date datetime or str ): Date start of interval. date2 ( date datetime or str ): Date end of interval. Note: The adopted notation is COB to COB so effectively date1 is not included in the calculation result. Example: >>> ...
def busdaycount(self, date1, date2): """ Count business days between two dates (private), taking holidays into consideration. Args: date1 (date, datetime or str): Date start of interval. date2 (date, datetime or str): Date end of interval. Note:...
Adjust date to last day of the month regardless of work days. Args: date ( date datetime or str ): Date to be adjusted. Returns: datetime: Adjusted date.
def caleom(date): """ Adjust date to last day of the month, regardless of work days. Args: date (date, datetime or str): Date to be adjusted. Returns: datetime: Adjusted date. """ date = parsefun(date) date += datetime.timedelt...
Generate business days between two dates taking holidays into consideration. Args: date1 ( date datetime or str ): Date start of interval. date2 ( date datetime or str ): Date end of interval not included. Note: All business days between date1 ( inc ) and date2 ( exc ) are returned and date2 must be bigger than date1. ...
def range(self, date1, date2): """ Generate business days between two dates, taking holidays into consideration. Args: date1 (date, datetime or str): Date start of interval. date2 (date, datetime or str): Date end of interval, not included. Note...
Connect signal to current model
def _connect(cls): """ Connect signal to current model """ post_save.connect( notify_items, sender=cls, dispatch_uid='knocker_{0}'.format(cls.__name__) )
Disconnect signal from current model
def _disconnect(cls): """ Disconnect signal from current model """ post_save.disconnect( notify_items, sender=cls, dispatch_uid='knocker_{0}'.format(cls.__name__) )
Returns a dictionary with the knock data built from _knocker_data
def as_knock(self, created=False): """ Returns a dictionary with the knock data built from _knocker_data """ knock = {} if self.should_knock(created): for field, data in self._retrieve_data(None, self._knocker_data): knock[field] = data return ...
Send the knock in the associated channels Group
def send_knock(self, created=False): """ Send the knock in the associated channels Group """ knock = self.as_knock(created) if knock: gr = Group('knocker-{0}'.format(knock['language'])) gr.send({'text': json.dumps(knock)})
Colorize some message with ANSI colors specification
def colorize(printable, color, style='normal', autoreset=True): """Colorize some message with ANSI colors specification :param printable: interface whose has __str__ or __repr__ method :param color: the colors defined in COLOR_MAP to colorize the text :style: can be 'normal', 'bold' or 'underline' ...
Function: cache Summary: Decorator used to cache the input - > output Examples: An fib memoized executes at O ( 1 ) time instead O ( e^n ) Attributes: @param ( function ): function Returns: wrapped function
def cache(function): """ Function: cache Summary: Decorator used to cache the input->output Examples: An fib memoized executes at O(1) time instead O(e^n) Attributes: @param (function): function Returns: wrapped function TODO: Give support to functions with kwargs ...
Change text color for the linux terminal defaults to green. Set warning = True for red.
def color(string, status=True, warning=False, bold=True): """ Change text color for the linux terminal, defaults to green. Set "warning=True" for red. """ attr = [] if status: # green attr.append('32') if warning: # red attr.append('31') if bold: a...
A generator which will block and yield entries as they are added to a capped collection. Only use this on capped collections ; behaviour is undefined against non - tailable cursors. Accepts a timeout as an integer or floating point number of seconds indicating how long to wait for a result. Correct operation requires a...
def tail(collection, filter=None, projection=None, limit=0, timeout=None, aggregate=False): """A generator which will block and yield entries as they are added to a capped collection. Only use this on capped collections; behaviour is undefined against non-tailable cursors. Accepts a timeout as an integer or floati...
Patch pymongo s Collection object to add a tail method. While not nessicarily recommended you can use this to inject tail as a method into Collection making it generally accessible.
def _patch(): """Patch pymongo's Collection object to add a tail method. While not nessicarily recommended, you can use this to inject `tail` as a method into Collection, making it generally accessible. """ if not __debug__: # pragma: no cover import warnings warnings.warn("A catgirl has died.", ImportWar...
Process arguments to query methods. For internal use only. Positional arguments are treated as query components combined using boolean AND reduction. Keyword arguments are processed depending on the passed in mapping and set of valid options with non - option arguments treated as parametric query components also ANDed ...
def _prepare_query(cls, mapping, valid, *args, **kw): """Process arguments to query methods. For internal use only. Positional arguments are treated as query components, combined using boolean AND reduction. Keyword arguments are processed depending on the passed in mapping and set of valid options, with no...
Execute a find and return the resulting queryset using combined plain and parametric query generation. Additionally performs argument case normalization refer to the _prepare_query method s docstring.
def _prepare_find(cls, *args, **kw): """Execute a find and return the resulting queryset using combined plain and parametric query generation. Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring. """ cls, collection, query, options = cls._prepare_query( ...
Generate and execute an aggregate query pipline using combined plain and parametric query generation. Additionally performs argument case normalization refer to the _prepare_query method s docstring. This provides a find - like interface for generating aggregate pipelines with a few shortcuts that make aggregates behav...
def _prepare_aggregate(cls, *args, **kw): """Generate and execute an aggregate query pipline using combined plain and parametric query generation. Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring. This provides a find-like interface for generating aggregat...
Query the collection this class is bound to. Additional arguments are processed according to _prepare_find prior to passing to PyMongo where positional parameters are interpreted as query fragments parametric keyword arguments combined and other keyword arguments passed along with minor transformation. https:// api. mo...
def find(cls, *args, **kw): """Query the collection this class is bound to. Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword arguments passed al...
Get a single document from the collection this class is bound to. Additional arguments are processed according to _prepare_find prior to passing to PyMongo where positional parameters are interpreted as query fragments parametric keyword arguments combined and other keyword arguments passed along with minor transformat...
def find_one(cls, *args, **kw): """Get a single document from the collection this class is bound to. Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyw...
Return a QuerySet iterating the results of a query in a defined order. Technically an aggregate. To be successful one must be running MongoDB 3. 4 or later. Document order will not be represented otherwise. Based on the technique described here: http:// s. webcore. io/ 2O3i0N2E3h0r See also: https:// jira. mongodb. org...
def find_in_sequence(cls, field, order, *args, **kw): """Return a QuerySet iterating the results of a query in a defined order. Technically an aggregate. To be successful one must be running MongoDB 3.4 or later. Document order will not be represented otherwise. Based on the technique described here: http:/...
Reload the entire document from the database or refresh specific named top - level fields.
def reload(self, *fields, **kw): """Reload the entire document from the database, or refresh specific named top-level fields.""" Doc, collection, query, options = self._prepare_find(id=self.id, projection=fields, **kw) result = collection.find_one(query, **options) if fields: # Refresh only the requested...
Get values gathered from the previously set hierarchy.
def get(cls): """Get values gathered from the previously set hierarchy. Respects the order in which sources are set, the first source set has the highest priority, overrides values with the same key that exist in sources with lower priority. Returns: dict: The dicti...
Set command line arguments as a source
def argv(cls, name, short_name=None, type=None, help=None): """ Set command line arguments as a source Parses the command line arguments described by the parameters. Args: name: the long name of the argument (foo) short_name: the optional short name of the argument (f) ...
Set environment variables as a source.
def env(cls, separator=None, match=None, whitelist=None, parse_values=None, to_lower=None, convert_underscores=None): """Set environment variables as a source. By default all environment variables available to the process are used. This can be narrowed by the args. Args: se...
Set a file as a source.
def file(cls, path, encoding=None, parser=None): """Set a file as a source. File are parsed as literal python dicts by default, this behaviour can be configured. Args: path: The path to the file to be parsed encoding: The encoding of the file. De...
Generate a MongoDB projection dictionary using the Django ORM style.
def P(Document, *fields, **kw): """Generate a MongoDB projection dictionary using the Django ORM style.""" __always__ = kw.pop('__always__', set()) projected = set() omitted = set() for field in fields: if field[0] in ('-', '!'): omitted.add(field[1:]) elif field[0] == '+': projected.add(field[1:]) ...
Performs a login handshake with a user on the command - line. This method will handle all of the follow - up requests ( e. g. capcha or two - factor ). A login that requires two - factor looks like this::
def do_login(session, for_what): """ Performs a login handshake with a user on the command-line. This method will handle all of the follow-up requests (e.g. capcha or two-factor). A login that requires two-factor looks like this:: >>> import mwapi.cli >>> import mwapi >>> mwap...
Identify if the given session ID is currently valid. Return True if valid False if explicitly invalid None if unknown.
def is_valid(self, context, sid): """Identify if the given session ID is currently valid. Return True if valid, False if explicitly invalid, None if unknown. """ record = self._Document.find_one(sid, project=('expires', )) if not record: return return not record._expired
Immediately expire a session from the backing store.
def invalidate(self, context, sid): """Immediately expire a session from the backing store.""" result = self._Document.get_collection().delete_one({'_id': sid}) return result.deleted_count == 1
Update or insert the session document into the configured collection
def persist(self, context): """Update or insert the session document into the configured collection""" D = self._Document document = context.session[self.name] D.get_collection().replace_one(D.id == document.id, document, True)
Channels connection setup. Register the current client on the related Group according to the language
def ws_connect(message): """ Channels connection setup. Register the current client on the related Group according to the language """ prefix, language = message['path'].strip('/').split('/') gr = Group('knocker-{0}'.format(language)) gr.add(message.reply_channel) message.channel_session...
Channels connection close. Deregister the client
def ws_disconnect(message): """ Channels connection close. Deregister the client """ language = message.channel_session['knocker'] gr = Group('knocker-{0}'.format(language)) gr.discard(message.reply_channel)
Return a shallow copy.
def copy(self): """Return a shallow copy.""" return self.__class__(self.operations.copy(), self.collection, self.document)
Transform to a MongoDB - safe value.
def to_foreign(self, obj, name, value): # pylint:disable=unused-argument """Transform to a MongoDB-safe value.""" if self.cache: return self._populate_cache(value) identifier = value # First, we handle the typcial Document object case. if isinstance(value, Document): identifier = value.__data_...
Function: space_wave Summary: This function is used to generate a wave - like padding spacement based on the variable lambda Examples: >>> print ( \ n. join ( space_wave ( x ) for x in range ( 100 )) █ ███ ████ ██████ ███████ ████████ █████████ ██████████ ██████████ ██████████ ██████████ ██████████ ██████████ █████████...
def space_wave(phase, amplitude=12, frequency=0.1): """ Function: space_wave Summary: This function is used to generate a wave-like padding spacement based on the variable lambda Examples: >>> print('\n'.join(space_wave(x) for x in range(100)) █ ███ ...
Start a new animation instance
def start(self, autopush=True): """Start a new animation instance""" if self.enabled: if autopush: self.push_message(self.message) self.spinner.message = ' - '.join(self.animation.messages) if not self.spinner.running: self.animatio...
Stop the thread animation gracefully and reset_message
def stop(cls): """Stop the thread animation gracefully and reset_message""" if AnimatedDecorator._enabled: if cls.spinner.running: cls.spinner.running = False cls.animation.thread.join() if any(cls.animation.messages): cls.pop_mess...
Try guess the message by the args passed
def auto_message(self, args): """Try guess the message by the args passed args: a set of args passed on the wrapper __call__ in the definition above. if the object already have some message (defined in __init__), we don't change that. If the first arg is a function, so is...
Activate the TypingStream on stdout
def start(self): """Activate the TypingStream on stdout""" self.streams.append(sys.stdout) sys.stdout = self.stream
Change back the normal stdout after the end
def stop(cls): """Change back the normal stdout after the end""" if any(cls.streams): sys.stdout = cls.streams.pop(-1) else: sys.stdout = sys.__stdout__
Attempt to acquire an exclusive lock on this record. If a timeout is given ( in seconds ) then the acquire call will block for up to that much time attempting to acquire the lock. If the lock can not be acquired ( either because it is already set or we time out ) a Locked exception will be raised.
def acquire(self, timeout=0, force=False): """Attempt to acquire an exclusive lock on this record. If a timeout is given (in seconds) then the acquire call will block for up to that much time attempting to acquire the lock. If the lock can not be acquired (either because it is already set or we time out) a Loc...
Prolong the working duration of an already held lock. Attempting to prolong a lock not already owned will result in a Locked exception.
def prolong(self): """Prolong the working duration of an already held lock. Attempting to prolong a lock not already owned will result in a Locked exception. """ D = self.__class__ collection = self.get_collection() identity = self.Lock() query = D.id == self query &= D.lock.instance == identit...
Release an exclusive lock on this integration task. Unless forcing if we are not the current owners of the lock a Locked exception will be raised.
def release(self, force=False): """Release an exclusive lock on this integration task. Unless forcing, if we are not the current owners of the lock a Locked exception will be raised. """ D = self.__class__ collection = self.get_collection() identity = self.Lock() query = D.id == self if not ...
Transform the MongoDB value into a Marrow Mongo value.
def to_native(self, obj, name, value): # pylint:disable=unused-argument """Transform the MongoDB value into a Marrow Mongo value.""" if self.mapping: for original, new in self.mapping.items(): value = value.replace(original, new) return load(value, self.namespace)
Transform to a MongoDB - safe value.
def to_foreign(self, obj, name, value): # pylint:disable=unused-argument """Transform to a MongoDB-safe value.""" namespace = self.namespace try: explicit = self.explicit except AttributeError: explicit = not namespace if not isinstance(value, (str, unicode)): value = canon(value) if n...
Generate a MongoDB filter document through parameter interpolation. Arguments passed by name have their name interpreted as an optional prefix ( currently only not ) a double - underscore Because this utility is likely going to be used frequently it has been given a single - character name.
def F(Document, __raw__=None, **filters): """Generate a MongoDB filter document through parameter interpolation. Arguments passed by name have their name interpreted as an optional prefix (currently only `not`), a double- underscore Because this utility is likely going to be used frequently it has been given a ...
Function: write Summary: write method on the default stream Examples: >>> stream. write ( message ) message Attributes:
def write(self, message, flush=True): """ Function: write Summary: write method on the default stream Examples: >>> stream.write('message') 'message' Attributes: @param (message): str-like content to send on stream @param (flush) default=...
Send something for stdout and erased after delay
def write(self, message, autoerase=True): """Send something for stdout and erased after delay""" super(Animation, self).write(message) self.last_message = message if autoerase: time.sleep(self.interval) self.erase(message)
Erase something whose you write before: message
def erase(self, message=None): """Erase something whose you write before: message""" if not message: message = self.last_message # Move cursor to the beginning of line super(Animation, self).write("\033[G") # Erase in line from cursor super(Animation, self).wr...
Write something on the default stream with a prefixed message
def write(self, message, flush=False): """Write something on the default stream with a prefixed message""" # this need be threadsafe because the concurrent spinning running on # the stderr with self.lock: self.paralell_stream.erase() super(Clean, self).write(messa...
A Writting like write method delayed at each char
def write(self, message, flush=True): if isinstance(message, bytes): # pragma: no cover message = message.decode('utf-8') """A Writting like write method, delayed at each char""" for char in message: time.sleep(self.delay * (4 if char == '\n' else 1)) super(...
Bind a copy of the collection to the class modified per our class settings. The given target ( and eventual collection returned ) must be safe within the context the document sublcass being bound is constructed within. E. g. at the module scope this binding must be thread - safe.
def bind(cls, target): """Bind a copy of the collection to the class, modified per our class' settings. The given target (and eventual collection returned) must be safe within the context the document sublcass being bound is constructed within. E.g. at the module scope this binding must be thread-safe. """ ...
Retrieve a properly configured collection object as configured by this document class. If given an existing collection will instead call collection. with_options. http:// api. mongodb. com/ python/ current/ api/ pymongo/ database. html#pymongo. database. Database. get_collection
def get_collection(cls, target=None): """Retrieve a properly configured collection object as configured by this document class. If given an existing collection, will instead call `collection.with_options`. http://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.get_collecti...
Ensure the collection identified by this document class exists creating it if not also creating indexes. ** Warning: ** enabling the recreate option ** will drop the collection erasing all data within **. http:// api. mongodb. com/ python/ current/ api/ pymongo/ database. html#pymongo. database. Database. create_collec...
def create_collection(cls, target=None, drop=False, indexes=True): """Ensure the collection identified by this document class exists, creating it if not, also creating indexes. **Warning:** enabling the `recreate` option **will drop the collection, erasing all data within**. http://api.mongodb.com/python/cu...
Iterate all known indexes and construct them. https:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. create_indexes
def create_indexes(cls, target=None, recreate=False): """Iterate all known indexes and construct them. https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes """ # TODO: Nested indexes. results = [] collection = cls.get_collection(target) ...
Construct the default projection document.
def _get_default_projection(cls): """Construct the default projection document.""" projected = [] # The fields explicitly requested for inclusion. neutral = [] # Fields returning neutral (None) status. omitted = False # Have any fields been explicitly omitted? for name, field in cls.__fields__.items(...
Insert this document. The validate argument translates to the inverse of the bypass_document_validation PyMongo option. https:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. insert_one
def insert_one(self, validate=True): """Insert this document. The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option. https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one """ kw = {} kw['bypass_docu...
Update this document in the database. Local representations will not be affected. A single positional parameter update may be provided as a mapping. Keyword arguments ( other than those identified in UPDATE_MAPPING ) are interpreted as parametric updates added to any update passed in. https:// api. mongodb. com/ python...
def update_one(self, update=None, validate=True, **kw): """Update this document in the database. Local representations will not be affected. A single positional parameter, `update`, may be provided as a mapping. Keyword arguments (other than those identified in UPDATE_MAPPING) are interpreted as parametric upd...
Remove this document from the database passing additional arguments through to PyMongo. https:// api. mongodb. com/ python/ current/ api/ pymongo/ collection. html#pymongo. collection. Collection. delete_one
def delete_one(self, source=None, **kw): """Remove this document from the database, passing additional arguments through to PyMongo. https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one """ collection = self.get_collection(source) return collection....
Returns a bytestring version of s encoded as specified in encoding.
def force_text(s, encoding='utf-8', errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. Based on the `django.utils.encoding.smart_str' (https://github.com/django/django/blob/master/django/...
Move marrow. schema fields around to control positional instantiation order.
def adjust_attribute_sequence(*fields): """Move marrow.schema fields around to control positional instantiation order.""" amount = None if fields and isinstance(fields[0], int): amount, fields = fields[0], fields[1:] def adjust_inner(cls): for field in fields: if field not in cls.__dict__: # TODO: ...
Round a datetime object down to the start of a defined period. The base argument may be used to find the period start for an arbitrary datetime defaults to utcnow ().
def datetime_period(base=None, hours=None, minutes=None, seconds=None): """Round a datetime object down to the start of a defined period. The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`. """ if base is None: base = utcnow() base -= timedelta( ho...
Get a dictionary of file paths and timestamps.
def get_hashes(path, exclude=None): ''' Get a dictionary of file paths and timestamps. Paths matching `exclude` regex will be excluded. ''' out = {} for f in Path(path).rglob('*'): if f.is_dir(): # We want to watch files, not directories. continue if excl...
Sends an HTTP request to the API.
def request(self, method, params=None, query_continue=None, files=None, auth=None, continuation=False): """ Sends an HTTP request to the API. :Parameters: method : `str` Which HTTP method to use for the request? (Usually "POST" or "GET...
Authenticate with the given credentials. If authentication is successful all further requests sent will be signed the authenticated user.
def login(self, username, password, login_token=None): """ Authenticate with the given credentials. If authentication is successful, all further requests sent will be signed the authenticated user. Note that passwords are sent as plaintext. This is a limitation of the M...
Continues a login that requires an additional step. This is common for when login requires completing a captcha or supplying a two - factor authentication token.
def continue_login(self, login_token, **params): """ Continues a login that requires an additional step. This is common for when login requires completing a captcha or supplying a two-factor authentication token. :Parameters: login_token : `str` A lo...
Makes an API request with the GET method
def get(self, query_continue=None, auth=None, continuation=False, **params): """Makes an API request with the GET method :Parameters: query_continue : `dict` Optionally, the value of a query continuation 'continue' field. auth : mixed ...
Makes an API request with the POST method
def post(self, query_continue=None, upload_file=None, auth=None, continuation=False, **params): """Makes an API request with the POST method :Parameters: query_continue : `dict` Optionally, the value of a query continuation 'continue' field. upload_f...
Produce a query fragment suitable for selecting documents public. Now ( no arguments ) at a specific time ( datetime argument ) or relative to now ( timedelta ).
def only_published(cls, at=None): """Produce a query fragment suitable for selecting documents public. Now (no arguments), at a specific time (datetime argument), or relative to now (timedelta). """ if isinstance(at, timedelta): at = utcnow() + at else: at = at or utcnow() pub, ret = cls.publ...
Transform the MongoDB value into a Marrow Mongo value.
def to_native(self, obj, name, value): # pylint:disable=unused-argument """Transform the MongoDB value into a Marrow Mongo value.""" from marrow.mongo import Document from marrow.mongo.trait import Derived kind = self._kind(obj.__class__) if isinstance(value, Document): if __debug__ and kind and ...
Transform to a MongoDB - safe value.
def to_foreign(self, obj, name, value): # pylint:disable=unused-argument """Transform to a MongoDB-safe value.""" from marrow.mongo import Document kind = self._kind(obj if isclass(obj) else obj.__class__) if isinstance(value, Document): if __debug__ and kind and issubclass(kind, Document) and not ...
Transform this record into an instance of a more specialized subclass.
def promote(self, cls, update=False, preserve=True): """Transform this record into an instance of a more specialized subclass.""" if not issubclass(cls, self.__class__): raise TypeError("Must promote to a subclass of " + self.__class__.__name__) return self._as(cls, update, preserve)
Transform the MongoDB value into a Marrow Mongo value.
def to_native(self, obj, name, value): """Transform the MongoDB value into a Marrow Mongo value.""" if isinstance(value, self.List): return value result = self.List(super(Array, self).to_native(obj, name, i) for i in value) obj.__data__[self.__name__] = result return result
Transform to a MongoDB - safe value.
def to_foreign(self, obj, name, value): """Transform to a MongoDB-safe value.""" if isinstance(value, Iterable) and not isinstance(value, Mapping): return self.List(super(Array, self).to_foreign(obj, name, i) for i in value) return super(Array, self).to_foreign(obj, name, value)
cutting nodes away from menus
def cut_levels(nodes, start_level): """ cutting nodes away from menus """ final = [] removed = [] for node in nodes: if not hasattr(node, 'level'): # remove and ignore nodes that don't have level information remove(node, removed) continue if no...
Generate a MongoDB update document through paramater interpolation. Arguments passed by name have their name interpreted as an optional operation prefix ( defaulting to set e. g. push ) a double - underscore separated field reference ( e. g. foo or foo__bar or foo__S__bar or foo__27__bar ) Because this utility is likel...
def U(Document, __raw__=None, **update): """Generate a MongoDB update document through paramater interpolation. Arguments passed by name have their name interpreted as an optional operation prefix (defaulting to `set`, e.g. `push`), a double-underscore separated field reference (e.g. `foo`, or `foo__bar`, or `foo_...
Function: debug Summary: decorator to debug a function Examples: at the execution of the function wrapped the decorator will allows to print the input and output of each execution Attributes:
def debug(function): """ Function: debug Summary: decorator to debug a function Examples: at the execution of the function wrapped, the decorator will allows to print the input and output of each execution Attributes: @param (function): function Returns: wrapp...
Function: counter Summary: Decorator to count the number of a function is executed each time Examples: You can use that to had a progress of heally heavy computation without progress feedback Attributes:
def counter(function): """ Function: counter Summary: Decorator to count the number of a function is executed each time Examples: You can use that to had a progress of heally heavy computation without progress feedback Attributes: @param (function): function Returns: wrappe...
Function: count_time Summary: get the time to finish a function print at the end that time to stdout Examples: <NONE > Attributes:
def count_time(function): """ Function: count_time Summary: get the time to finish a function print at the end that time to stdout Examples: <NONE> Attributes: @param (function): function Returns: wrapped function """ @wraps(function) def _wrapper(*args, **kwargs...
In the event a value that has technically already expired is loaded swap it for None.
def from_mongo(cls, data, expired=False, **kw): """In the event a value that has technically already expired is loaded, swap it for None.""" value = super(Expires, cls).from_mongo(data, **kw) if not expired and value.is_expired: return None return value