INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
: rtype: list ( list ( str )) | def _get_webpages(self):
"""
:rtype: list(list(str))
"""
urls = []
for child in self.vcard.getChildren():
if child.name == "URL":
urls.append(child.value)
return sorted(urls) |
: returns: contacts anniversary or None if not available: rtype: datetime. datetime or str | def get_anniversary(self):
""":returns: contacts anniversary or None if not available
:rtype: datetime.datetime or str
"""
# vcard 4.0 could contain a single text value
try:
if self.vcard.anniversary.params.get("VALUE")[0] == "text":
return self.vc... |
: returns: contacts birthday or None if not available: rtype: datetime. datetime or str | def get_birthday(self):
""":returns: contacts birthday or None if not available
:rtype: datetime.datetime or str
"""
# vcard 4.0 could contain a single text value
try:
if self.vcard.bday.params.get("VALUE")[0] == "text":
return self.vcard.bday.valu... |
get list of types for phone number email or post address: param object: vcard class object: type object: vobject. vCard: param default_type: use if the object contains no type: type default_type: str: returns: list of type labels: rtype: list ( str ) | def _get_types_for_vcard_object(self, object, default_type):
"""
get list of types for phone number, email or post address
:param object: vcard class object
:type object: vobject.vCard
:param default_type: use if the object contains no type
:type default_type: str
... |
Parse type value of phone numbers email and post addresses. | def _parse_type_value(types, value, supported_types):
"""Parse type value of phone numbers, email and post addresses.
:param types: list of type values
:type types: list(str)
:param value: the corresponding label, required for more verbose
exceptions
:type value: str... |
converts list to string recursively so that nested lists are supported | def list_to_string(input, delimiter):
"""converts list to string recursively so that nested lists are supported
:param input: a list of strings and lists of strings (and so on recursive)
:type input: list
:param delimiter: the deimiter to use when joining the items
:type delimiter: str
:returns... |
Convert string to date object. | def string_to_date(input):
"""Convert string to date object.
:param input: the date string to parse
:type input: str
:returns: the parsed datetime object
:rtype: datetime.datetime
"""
# try date formats --mmdd, --mm-dd, yyyymmdd, yyyy-mm-dd and datetime
# formats yyyymmddThhmmss, yyyy-m... |
converts a value list into yaml syntax: param name: name of object ( example: phone ): type name: str: param value: object contents: type value: str list ( str ) list ( list ( str )): param indentation: indent all by number of spaces: type indentation: int: param indexOfColon: use to position: at the name string ( - 1 ... | def convert_to_yaml(
name, value, indentation, indexOfColon, show_multi_line_character):
"""converts a value list into yaml syntax
:param name: name of object (example: phone)
:type name: str
:param value: object contents
:type value: str, list(str), list(list(str))
:param indentation: i... |
converts user input into vcard compatible data structures: param name: object name only required for error messages: type name: str: param value: user input: type value: str or list ( str ): param allowed_object_type: set the accepted return type for vcard attribute: type allowed_object_type: enum of type ObjectType: r... | def convert_to_vcard(name, value, allowed_object_type):
"""converts user input into vcard compatible data structures
:param name: object name, only required for error messages
:type name: str
:param value: user input
:type value: str or list(str)
:param allowed_object_type: set the accepted retu... |
Calculate the minimum length of initial substrings of uid1 and uid2 for them to be different. | def _compare_uids(uid1, uid2):
"""Calculate the minimum length of initial substrings of uid1 and uid2
for them to be different.
:param uid1: first uid to compare
:type uid1: str
:param uid2: second uid to compare
:type uid2: str
:returns: the length of the shorte... |
Search in all fields for contacts matching query. | def _search_all(self, query):
"""Search in all fields for contacts matching query.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject)
"""
regexp = re.compile(query, re.IGNORECASE | r... |
Search in the name filed for contacts matching query. | def _search_names(self, query):
"""Search in the name filed for contacts matching query.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject)
"""
regexp = re.compile(query, re.IGNORECA... |
Search for contacts with a matching uid. | def _search_uid(self, query):
"""Search for contacts with a matching uid.
:param query: the query to search for
:type query: str
:yields: all found contacts
:rtype: generator(carddav_object.CarddavObject)
"""
try:
# First we treat the argument as a f... |
Search this address book for contacts matching the query. | def search(self, query, method="all"):
"""Search this address book for contacts matching the query.
The method can be one of "all", "name" and "uid". The backend for this
address book migth be load()ed if needed.
:param query: the query to search for
:type query: str
:... |
Create a dictionary of shortend UIDs for all contacts. | def get_short_uid_dict(self, query=None):
"""Create a dictionary of shortend UIDs for all contacts.
All arguments are only used if the address book is not yet initialized
and will just be handed to self.load().
:param query: see self.load()
:type query: str
:returns: th... |
Get the shortend UID for the given UID. | def get_short_uid(self, uid):
"""Get the shortend UID for the given UID.
:param uid: the full UID to shorten
:type uid: str
:returns: the shortend uid or the empty string
:rtype: str
"""
if uid:
short_uids = self.get_short_uid_dict()
for l... |
Find all vcard files inside this address book. | def _find_vcard_files(self, search=None, search_in_source_files=False):
"""Find all vcard files inside this address book.
If a search string is given only files which contents match that will
be returned.
:param search: a regular expression to limit the results
:type search: st... |
Load all vcard files in this address book from disk. | def load(self, query=None, search_in_source_files=False):
"""Load all vcard files in this address book from disk.
If a search string is given only files which contents match that will
be loaded.
:param query: a regular expression to limit the results
:type query: str
:p... |
Get one of the backing abdress books by its name | def get_abook(self, name):
"""Get one of the backing abdress books by its name,
:param name: the name of the address book to get
:type name: str
:returns: the matching address book or None
:rtype: AddressBook or NoneType
"""
for abook in self._abooks:
... |
This function is used in sys command ( when user want to find a specific syscall ) | def get_table(self, arch, pattern, colored=False, verbose=False):
'''
This function is used in sys command (when user want to find a specific syscall)
:param Architecture for syscall table;
:param Searching pattern;
:param Flag for verbose output
:return Return a printab... |
Initialize the dictionary of architectures for assembling via keystone | def avail_archs(self):
''' Initialize the dictionary of architectures for assembling via keystone'''
return {
ARM32: (KS_ARCH_ARM, KS_MODE_ARM),
ARM64: (KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN),
ARM_TB: (KS_ARCH_ARM, KS_MODE_THUMB),
HEXAGON: (... |
Initialize the dictionary of architectures for disassembling via capstone | def avail_archs(self):
''' Initialize the dictionary of architectures for disassembling via capstone'''
return {
ARM32: (CS_ARCH_ARM, CS_MODE_ARM),
ARM64: (CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN),
ARM_TB: (CS_ARCH_ARM, CS_MODE_THUMB),
MIPS32: (CS_... |
An inspect. getargspec with a relaxed sanity check to support Cython. | def getargspec_permissive(func):
"""
An `inspect.getargspec` with a relaxed sanity check to support Cython.
Motivation:
A Cython-compiled function is *not* an instance of Python's
types.FunctionType. That is the sanity check the standard Py2
library uses in `inspect.getargspec()`.... |
Parses given list of arguments using given parser calls the relevant function and prints the result. | def dispatch(parser, argv=None, add_help_command=True,
completion=True, pre_call=None,
output_file=sys.stdout, errors_file=sys.stderr,
raw_output=False, namespace=None,
skip_unknown_args=False):
"""
Parses given list of arguments using given parser, calls the ... |
Assumes that function is a callable. Tries different approaches to call it ( with namespace_obj or with ordinary signature ). Yields the results line by line. | def _execute_command(function, namespace_obj, errors_file, pre_call=None):
"""
Assumes that `function` is a callable. Tries different approaches
to call it (with `namespace_obj` or with ordinary signature).
Yields the results line by line.
If :class:`~argh.exceptions.CommandError` is raised, its m... |
A wrapper for: func: dispatch that creates a one - command parser. Uses: attr: PARSER_FORMATTER. | def dispatch_command(function, *args, **kwargs):
"""
A wrapper for :func:`dispatch` that creates a one-command parser.
Uses :attr:`PARSER_FORMATTER`.
This::
dispatch_command(foo)
...is a shortcut for::
parser = ArgumentParser()
set_default_command(parser, foo)
dis... |
A wrapper for: func: dispatch that creates a parser adds commands to the parser and dispatches them. Uses: attr: PARSER_FORMATTER. | def dispatch_commands(functions, *args, **kwargs):
"""
A wrapper for :func:`dispatch` that creates a parser, adds commands to
the parser and dispatches them.
Uses :attr:`PARSER_FORMATTER`.
This::
dispatch_commands([foo, bar])
...is a shortcut for::
parser = ArgumentParser()
... |
Prompts user for input. Correctly handles prompt message encoding. | def safe_input(prompt):
"""
Prompts user for input. Correctly handles prompt message encoding.
"""
if sys.version_info < (3,0):
if isinstance(prompt, compat.text_type):
# Python 2.x: unicode → bytes
encoding = locale.getpreferredencoding() or 'utf-8'
prompt ... |
Encodes given value so it can be written to given file object. | def encode_output(value, output_file):
"""
Encodes given value so it can be written to given file object.
Value may be Unicode, binary string or any other data type.
The exact behaviour depends on the Python version:
Python 3.x
`sys.stdout` is a `_io.TextIOWrapper` instance that accepts ... |
Writes given line to given output file. See: func: encode_output for details. | def dump(raw_data, output_file):
"""
Writes given line to given output file.
See :func:`encode_output` for details.
"""
data = encode_output(raw_data, output_file)
output_file.write(data) |
Adds support for shell completion via argcomplete_ by patching given argparse. ArgumentParser ( sub ) class. | def autocomplete(parser):
"""
Adds support for shell completion via argcomplete_ by patching given
`argparse.ArgumentParser` (sub)class.
If completion is not enabled, logs a debug-level message.
"""
if COMPLETION_ENABLED:
argcomplete.autocomplete(parser)
elif 'bash' in os.getenv('SH... |
Wrapper for: meth: argparse. ArgumentParser. parse_args. If namespace is not defined: class: argh. dispatching. ArghNamespace is used. This is required for functions to be properly used as commands. | def parse_args(self, args=None, namespace=None):
"""
Wrapper for :meth:`argparse.ArgumentParser.parse_args`. If `namespace`
is not defined, :class:`argh.dispatching.ArghNamespace` is used.
This is required for functions to be properly used as commands.
"""
namespace = na... |
This method is copied verbatim from ArgumentDefaultsHelpFormatter with a couple of lines added just before the end. Reason: we need to repr () default values instead of simply inserting them as is. This helps notice for example an empty string as the default value ; moreover it prevents breaking argparse due to logical... | def _expand_help(self, action):
"""
This method is copied verbatim from ArgumentDefaultsHelpFormatter with
a couple of lines added just before the end. Reason: we need to
`repr()` default values instead of simply inserting them as is.
This helps notice, for example, an empty str... |
Adds types actions etc. to given argument specification. For example default = 3 implies type = int. | def _guess(kwargs):
"""
Adds types, actions, etc. to given argument specification.
For example, ``default=3`` implies ``type=int``.
:param arg: a :class:`argh.utils.Arg` instance
"""
guessed = {}
# Parser actions that accept argument 'type'
TYPE_AWARE_ACTIONS = 'store', 'append'
#... |
Sets default command ( i. e. a function ) for given parser. | def set_default_command(parser, function):
"""
Sets default command (i.e. a function) for given parser.
If `parser.description` is empty and the function has a docstring,
it is used as the description.
.. note::
An attempt to set default command to a parser which already has
subpars... |
Adds given functions as commands to given parser. | def add_commands(parser, functions, namespace=None, namespace_kwargs=None,
func_kwargs=None,
# deprecated args:
title=None, description=None, help=None):
"""
Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.Argu... |
A wrapper for: func: add_commands. | def add_subcommands(parser, namespace, functions, **namespace_kwargs):
"""
A wrapper for :func:`add_commands`.
These examples are equivalent::
add_commands(parser, [get, put], namespace='db',
namespace_kwargs={
'title': 'database commands',
... |
Returns the: class: argparse. _SubParsersAction instance for given: class: ArgumentParser instance as would have been returned by: meth: ArgumentParser. add_subparsers. The problem with the latter is that it only works once and raises an exception on the second attempt and the public API seems to lack a method to get *... | def get_subparsers(parser, create=False):
"""
Returns the :class:`argparse._SubParsersAction` instance for given
:class:`ArgumentParser` instance as would have been returned by
:meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
it only works once and raises an exception on th... |
Returns argument specification for given function. Omits special arguments of instance methods ( self ) and static methods ( usually cls or something like this ). | def get_arg_spec(function):
"""
Returns argument specification for given function. Omits special
arguments of instance methods (`self`) and static methods (usually `cls`
or something like this).
"""
while hasattr(function, '__wrapped__'):
function = function.__wrapped__
spec = compa... |
Sets given string as command name instead of the function name. The string is used verbatim without further processing. | def named(new_name):
"""
Sets given string as command name instead of the function name.
The string is used verbatim without further processing.
Usage::
@named('load')
def do_load_some_stuff_and_keep_the_original_function_name(args):
...
The resulting command will be a... |
Defines alternative command name ( s ) for given function ( along with its original name ). Usage:: | def aliases(*names):
"""
Defines alternative command name(s) for given function (along with its
original name). Usage::
@aliases('co', 'check')
def checkout(args):
...
The resulting command will be available as ``checkout``, ``check`` and ``co``.
.. note::
This... |
Declares an argument for given function. Does not register the function anywhere nor does it modify the function in any way. | def arg(*args, **kwargs):
"""
Declares an argument for given function. Does not register the function
anywhere, nor does it modify the function in any way.
The signature of the decorator matches that of
:meth:`argparse.ArgumentParser.add_argument`, only some keywords are not
required if they ca... |
Decorator. Wraps given exceptions into: class: ~argh. exceptions. CommandError. Usage:: | def wrap_errors(errors=None, processor=None, *args):
"""
Decorator. Wraps given exceptions into
:class:`~argh.exceptions.CommandError`. Usage::
@wrap_errors([AssertionError])
def foo(x=None, y=None):
assert x or y, 'x or y must be specified'
If the assertion fails, its mess... |
A shortcut for typical confirmation prompt. | def confirm(action, default=None, skip=False):
"""
A shortcut for typical confirmation prompt.
:param action:
a string describing the action, e.g. "Apply changes". A question mark
will be appended.
:param default:
`bool` or `None`. Determines what happens when user hits :kbd:... |
Select the provided column names from the model do not return an entity do not involve the rom session just get the raw and/ or processed column data from Redis. | def select(self, *column_names, **kwargs):
'''
Select the provided column names from the model, do not return an entity,
do not involve the rom session, just get the raw and/or processed column
data from Redis.
Keyword-only arguments:
* *include_pk=False* - whether ... |
Copy the Query object optionally replacing the filters order_by or limit information on the copy. This is mostly an internal detail that you can ignore. | def replace(self, **kwargs):
'''
Copy the Query object, optionally replacing the filters, order_by, or
limit information on the copy. This is mostly an internal detail that
you can ignore.
'''
data = {
'model': self._model,
'filters': self._filters... |
Only columns/ attributes that have been specified as having an index with the index = True option on the column definition can be filtered with this method. Prefix suffix and pattern match filters must be provided using the. startswith (). endswith () and the. like () methods on the query object respectively. Geo locat... | def filter(self, **kwargs):
'''
Only columns/attributes that have been specified as having an index with
the ``index=True`` option on the column definition can be filtered with
this method. Prefix, suffix, and pattern match filters must be provided
using the ``.startswith()``, ``... |
When provided with keyword arguments of the form col = prefix this will limit the entities returned to those that have a word with the provided prefix in the specified column ( s ). This requires that the prefix = True option was provided during column definition. | def startswith(self, **kwargs):
'''
When provided with keyword arguments of the form ``col=prefix``, this
will limit the entities returned to those that have a word with the
provided prefix in the specified column(s). This requires that the
``prefix=True`` option was provided dur... |
When provided with keyword arguments of the form col = suffix this will limit the entities returned to those that have a word with the provided suffix in the specified column ( s ). This requires that the suffix = True option was provided during column definition. | def endswith(self, **kwargs):
'''
When provided with keyword arguments of the form ``col=suffix``, this
will limit the entities returned to those that have a word with the
provided suffix in the specified column(s). This requires that the
``suffix=True`` option was provided durin... |
When provided with keyword arguments of the form col = pattern this will limit the entities returned to those that include the provided pattern. Note that like queries require that the prefix = True option must have been provided as part of the column definition. | def like(self, **kwargs):
'''
When provided with keyword arguments of the form ``col=pattern``, this
will limit the entities returned to those that include the provided
pattern. Note that 'like' queries require that the ``prefix=True``
option must have been provided as part of th... |
When provided with a column name will sort the results of your query:: | def order_by(self, column):
'''
When provided with a column name, will sort the results of your query::
# returns all users, ordered by the created_at column in
# descending order
User.query.order_by('-created_at').execute()
'''
cname = column.lstrip(... |
Will return the total count of the objects that match the specified filters.:: | def count(self):
'''
Will return the total count of the objects that match the specified
filters.::
# counts the number of users created in the last 24 hours
User.query.filter(created_at=(time.time()-86400, time.time())).count()
'''
filters = self._filter... |
Iterate over the results of your query instead of getting them all with. all (). Will only perform a single query. If you expect that your processing will take more than 30 seconds to process 100 items you should pass timeout and pagesize to reflect an appropriate timeout and page size to fetch at once. | def iter_result(self, timeout=30, pagesize=100, no_hscan=False):
'''
Iterate over the results of your query instead of getting them all with
`.all()`. Will only perform a single query. If you expect that your
processing will take more than 30 seconds to process 100 items, you
sho... |
This will execute the query returning the key where a ZSET of your results will be stored for pagination further operations etc. | def cached_result(self, timeout):
'''
This will execute the query, returning the key where a ZSET of your
results will be stored for pagination, further operations, etc.
The timeout must be a positive integer number of seconds for which to
set the expiration time on the key (thi... |
Returns only the first result from the query if any. | def first(self):
'''
Returns only the first result from the query, if any.
'''
lim = [0, 1]
if self._limit:
lim[0] = self._limit[0]
if not self._filters and not self._order_by:
for ent in self:
return ent
return None
... |
Will delete the entities that match at the time the query is executed. | def delete(self, blocksize=100):
'''
Will delete the entities that match at the time the query is executed.
Used like::
MyModel.query.filter(email=...).delete()
MyModel.query.endswith(email='@host.com').delete()
.. warning:: can't be used on models on either si... |
This function handles all on_delete semantics defined on OneToMany columns. | def _on_delete(ent):
'''
This function handles all on_delete semantics defined on OneToMany columns.
This function only exists because 'cascade' is *very* hard to get right.
'''
seen_d = set([ent._pk])
to_delete = [ent]
seen_s = set()
to_save = []
def _set_default(ent, attr, de=NUL... |
Performs the actual prefix suffix and pattern match operations. | def redis_prefix_lua(conn, dest, index, prefix, is_first, pattern=None):
'''
Performs the actual prefix, suffix, and pattern match operations.
'''
tkey = '%s:%s'%(index.partition(':')[0], uuid.uuid4())
start, end = _start_end(prefix)
return _redis_prefix_lua(conn,
[dest, tkey, index],
... |
Estimates the total work necessary to calculate the prefix match over the given index with the provided prefix. | def estimate_work_lua(conn, index, prefix):
'''
Estimates the total work necessary to calculate the prefix match over the
given index with the provided prefix.
'''
if index.endswith(':idx'):
args = [] if not prefix else list(prefix)
if args:
args[0] = '-inf' if args[0] is... |
Search for model ids that match the provided filters. | def search(self, conn, filters, order_by, offset=None, count=None, timeout=None):
'''
Search for model ids that match the provided filters.
Arguments:
* *filters* - A list of filters that apply to the search of one of
the following two forms:
1. ``'co... |
Returns the count of the items that match the provided filters. | def count(self, conn, filters):
'''
Returns the count of the items that match the provided filters.
For the meaning of what the ``filters`` argument means, see the
``.search()`` method docs.
'''
pipe, intersect, temp_id = self._prepare(conn, filters)
pipe.zcard(t... |
Tries to get the _conn attribute from a model. Barring that gets the global default connection using other methods. | def _connect(obj):
'''
Tries to get the _conn attribute from a model. Barring that, gets the
global default connection using other methods.
'''
from .columns import MODELS
if isinstance(obj, MODELS['Model']):
obj = obj.__class__
if hasattr(obj, '_conn'):
return obj._conn
... |
This is a basic full - text index keygen function. Words are lowercased split by whitespace and stripped of punctuation from both ends before an inverted index is created for term searching. | def FULL_TEXT(val):
'''
This is a basic full-text index keygen function. Words are lowercased, split
by whitespace, and stripped of punctuation from both ends before an inverted
index is created for term searching.
'''
if isinstance(val, float):
val = repr(val)
elif val in (None, '')... |
This is a basic case - sensitive sorted order index keygen function for strings. This will return a value that is suitable to be used for ordering by a 7 - byte prefix of a string ( that is 7 characters from a byte - string and 1. 75 - 7 characters from a unicode string depending on character - > encoding length ). | def SIMPLE(val):
'''
This is a basic case-sensitive "sorted order" index keygen function for
strings. This will return a value that is suitable to be used for ordering
by a 7-byte prefix of a string (that is 7 characters from a byte-string, and
1.75-7 characters from a unicode string, depending on c... |
This is a basic equality index keygen primarily meant to be used for things like:: | def IDENTITY(val):
'''
This is a basic "equality" index keygen, primarily meant to be used for
things like::
Model.query.filter(col='value')
Where ``FULL_TEXT`` would transform a sentence like "A Simple Sentence" into
an inverted index searchable by the words "a", "simple", and/or "sentenc... |
This utility function will iterate over all entities of a provided model refreshing their indices. This is primarily useful after adding an index on a column. | def refresh_indices(model, block_size=100):
'''
This utility function will iterate over all entities of a provided model,
refreshing their indices. This is primarily useful after adding an index
on a column.
Arguments:
* *model* - the model whose entities you want to reindex
* *blo... |
This utility function will clean out old index data that was accidentally left during item deletion in rom versions < = 0. 27. 0. You should run this after you have upgraded all of your clients to version 0. 28. 0 or later. | def clean_old_index(model, block_size=100, **kwargs):
'''
This utility function will clean out old index data that was accidentally
left during item deletion in rom versions <= 0.27.0 . You should run this
after you have upgraded all of your clients to version 0.28.0 or later.
Arguments:
*... |
This utility function will print the progress of a passed iterator job as started by refresh_indices () and clean_old_index (). | def show_progress(job):
'''
This utility function will print the progress of a passed iterator job as
started by ``refresh_indices()`` and ``clean_old_index()``.
Usage example::
class RomTest(Model):
pass
for i in xrange(1000):
RomTest().save()
util.sh... |
Borrowed/ modified from my book Redis in Action: https:// github. com/ josiahcarlson/ redis - in - action/ blob/ master/ python/ ch11_listing_source. py | def _script_load(script):
'''
Borrowed/modified from my book, Redis in Action:
https://github.com/josiahcarlson/redis-in-action/blob/master/python/ch11_listing_source.py
Used for Lua scripting support when writing against Redis 2.6+ to allow
for multiple unique columns per model.
'''
script... |
Useful when you want exclusive access to an entity across all writers.:: | def EntityLock(entity, acquire_timeout, lock_timeout):
'''
Useful when you want exclusive access to an entity across all writers.::
# example
import rom
class Document(rom.Model):
owner = rom.ManyToOne('User', on_delete='restrict')
...
def change_owner(... |
Adds an entity to the session. | def add(self, obj):
'''
Adds an entity to the session.
'''
if self.null_session:
return
self._init()
pk = obj._pk
if not pk.endswith(':None'):
self.known[pk] = obj
self.wknown[pk] = obj |
Forgets about an entity ( automatically called when an entity is deleted ). Call this to ensure that an entity that you ve modified is not automatically saved on session. commit (). | def forget(self, obj):
'''
Forgets about an entity (automatically called when an entity is
deleted). Call this to ensure that an entity that you've modified is
not automatically saved on ``session.commit()`` .
'''
self._init()
self.known.pop(obj._pk, None)
... |
Fetches an entity from the session based on primary key. | def get(self, pk):
'''
Fetches an entity from the session based on primary key.
'''
self._init()
return self.known.get(pk) or self.wknown.get(pk) |
Call. save () on all modified entities in the session. Use when you want to flush changes to Redis but don t want to lose your local session cache. | def flush(self, full=False, all=False, force=False):
'''
Call ``.save()`` on all modified entities in the session. Use when you
want to flush changes to Redis, but don't want to lose your local
session cache.
See the ``.commit()`` method for arguments and their meanings.
... |
Call. save () on all modified entities in the session. Also forgets all known entities in the session so this should only be called at the end of a request. | def commit(self, full=False, all=False, force=False):
'''
Call ``.save()`` on all modified entities in the session. Also forgets
all known entities in the session, so this should only be called at
the end of a request.
Arguments:
* *full* - pass ``True`` to force sa... |
This method is an alternate API for saving many entities ( possibly not tracked by the session ). You can call:: | def save(self, *objects, **kwargs):
'''
This method is an alternate API for saving many entities (possibly not
tracked by the session). You can call::
session.save(obj)
session.save(obj1, obj2, ...)
session.save([obj1, obj2, ...])
And the entities wi... |
This method offers the ability to delete multiple entities in a single round trip to Redis ( assuming your models are all stored on the same server ). You can call:: | def delete(self, *objects, **kwargs):
'''
This method offers the ability to delete multiple entities in a single
round trip to Redis (assuming your models are all stored on the same
server). You can call::
session.delete(obj)
session.delete(obj1, obj2, ...)
... |
This method is an alternate API for refreshing many entities ( possibly not tracked by the session ). You can call:: | def refresh(self, *objects, **kwargs):
'''
This method is an alternate API for refreshing many entities (possibly
not tracked by the session). You can call::
session.refresh(obj)
session.refresh(obj1, obj2, ...)
session.refresh([obj1, obj2, ...])
And... |
This method is an alternate API for refreshing all entities tracked by the session. You can call:: | def refresh_all(self, *objects, **kwargs):
'''
This method is an alternate API for refreshing all entities tracked
by the session. You can call::
session.refresh_all()
session.refresh_all(force=True)
And all entities known by the session will be reloaded from Re... |
... Actually write data to Redis. This is an internal detail. Please don t call me directly. | def redis_writer_lua(conn, pkey, namespace, id, unique, udelete, delete,
data, keys, scored, prefix, suffix, geo, old_data, is_delete):
'''
... Actually write data to Redis. This is an internal detail. Please don't
call me directly.
'''
ldata = []
for pair in data.items():
... |
Saves the current entity to Redis. Will only save changed data by default but you can force a full save by passing full = True. | def save(self, full=False, force=False):
'''
Saves the current entity to Redis. Will only save changed data by
default, but you can force a full save by passing ``full=True``.
If the underlying entity was deleted and you want to re-save the entity,
you can pass ``force=True`` to... |
Deletes the entity immediately. Also performs any on_delete operations specified as part of column definitions. | def delete(self, **kwargs):
'''
Deletes the entity immediately. Also performs any on_delete operations
specified as part of column definitions.
'''
if kwargs.get('skip_on_delete_i_really_mean_it') is not SKIP_ON_DELETE:
# handle the pre-commit hook
self._b... |
Creates a shallow copy of the given entity ( any entities that can be retrieved from a OneToMany relationship will not be copied ). | def copy(self):
'''
Creates a shallow copy of the given entity (any entities that can be
retrieved from a OneToMany relationship will not be copied).
'''
x = self.to_dict()
x.pop(self._pkey)
return self.__class__(**x) |
Will fetch one or more entities of this type from the session or Redis. | def get(cls, ids):
'''
Will fetch one or more entities of this type from the session or
Redis.
Used like::
MyModel.get(5)
MyModel.get([1, 6, 2, 4])
Passing a list or a tuple will return multiple entities, in the same
order that the ids were pass... |
This method offers a simple query method for fetching entities of this type via attribute numeric ranges ( such columns must be indexed ) or via unique columns. | def get_by(cls, **kwargs):
'''
This method offers a simple query method for fetching entities of this
type via attribute numeric ranges (such columns must be ``indexed``),
or via ``unique`` columns.
Some examples::
user = User.get_by(email_address='user@domain.com')... |
Updates multiple attributes in a model. If args are provided this method will assign attributes in the order returned by list ( self. _columns ) until one or both are exhausted. | def update(self, *args, **kwargs):
'''
Updates multiple attributes in a model. If ``args`` are provided, this
method will assign attributes in the order returned by
``list(self._columns)`` until one or both are exhausted.
If ``kwargs`` are provided, this method will assign attri... |
Replacement for pickle. dump () using _LokyPickler. | def dump(obj, file, reducers=None, protocol=None):
'''Replacement for pickle.dump() using _LokyPickler.'''
global _LokyPickler
_LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj) |
Attach a reducer function to a given type in the dispatch table. | def register(cls, type, reduce_func):
"""Attach a reducer function to a given type in the dispatch table."""
if sys.version_info < (3,):
# Python 2 pickler dispatching is not explicitly customizable.
# Let us use a closure to workaround this limitation.
def dispatcher... |
Construct or retrieve a semaphore with the given name | def _sem_open(name, value=None):
""" Construct or retrieve a semaphore with the given name
If value is None, try to retrieve an existing named semaphore.
Else create a new semaphore with the given value
"""
if value is None:
handle = pthread.sem_open(ctypes.c_char_p(name), 0)
else:
... |
Return the number of CPUs the current process can use. | def cpu_count():
"""Return the number of CPUs the current process can use.
The returned number of CPUs accounts for:
* the number of CPUs in the system, as given by
``multiprocessing.cpu_count``;
* the CPU affinity settings of the current process
(available with Python 3.4+ on some Unix... |
Returns a queue object | def Queue(self, maxsize=0, reducers=None):
'''Returns a queue object'''
from .queues import Queue
return Queue(maxsize, reducers=reducers,
ctx=self.get_context()) |
Returns a queue object | def SimpleQueue(self, reducers=None):
'''Returns a queue object'''
from .queues import SimpleQueue
return SimpleQueue(reducers=reducers, ctx=self.get_context()) |
Iterates over zip () ed iterables in chunks. | def _get_chunks(chunksize, *iterables):
"""Iterates over zip()ed iterables in chunks. """
if sys.version_info < (3, 3):
it = itertools.izip(*iterables)
else:
it = zip(*iterables)
while True:
chunk = tuple(itertools.islice(it, chunksize))
if not chunk:
return
... |
Safely send back the given result or exception | def _sendback_result(result_queue, work_id, result=None, exception=None):
"""Safely send back the given result or exception"""
try:
result_queue.put(_ResultItem(work_id, result=result,
exception=exception))
except BaseException as e:
exc = _ExceptionWithT... |
Evaluates calls from call_queue and places the results in result_queue. | def _process_worker(call_queue, result_queue, initializer, initargs,
processes_management_lock, timeout, worker_exit_lock,
current_depth):
"""Evaluates calls from call_queue and places the results in result_queue.
This worker is run in a separate process.
Args:
... |
Fills call_queue with _WorkItems from pending_work_items. | def _add_call_item_to_queue(pending_work_items,
running_work_items,
work_ids,
call_queue):
"""Fills call_queue with _WorkItems from pending_work_items.
This function never blocks.
Args:
pending_work_items: A dict m... |
Manages the communication between this process and the worker processes. | def _queue_management_worker(executor_reference,
executor_flags,
processes,
pending_work_items,
running_work_items,
work_ids_queue,
call_queue,
... |
ensures all workers and management thread are running | def _ensure_executor_running(self):
"""ensures all workers and management thread are running
"""
with self._processes_management_lock:
if len(self._processes) != self._max_workers:
self._adjust_process_count()
self._start_queue_management_thread() |
Returns an iterator equivalent to map ( fn iter ). | def map(self, fn, *iterables, **kwargs):
"""Returns an iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
i... |
Wrapper for non - picklable object to use cloudpickle to serialize them. | def wrap_non_picklable_objects(obj, keep_wrapper=True):
"""Wrapper for non-picklable object to use cloudpickle to serialize them.
Note that this wrapper tends to slow down the serialization process as it
is done with cloudpickle which is typically slower compared to pickle. The
proper way to solve seri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.