_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q271600 | parse_agi_result | test | def parse_agi_result(line):
"""Parse AGI results using Regular expression.
AGI Result examples::
100 result=0 Trying...
200 result=0
200 result=-1
200 result=132456
200 result= (timeout)
510 Invalid or unknown command
520-Invalid command syntax. Proper usage follows:
int() argument must be a string, a bytes-like object or a number, not
'NoneType'
HANGUP
"""
# print("--------------\n", line)
if line == 'HANGUP':
return {'error': 'AGIResultHangup',
| python | {
"resource": ""
} |
q271601 | agi_code_check | test | def agi_code_check(code=None, response=None, line=None):
"""
Check the AGI code and return a dict to help on error handling.
"""
code = int(code)
response = response or ""
result = {'status_code': code, 'result': ('', ''), 'msg': ''}
if code == 100:
result['msg'] = line
elif code == 200:
for key, value, data in re_kv.findall(response):
result[key] = (value, data)
# If user hangs up... we get 'hangup' in the data
if data == 'hangup':
return {
'error': 'AGIResultHangup',
'msg': 'User hungup during execution'}
elif key == 'result' and value == '-1':
return {
'error': 'AGIAppError',
| python | {
"resource": ""
} |
q271602 | IdGenerator.reset | test | def reset(cls, uid=None):
"""Mostly used for unit testing. Allow to use a static uuid and reset
all counter"""
for instance in cls.instances:
if uid:
| python | {
"resource": ""
} |
q271603 | IdGenerator.get_instances | test | def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
| python | {
"resource": ""
} |
q271604 | get_data | test | def get_data(path):
"""
Returns data from a package directory.
'path' should be an absolute path.
"""
# Run the imported setup to get the metadata.
with FakeContext(path):
with SetupMonkey() as sm:
try:
distro = run_setup('setup.py', stop_after='config')
metadata = {'_setuptools': sm.used_setuptools}
for k, v in distro.metadata.__dict__.items():
if k[0] == '_' or not v:
continue
if all(not x for x in v):
continue
metadata[k] = v
if sm.used_setuptools:
| python | {
"resource": ""
} |
q271605 | get_primary_keys | test | def get_primary_keys(model):
"""Get primary key properties for a SQLAlchemy model.
:param model: SQLAlchemy model class
"""
mapper = model.__mapper__
| python | {
"resource": ""
} |
q271606 | Related._deserialize | test | def _deserialize(self, value, *args, **kwargs):
"""Deserialize a serialized value to a model instance.
If the parent schema is transient, create a new (transient) instance.
Otherwise, attempt to find an existing instance in the database.
:param value: The value to deserialize.
"""
if not isinstance(value, dict):
if len(self.related_keys) != 1:
self.fail(
| python | {
"resource": ""
} |
q271607 | Related._get_existing_instance | test | def _get_existing_instance(self, query, value):
"""Retrieve the related object from an existing instance in the DB.
:param query: A SQLAlchemy `Query <sqlalchemy.orm.query.Query>` object.
:param value: The serialized value to mapto an existing instance.
:raises NoResultFound: if there is no matching record.
"""
if self.columns:
result = query.filter_by(
**{prop.key: value.get(prop.key) for prop in self.related_keys}
| python | {
"resource": ""
} |
q271608 | SchemaMeta.get_declared_fields | test | def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls):
"""Updates declared fields with fields converted from the SQLAlchemy model
passed as the `model` class Meta option.
"""
opts = klass.opts
Converter = opts.model_converter
converter = Converter(schema_cls=klass)
declared_fields = super(SchemaMeta, mcs).get_declared_fields(
| python | {
"resource": ""
} |
q271609 | ModelSchema.load | test | def load(self, data, session=None, instance=None, transient=False, *args, **kwargs):
"""Deserialize data to internal representation.
:param session: Optional SQLAlchemy session.
:param instance: Optional existing instance to modify.
:param transient: Optional switch to allow transient instantiation.
| python | {
"resource": ""
} |
q271610 | ModelSchema._split_model_kwargs_association | test | def _split_model_kwargs_association(self, data):
"""Split serialized attrs to ensure association proxies are passed separately.
This is necessary for Python < 3.6.0, as the order in which kwargs are passed
is non-deterministic, and associations must be parsed by sqlalchemy after their
intermediate relationship, unless their `creator` has been set.
Ignore invalid keys at this point - behaviour for unknowns should be
handled elsewhere.
:param data: serialized dictionary of attrs to split on association_proxy.
"""
association_attrs = {
key: value
| python | {
"resource": ""
} |
q271611 | gc | test | def gc():
"""Deletes old stellar tables that are not used anymore"""
def after_delete(database):
click.echo("Deleted table %s" % database)
| python | {
"resource": ""
} |
q271612 | snapshot | test | def snapshot(name):
"""Takes a snapshot of the database"""
app = get_app()
upgrade_from_old_version(app)
name = name or app.default_snapshot_name
if app.get_snapshot(name):
click.echo("Snapshot with name %s already exists" % name)
sys.exit(1)
else:
| python | {
"resource": ""
} |
q271613 | list | test | def list():
"""Returns a list of snapshots"""
snapshots = get_app().get_snapshots()
click.echo('\n'.join(
'%s: %s' % (
s.snapshot_name,
| python | {
"resource": ""
} |
q271614 | restore | test | def restore(name):
"""Restores the database from a snapshot"""
app = get_app()
if not name:
snapshot = app.get_latest_snapshot()
if not snapshot:
click.echo(
"Couldn't find any snapshots for project %s" %
load_config()['project_name']
)
sys.exit(1)
else:
snapshot = app.get_snapshot(name)
if not snapshot:
click.echo(
"Couldn't find snapshot with name %s.\n"
"You can list snapshots with 'stellar list'" % name
)
sys.exit(1)
# Check if slaves are ready
if not snapshot.slaves_ready:
if app.is_copy_process_running(snapshot):
sys.stdout.write(
'Waiting for background process(%s) to finish' %
snapshot.worker_pid
)
sys.stdout.flush()
| python | {
"resource": ""
} |
q271615 | remove | test | def remove(name):
"""Removes a snapshot"""
app = get_app()
snapshot = app.get_snapshot(name)
if not snapshot:
click.echo("Couldn't find snapshot %s" % name)
| python | {
"resource": ""
} |
q271616 | rename | test | def rename(old_name, new_name):
"""Renames a snapshot"""
app = get_app()
snapshot = app.get_snapshot(old_name)
if not snapshot:
click.echo("Couldn't find snapshot %s" % old_name)
sys.exit(1)
new_snapshot = app.get_snapshot(new_name)
if new_snapshot:
click.echo("Snapshot with name %s already | python | {
"resource": ""
} |
q271617 | replace | test | def replace(name):
"""Replaces a snapshot"""
app = get_app()
snapshot = app.get_snapshot(name)
if not snapshot:
click.echo("Couldn't find snapshot %s" % name)
| python | {
"resource": ""
} |
q271618 | Neg_Sampling_Data_Gen.on_epoch_end | test | def on_epoch_end(self) -> None:
'Updates indexes after each epoch for shuffling'
self.indexes = np.arange(self.nrows)
| python | {
"resource": ""
} |
q271619 | textacy_cleaner | test | def textacy_cleaner(text: str) -> str:
"""
Defines the default function for cleaning text.
This function operates over a list.
"""
return preprocess_text(text,
fix_unicode=True,
lowercase=True,
| python | {
"resource": ""
} |
q271620 | apply_parallel | test | def apply_parallel(func: Callable,
data: List[Any],
cpu_cores: int = None) -> List[Any]:
"""
Apply function to list of elements.
Automatically determines the chunk size.
"""
if not cpu_cores:
cpu_cores = cpu_count()
try:
| python | {
"resource": ""
} |
q271621 | process_text_constructor | test | def process_text_constructor(cleaner: Callable,
tokenizer: Callable,
append_indicators: bool,
start_tok: str,
end_tok: str):
"""Generate a function that will clean and tokenize text."""
def process_text(text):
| python | {
"resource": ""
} |
q271622 | processor.process_text | test | def process_text(self, text: List[str]) -> List[List[str]]:
"""Combine the cleaner and tokenizer."""
process_text = process_text_constructor(cleaner=self.cleaner,
tokenizer=self.tokenizer,
append_indicators=self.append_indicators,
| python | {
"resource": ""
} |
q271623 | processor.parallel_process_text | test | def parallel_process_text(self, data: List[str]) -> List[List[str]]:
"""Apply cleaner -> tokenizer."""
process_text = process_text_constructor(cleaner=self.cleaner,
tokenizer=self.tokenizer,
append_indicators=self.append_indicators,
| python | {
"resource": ""
} |
q271624 | processor.generate_doc_length_stats | test | def generate_doc_length_stats(self):
"""Analyze document length statistics for padding strategy"""
heuristic = self.heuristic_pct
histdf = (pd.DataFrame([(a, b) for a, b in self.document_length_histogram.items()],
columns=['bin', 'doc_count'])
.sort_values(by='bin'))
histdf['cumsum_pct'] = histdf.doc_count.cumsum() / histdf.doc_count.sum()
self.document_length_stats = histdf
self.doc_length_huerestic = histdf.query(f'cumsum_pct >= {heuristic}').bin.head(1).values[0]
logging.warning(' '.join(["Setting maximum document length to",
| python | {
"resource": ""
} |
q271625 | processor.token_count_pandas | test | def token_count_pandas(self):
""" See token counts as pandas dataframe"""
freq_df = pd.DataFrame.from_dict(self.indexer.word_counts, orient='index')
| python | {
"resource": ""
} |
q271626 | map_param_type | test | def map_param_type(param_type):
"""
Perform param type mapping
This requires a bit of logic since this isn't standardized.
If a type doesn't map, assume str
"""
main_type, sub_type = TYPE_INFO_RE.match(param_type).groups()
if main_type in ('list', 'array'):
# Handle no sub-type: "required list"
if sub_type is not None:
sub_type = sub_type.strip()
if not sub_type:
sub_type = 'str'
# Handle list of pairs: "optional list<pair<callsign, | python | {
"resource": ""
} |
q271627 | parse_interfaces | test | def parse_interfaces(interfaces):
"""
Parse the conduit.query json dict response
This performs the logic of parsing the non-standard params dict
and then returning a dict Resource can understand
"""
parsed_interfaces = collections.defaultdict(dict)
for m, d in iteritems(interfaces):
app, func = m.split('.', 1)
method = parsed_interfaces[app][func] = {}
# Make default assumptions since these aren't provided by Phab
method['formats'] = ['json', 'human']
method['method'] = 'POST'
method['optional'] = {}
method['required'] = {}
for name, type_info in iteritems(dict(d['params'])):
# Set the defaults
optionality = 'required'
param_type = 'string'
# Usually in the format: <optionality> <param_type>
type_info = TYPE_INFO_COMMENT_RE.sub('', type_info)
info_pieces = TYPE_INFO_SPLITTER_RE.findall(type_info)
for info_piece in info_pieces:
if info_piece in ('optional', 'required'):
| python | {
"resource": ""
} |
q271628 | BidictBase.inverse | test | def inverse(self):
"""The inverse of this bidict.
*See also* :attr:`inv`
"""
# Resolve and return a strong reference to the inverse bidict.
# One may be stored in self._inv already.
if self._inv is not None:
return self._inv
# Otherwise a weakref is stored in self._invweak. Try to get a strong ref from it.
inv = self._invweak()
if inv is not None:
return inv
| python | {
"resource": ""
} |
q271629 | BidictBase._update_with_rollback | test | def _update_with_rollback(self, on_dup, *args, **kw):
"""Update, rolling back on failure."""
writelog = []
appendlog = writelog.append
dedup_item = self._dedup_item
write_item = self._write_item
for (key, val) in _iteritems_args_kw(*args, **kw):
try:
dedup_result = dedup_item(key, val, on_dup)
except DuplicationError:
undo_write = self._undo_write
for dedup_result, write_result | python | {
"resource": ""
} |
q271630 | BidictBase.copy | test | def copy(self):
"""A shallow copy."""
# Could just ``return self.__class__(self)`` here instead, but the below is faster. It uses
# __new__ to create a copy instance while bypassing its __init__, which would result
# in copying this bidict's items into the copy instance one at a time. Instead, make whole
# copies of each of the backing mappings, and make them the backing mappings of the copy,
| python | {
"resource": ""
} |
q271631 | OrderedBidictBase.copy | test | def copy(self):
"""A shallow copy of this ordered bidict."""
# Fast copy implementation bypassing __init__. See comments in :meth:`BidictBase.copy`.
copy = self.__class__.__new__(self.__class__)
sntl = _Sentinel()
fwdm = self._fwdm.copy()
invm = self._invm.copy()
cur = sntl
nxt = sntl.nxt
for (key, val) in iteritems(self):
nxt = _Node(cur, sntl)
cur.nxt = fwdm[key] = invm[val] = nxt
| python | {
"resource": ""
} |
q271632 | OrderedBidictBase.equals_order_sensitive | test | def equals_order_sensitive(self, other):
"""Order-sensitive equality check.
*See also* :ref:`eq-order-insensitive`
"""
# Same short-circuit as BidictBase.__eq__. Factoring out not worth function call overhead.
if | python | {
"resource": ""
} |
q271633 | inverted | test | def inverted(arg):
"""Yield the inverse items of the provided object.
If *arg* has a :func:`callable` ``__inverted__`` attribute,
return the result of calling it.
Otherwise, return an iterator over the | python | {
"resource": ""
} |
q271634 | OrderedBidict.clear | test | def clear(self):
"""Remove all items."""
self._fwdm.clear()
| python | {
"resource": ""
} |
q271635 | OrderedBidict.move_to_end | test | def move_to_end(self, key, last=True):
"""Move an existing key to the beginning or end of this ordered bidict.
The item is moved to the end if *last* is True, else to the beginning.
:raises KeyError: if the key does not exist
"""
node = self._fwdm[key]
node.prv.nxt = node.nxt
node.nxt.prv = node.prv
sntl = self._sntl
if last:
last = sntl.prv
| python | {
"resource": ""
} |
q271636 | write_temp_file | test | def write_temp_file(text=""):
"""Create a new temporary file and write some initial text to it.
:param text: the text to write to the temp file
:type text: str | python | {
"resource": ""
} |
q271637 | get_contacts | test | def get_contacts(address_books, query, method="all", reverse=False,
group=False, sort="first_name"):
"""Get a list of contacts from one or more address books.
:param address_books: the address books to search
:type address_books: list(address_book.AddressBook)
:param query: a search query to select contacts
:type quer: str
:param method: the search method, one of "all", "name" or "uid"
:type method: str
:param reverse: reverse the order of the returned contacts
:type reverse: bool
:param group: group results by address book
:type group: bool
:param sort: the field to use for sorting, one of "first_name", "last_name"
:type sort: str
:returns: contacts from the address_books that match the query
:rtype: list(CarddavObject)
"""
# Search for the contacts in all address books.
contacts = []
for address_book in address_books:
contacts.extend(address_book.search(query, method=method))
# Sort the contacts.
if group:
if sort == "first_name":
return sorted(contacts, reverse=reverse, key=lambda x: (
unidecode(x.address_book.name).lower(),
unidecode(x.get_first_name_last_name()).lower()))
elif sort == "last_name":
return sorted(contacts, reverse=reverse, key=lambda x: (
| python | {
"resource": ""
} |
q271638 | merge_args_into_config | test | def merge_args_into_config(args, config):
"""Merge the parsed arguments from argparse into the config object.
:param args: the parsed command line arguments
:type args: argparse.Namespace
:param config: the parsed config file
:type config: config.Config
:returns: the merged config object
:rtype: config.Config
"""
# display by name: first or last name
if "display" in args and args.display:
config.set_display_by_name(args.display)
# group by address book
if "group_by_addressbook" in args and args.group_by_addressbook:
config.set_group_by_addressbook(True)
# reverse contact list
if "reverse" in args and args.reverse:
config.set_reverse(True)
# sort criteria: first or last name
if "sort" in args and args.sort:
config.sort = args.sort
# preferred vcard version
if "vcard_version" in args and args.vcard_version:
config.set_preferred_vcard_version(args.vcard_version)
| python | {
"resource": ""
} |
q271639 | load_address_books | test | def load_address_books(names, config, search_queries):
"""Load all address books with the given names from the config.
:param names: the address books to load
:type names: list(str)
:param config: the config instance to use when looking up address books
:type config: config.Config
:param search_queries: a mapping of address book names to search queries
:type search_queries: dict
:yields: the loaded address books
:ytype: addressbook.AddressBook
"""
all_names = {str(book) for book in config.abooks}
if not names:
names = all_names
elif not all_names.issuperset(names):
sys.exit('Error: The entered address books "{}" do not exist.\n'
| python | {
"resource": ""
} |
q271640 | prepare_search_queries | test | def prepare_search_queries(args):
"""Prepare the search query string from the given command line args.
Each address book can get a search query string to filter vcards befor
loading them. Depending on the question if the address book is used for
source or target searches different regexes have to be combined into one
search string.
:param args: the parsed command line
:type args: argparse.Namespace
:returns: a dict mapping abook names to their loading queries, if the query
is None it means that all cards should be loaded
:rtype: dict(str:str or None)
"""
# get all possible search queries for address book parsing
source_queries = []
target_queries = []
if "source_search_terms" in args and args.source_search_terms:
escaped_term = ".*".join(re.escape(x)
for x in args.source_search_terms)
source_queries.append(escaped_term)
args.source_search_terms = escaped_term
if "search_terms" in args and args.search_terms:
escaped_term = ".*".join(re.escape(x) for x in args.search_terms)
source_queries.append(escaped_term)
args.search_terms = escaped_term
if "target_contact" in args and args.target_contact:
escaped_term = re.escape(args.target_contact)
target_queries.append(escaped_term)
args.target_contact = escaped_term
if "uid" in args and args.uid:
source_queries.append(args.uid)
if "target_uid" in args and args.target_uid:
target_queries.append(args.target_uid)
# create and return regexp, None means that no query is given and hence all
# contacts should be searched.
source_queries = "^.*(%s).*$" % ')|('.join(source_queries) \
if source_queries else None
target_queries = "^.*(%s).*$" % ')|('.join(target_queries) \
| python | {
"resource": ""
} |
q271641 | new_subcommand | test | def new_subcommand(selected_address_books, input_from_stdin_or_file,
open_editor):
"""Create a new contact.
:param selected_address_books: a list of addressbooks that were selected on
the command line
:type selected_address_books: list of address_book.AddressBook
:param input_from_stdin_or_file: the data for the new contact as a yaml
formatted string
:type input_from_stdin_or_file: str
:param open_editor: whether to open the new contact in the edior after
creation
:type open_editor: bool
:returns: None
:rtype: None
"""
# ask for address book, in which to create the new contact
selected_address_book = choose_address_book_from_list(
| python | {
"resource": ""
} |
q271642 | birthdays_subcommand | test | def birthdays_subcommand(vcard_list, parsable):
"""Print birthday contact table.
:param vcard_list: the vcards to search for matching entries which should
be printed
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t)
:type parsable: bool
:returns: None
:rtype: None
"""
# filter out contacts without a birthday date
vcard_list = [
vcard for vcard in vcard_list if vcard.get_birthday() is not None]
# sort by date (month and day)
# The sort function should work for strings and datetime objects. All
# strings will besorted before any datetime objects.
vcard_list.sort(
key=lambda x: (x.get_birthday().month, x.get_birthday().day)
if isinstance(x.get_birthday(), datetime.datetime)
else (0, 0, x.get_birthday()))
# add to string list
birthday_list = []
for vcard in vcard_list:
date = vcard.get_birthday()
if parsable:
if config.display_by_name() == "first_name":
birthday_list.append("%04d.%02d.%02d\t%s"
% (date.year, date.month, date.day,
vcard.get_first_name_last_name()))
else:
birthday_list.append("%04d.%02d.%02d\t%s"
% (date.year, date.month, date.day,
vcard.get_last_name_first_name()))
else:
| python | {
"resource": ""
} |
q271643 | phone_subcommand | test | def phone_subcommand(search_terms, vcard_list, parsable):
"""Print a phone application friendly contact table.
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries which should
be printed
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t)
:type parsable: bool
:returns: None
:rtype: None
"""
all_phone_numbers_list = []
matching_phone_number_list = []
for vcard in vcard_list:
for type, number_list in sorted(vcard.get_phone_numbers().items(),
key=lambda k: k[0].lower()):
for number in sorted(number_list):
if config.display_by_name() == "first_name":
name = vcard.get_first_name_last_name()
else:
name = vcard.get_last_name_first_name()
# create output lines
line_formatted = "\t".join([name, type, number])
line_parsable = "\t".join([number, name, type])
if parsable:
# parsable option: start with phone number
phone_number_line = line_parsable
else:
# else: start with name
phone_number_line = line_formatted
if re.search(search_terms,
"%s\n%s" % (line_formatted, line_parsable),
re.IGNORECASE | re.DOTALL):
matching_phone_number_list.append(phone_number_line)
elif len(re.sub("\D", "", search_terms)) >= 3:
# The user likely | python | {
"resource": ""
} |
q271644 | list_subcommand | test | def list_subcommand(vcard_list, parsable):
"""Print a user friendly contacts table.
:param vcard_list: the vcards to print
:type vcard_list: list of carddav_object.CarddavObject
:param parsable: machine readable output: columns devided by tabulator (\t)
:type parsable: bool
:returns: None
:rtype: None
"""
if not vcard_list:
if not parsable:
print("Found no contacts")
sys.exit(1)
elif parsable:
contact_line_list = []
for vcard in vcard_list:
if config.display_by_name() == "first_name":
| python | {
"resource": ""
} |
q271645 | modify_subcommand | test | def modify_subcommand(selected_vcard, input_from_stdin_or_file, open_editor):
"""Modify a contact in an external editor.
:param selected_vcard: the contact to modify
:type selected_vcard: carddav_object.CarddavObject
:param input_from_stdin_or_file: new data from stdin (or a file) that
should be incorperated into the contact, this should be a yaml
formatted string
:type input_from_stdin_or_file: str
:param open_editor: whether to open the new contact in the edior after
creation
:type open_editor: bool
:returns: None
:rtype: None
"""
# show warning, if vcard version of selected contact is not 3.0 or 4.0
if selected_vcard.get_version() not in config.supported_vcard_versions:
print("Warning:\nThe selected contact is based on vcard version %s "
"but khard only supports the creation and modification of vcards"
" with version 3.0 and 4.0.\nIf you proceed, the contact will be"
" converted to vcard version %s but beware: This could corrupt "
"the contact file or cause data loss."
% (selected_vcard.get_version(),
config.get_preferred_vcard_version()))
while True:
input_string = input("Do you want to proceed anyway (y/n)? ")
if input_string.lower() in ["", "n", "q"]:
print("Canceled")
sys.exit(0)
if input_string.lower() == "y":
break
# if there is some data in stdin
if input_from_stdin_or_file:
# create new contact from stdin
try:
new_contact = \
CarddavObject.from_existing_contact_with_new_user_input(
selected_vcard, input_from_stdin_or_file,
config.localize_dates())
| python | {
"resource": ""
} |
q271646 | remove_subcommand | test | def remove_subcommand(selected_vcard, force):
"""Remove a contact from the addressbook.
:param selected_vcard: the contact to delete
:type selected_vcard: carddav_object.CarddavObject
:param force: delete without confirmation
:type force: bool
:returns: None
:rtype: None
"""
if not force:
while True:
input_string = input(
"Deleting contact %s from address book %s. Are you sure? "
"(y/n): " % (selected_vcard, selected_vcard.address_book))
| python | {
"resource": ""
} |
q271647 | source_subcommand | test | def source_subcommand(selected_vcard, editor):
"""Open the vcard file for a contact in an external editor.
:param selected_vcard: the contact to edit
:type selected_vcard: carddav_object.CarddavObject
:param editor: the eitor command to use
:type | python | {
"resource": ""
} |
q271648 | merge_subcommand | test | def merge_subcommand(vcard_list, selected_address_books, search_terms,
target_uid):
"""Merge two contacts into one.
:param vcard_list: the vcards from which to choose contacts for mergeing
:type vcard_list: list of carddav_object.CarddavObject
:param selected_address_books: the addressbooks to use to find the target
contact
:type selected_address_books: list(addressbook.AddressBook)
:param search_terms: the search terms to find the target contact
:type search_terms: str
:param target_uid: the uid of the target contact or empty
:type target_uid: str
:returns: None
:rtype: None
"""
# Check arguments.
if target_uid != "" and search_terms != "":
print("You can not specify a target uid and target search terms for a "
"merge.")
sys.exit(1)
# Find possible target contacts.
if target_uid != "":
target_vcards = get_contacts(selected_address_books, target_uid,
method="uid")
# We require that the uid given can uniquely identify a contact.
| python | {
"resource": ""
} |
q271649 | copy_or_move_subcommand | test | def copy_or_move_subcommand(action, vcard_list, target_address_book_list):
"""Copy or move a contact to a different address book.
:action: the string "copy" or "move" to indicate what to do
:type action: str
:param vcard_list: the contact list from which to select one for the action
:type vcard_list: list of carddav_object.CarddavObject
:param target_address_book_list: the list of target address books
:type target_address_book_list: list(addressbook.AddressBook)
:returns: None
:rtype: None
"""
# get the source vcard, which to copy or move
source_vcard = choose_vcard_from_list(
"Select contact to %s" % action.title(), vcard_list)
if source_vcard is None:
print("Found no contact")
sys.exit(1)
else:
print("%s contact %s from address book %s"
% (action.title(), source_vcard, source_vcard.address_book))
# get target address book
if len(target_address_book_list) == 1 \
and target_address_book_list[0] == source_vcard.address_book:
print("The address book %s already contains the contact %s"
% (target_address_book_list[0], source_vcard))
sys.exit(1)
else:
available_address_books = [abook for abook in target_address_book_list
if abook != source_vcard.address_book]
selected_target_address_book = choose_address_book_from_list(
"Select target address book", available_address_books)
if selected_target_address_book is None:
print("Error: address book list is empty")
sys.exit(1)
# check if a contact already exists in the target address book
target_vcard = choose_vcard_from_list(
"Select target contact which to overwrite",
get_contact_list_by_user_selection([selected_target_address_book],
source_vcard.get_full_name(), True))
# If the target contact doesn't exist, move or copy the source contact into
# the target address book without further questions.
if target_vcard is None:
copy_contact(source_vcard, selected_target_address_book,
action == "move")
else:
if source_vcard == target_vcard:
# source and target contact are identical
print("Target contact: %s" % target_vcard)
if action == "move":
copy_contact(source_vcard, selected_target_address_book, True)
else:
print("The selected contacts are already identical")
else:
| python | {
"resource": ""
} |
q271650 | Actions.get_action | test | def get_action(cls, alias):
"""Find the name of the action for the supplied alias. If no action is
asociated with the given alias, None is returned.
:param alias: the alias to look up
:type alias: str
:rturns: the name of the corresponding action or None
| python | {
"resource": ""
} |
q271651 | Config._convert_boolean_config_value | test | def _convert_boolean_config_value(config, name, default=True):
"""Convert the named field to bool.
The current value should be one of the strings "yes" or "no". It will
be replaced with its boolean counterpart. If the field is not present
in the config object, the default value is used.
:param config: the config section where to set the option
:type config: configobj.ConfigObj
:param name: the name of the option to convert
:type name: str
:param default: the default value to use if the option was not
previously set
:type default: bool | python | {
"resource": ""
} |
q271652 | CarddavObject.new_contact | test | def new_contact(cls, address_book, supported_private_objects, version,
localize_dates):
"""Use this to create a new and empty contact."""
| python | {
"resource": ""
} |
q271653 | CarddavObject.from_file | test | def from_file(cls, address_book, filename, supported_private_objects,
localize_dates):
"""
Use this if you want to create a new contact from an existing .vcf
file.
"""
| python | {
"resource": ""
} |
q271654 | CarddavObject.from_user_input | test | def from_user_input(cls, address_book, user_input,
supported_private_objects, version, localize_dates):
"""Use this if you want to create a new contact from user input."""
contact | python | {
"resource": ""
} |
q271655 | CarddavObject.from_existing_contact_with_new_user_input | test | def from_existing_contact_with_new_user_input(cls, contact, user_input,
localize_dates):
"""
Use this if you want to clone an existing contact and replace its data
with new user input in one step.
"""
contact = | python | {
"resource": ""
} |
q271656 | CarddavObject._get_names_part | test | def _get_names_part(self, part):
"""Get some part of the "N" entry in the vCard as a list
:param part: the name to get e.g. "prefix" or "given"
:type part: str
:returns: a list of entries for this name part
:rtype: list(str)
"""
try:
the_list = getattr(self.vcard.n.value, part)
except AttributeError:
return []
| python | {
"resource": ""
} |
q271657 | CarddavObject._add_category | test | def _add_category(self, categories):
""" categories variable must be a list """
categories_obj = self.vcard.add('categories')
| python | {
"resource": ""
} |
q271658 | CarddavObject._parse_type_value | test | 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
:param supported_types: all allowed standard types
:type supported_types: list(str)
:returns: tuple of standard and custom types and pref integer
:rtype: tuple(list(str), list(str), int)
"""
custom_types = []
standard_types = []
pref = 0
for type in types:
type = type.strip()
if type:
if type.lower() in supported_types:
standard_types.append(type)
elif type.lower() == "pref":
| python | {
"resource": ""
} |
q271659 | list_to_string | test | 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: the recursively joined list
:rtype: | python | {
"resource": ""
} |
q271660 | string_to_date | test | 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-mm-ddThh:mm:ss, yyyymmddThhmmssZ,
# yyyy-mm-ddThh:mm:ssZ.
for format_string in ("--%m%d", "--%m-%d", "%Y%m%d", "%Y-%m-%d",
"%Y%m%dT%H%M%S", "%Y-%m-%dT%H:%M:%S",
"%Y%m%dT%H%M%SZ", "%Y-%m-%dT%H:%M:%SZ"):
try:
| python | {
"resource": ""
} |
q271661 | AddressBook._compare_uids | test | 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 shortes unequal initial substrings
| python | {
"resource": ""
} |
q271662 | AddressBook._search_all | test | 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 | re.DOTALL)
for contact in self.contacts.values():
# search in all contact fields
contact_details = contact.print_vcard()
if regexp.search(contact_details) is not None:
yield contact
| python | {
"resource": ""
} |
q271663 | AddressBook._search_names | test | 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.IGNORECASE | re.DOTALL)
| python | {
"resource": ""
} |
q271664 | AddressBook._search_uid | test | 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 full UID and try to match it
# exactly.
yield self.contacts[query]
except KeyError:
| python | {
"resource": ""
} |
q271665 | AddressBook.search | test | 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
:param method: the type of fileds to use when seaching
:type method: str
:returns: all found contacts
:rtype: list(carddav_object.CarddavObject)
"""
logging.debug('address book %s, searching with %s', self.name, query)
if not self._loaded:
self.load(query)
if method == | python | {
"resource": ""
} |
q271666 | AddressBook.get_short_uid_dict | test | 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: the contacts mapped by the shortes unique prefix of their UID
:rtype: dict(str: CarddavObject)
"""
if self._short_uids is None:
if not self._loaded:
self.load(query)
if not self.contacts:
self._short_uids = {}
elif len(self.contacts) == 1:
self._short_uids = {uid[0:1]: contact
for uid, contact in self.contacts.items()}
else:
self._short_uids = {}
sorted_uids = sorted(self.contacts)
# Prepare for the loop; the first and last items are handled
# seperatly.
| python | {
"resource": ""
} |
q271667 | AddressBook.get_short_uid | test | 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:
| python | {
"resource": ""
} |
q271668 | VdirAddressBook._find_vcard_files | test | 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: str
:param search_in_source_files: apply search regexp directly on the .vcf files to speed up parsing (less accurate)
:type search_in_source_files: bool
:returns: the paths of the vcard files
:rtype: generator
"""
files = glob.glob(os.path.join(self.path, "*.vcf"))
| python | {
"resource": ""
} |
q271669 | VdirAddressBook.load | test | 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
:param search_in_source_files: apply search regexp directly on the .vcf files to speed up parsing (less accurate)
:type search_in_source_files: bool
:returns: the number of successfully loaded cards and the number of
errors
:rtype: int, int
:throws: AddressBookParseError
"""
if self._loaded:
return
logging.debug('Loading Vdir %s with query %s', self.name, query)
errors = 0
for filename in self._find_vcard_files(
search=query, search_in_source_files=search_in_source_files):
try:
card = CarddavObject.from_file(self, filename,
self._private_objects,
self._localize_dates)
except (IOError, vobject.base.ParseError) as err:
verb = "open" if isinstance(err, IOError) else "parse"
logging.debug("Error: Could not %s file %s\n%s", verb,
filename, err)
if self._skip:
errors += 1
else:
# FIXME: This should throw an apropriate exception and the
# sys.exit should be called somewhere closer to the command
# line parsing.
logging.error(
"The vcard file %s of address book %s could not be "
| python | {
"resource": ""
} |
q271670 | AddressBookCollection.get_abook | test | 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
| python | {
"resource": ""
} |
q271671 | Assembler.avail_archs | test | 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: (KS_ARCH_HEXAGON, KS_MODE_BIG_ENDIAN),
MIPS32: (KS_ARCH_MIPS, KS_MODE_MIPS32),
MIPS64: (KS_ARCH_MIPS, KS_MODE_MIPS64),
PPC32: (KS_ARCH_PPC, KS_MODE_PPC32),
PPC64: (KS_ARCH_PPC, KS_MODE_PPC64),
| python | {
"resource": ""
} |
q271672 | Disassembler.avail_archs | test | 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),
| python | {
"resource": ""
} |
q271673 | getargspec_permissive | test | 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()`. So, an exception is raised
when calling `argh.dispatch_command(cythonCompiledFunc)`. However,
the CyFunctions do have perfectly usable `.func_code` and
`.func_defaults` which is all `inspect.getargspec` needs.
This function just copies `inspect.getargspec()` from the standard
library but relaxes the test to a more duck-typing one of having
both `.func_code` and `.func_defaults` attributes.
"""
if inspect.ismethod(func):
| python | {
"resource": ""
} |
q271674 | dispatch | test | 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 relevant
function and prints the result.
The target function should expect one positional argument: the
:class:`argparse.Namespace` object. However, if the function is decorated with
:func:`~argh.decorators.plain_signature`, the positional and named
arguments from the namespace object are passed to the function instead
of the object itself.
:param parser:
the ArgumentParser instance.
:param argv:
a list of strings representing the arguments. If `None`, ``sys.argv``
is used instead. Default is `None`.
:param add_help_command:
if `True`, converts first positional argument "help" to a keyword
argument so that ``help foo`` becomes ``foo --help`` and displays usage
information for "foo". Default is `True`.
:param output_file:
A file-like object for output. If `None`, the resulting lines are
collected and returned as a string. Default is ``sys.stdout``.
:param errors_file:
Same as `output_file` but for ``sys.stderr``.
:param raw_output:
If `True`, results are written to the output file raw, without adding
whitespaces or newlines between yielded strings. Default is `False`.
:param completion:
If `True`, shell tab completion is enabled. Default is `True`. (You
will also need to install it.) See :mod:`argh.completion`.
:param skip_unknown_args:
If `True`, unknown arguments do not cause an error
(`ArgumentParser.parse_known_args` is used).
:param namespace:
An `argparse.Namespace`-like object. By default an
:class:`ArghNamespace` object is used. Please note that support for
combined default and nested functions may be broken if a different
type of object is forced.
By default the exceptions are not wrapped and will propagate. The only
exception that is always wrapped is :class:`~argh.exceptions.CommandError`
which is interpreted as an expected event so the traceback is hidden.
You can also mark arbitrary exceptions as "wrappable" by using the
:func:`~argh.decorators.wrap_errors` decorator.
"""
if completion:
autocomplete(parser)
if argv is None:
argv = sys.argv[1:]
if add_help_command:
if argv and argv[0] == 'help':
argv.pop(0)
argv.append('--help')
if skip_unknown_args:
parse_args = parser.parse_known_args
else:
| python | {
"resource": ""
} |
q271675 | safe_input | test | 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 | python | {
"resource": ""
} |
q271676 | encode_output | test | 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 `str`
(unicode) and breaks on `bytes`.
It is OK to simply assume that everything is Unicode unless special
handling is introduced in the client code.
Thus, no additional processing is performed.
Python 2.x
`sys.stdout` is a file-like object that accepts `str` (bytes)
and breaks when `unicode` is passed to `sys.stdout.write()`. | python | {
"resource": ""
} |
q271677 | _guess | test | 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'
# guess type/action from default value
value = kwargs.get('default')
if value is not None:
if isinstance(value, bool):
if kwargs.get('action') is None:
# infer action from default value
guessed['action'] = 'store_false' if value else 'store_true'
elif kwargs.get('type') is | python | {
"resource": ""
} |
q271678 | add_commands | test | 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.ArgumentParser` instance.
:param functions:
a list of functions. A subparser is created for each of them.
If the function is decorated with :func:`~argh.decorators.arg`, the
arguments are passed to :class:`argparse.ArgumentParser.add_argument`.
See also :func:`~argh.dispatching.dispatch` for requirements
concerning function signatures. The command name is inferred from the
function name. Note that the underscores in the name are replaced with
hyphens, i.e. function name "foo_bar" becomes command name "foo-bar".
:param namespace:
an optional string representing the group of commands. For example, if
a command named "hello" is added without the namespace, it will be
available as "prog.py hello"; if the namespace if specified as "greet",
then the command will be accessible as "prog.py greet hello". The
namespace itself is not callable, so "prog.py greet" will fail and only
display a help message.
:param func_kwargs:
a `dict` of keyword arguments to be passed to each nested ArgumentParser
instance created per command (i.e. per function). Members of this
dictionary have the highest priority, so a function's docstring is
overridden by a `help` in `func_kwargs` (if present).
:param namespace_kwargs:
a `dict` of keyword arguments to be passed to the nested ArgumentParser
instance under given `namespace`.
Deprecated params that should be moved into `namespace_kwargs`:
:param title:
passed to :meth:`argparse.ArgumentParser.add_subparsers` as `title`.
.. deprecated:: 0.26.0
Please use `namespace_kwargs` instead.
:param description:
passed to :meth:`argparse.ArgumentParser.add_subparsers` as
`description`.
.. deprecated:: 0.26.0
Please use `namespace_kwargs` instead.
:param help:
passed to :meth:`argparse.ArgumentParser.add_subparsers` as `help`.
.. deprecated:: 0.26.0
Please use `namespace_kwargs` instead.
.. note::
This function modifies the parser object. Generally side effects are
bad practice but we don't seem to have any choice as ArgumentParser is
pretty opaque.
You may prefer :class:`~argh.helpers.ArghParser.add_commands` for a bit
more predictable API.
.. note::
An attempt to add commands to a parser which already has a default
function (e.g. added with :func:`~argh.assembling.set_default_command`)
results in `AssemblingError`.
"""
# FIXME "namespace" is a correct name but it clashes with the "namespace"
# that represents arguments (argparse.Namespace and our ArghNamespace).
# We should rename the argument here.
if DEST_FUNCTION in parser._defaults:
_require_support_for_default_command_with_subparsers()
namespace_kwargs = namespace_kwargs | python | {
"resource": ""
} |
q271679 | named | test | 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 available only as ``load``. To add aliases
without | python | {
"resource": ""
} |
q271680 | arg | test | 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 can be easily guessed (e.g. you don't have to specify type
or action when an `int` or `bool` default value is supplied).
Typical use cases:
- In combination with :func:`expects_obj` (which is not recommended);
- in combination with ordinary function signatures to add details that
cannot be expressed with that syntax (e.g. help message).
Usage::
from argh import arg
@arg('path', help='path to the file to load')
@arg('--format', choices=['yaml','json'])
@arg('-v', '--verbosity', choices=range(0,3), default=2)
def load(path, something=None, format='json', dry_run=False, verbosity=1):
loaders = {'json': json.load, 'yaml': yaml.load}
loader = loaders[args.format]
data = loader(args.path)
if not args.dry_run:
if verbosity < 1:
print('saving to the database')
put_to_database(data)
In this example:
- `path` declaration is extended with `help`; | python | {
"resource": ""
} |
q271681 | confirm | test | 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:`Enter`
without typing in a choice. If `True`, default choice is "yes". If
`False`, it is "no". If `None` the prompt keeps reappearing until user
types in a choice (not necessarily acceptable) or until the number of
iteration reaches the limit. Default is `None`.
:param skip:
`bool`; if `True`, no interactive prompt is used and default choice is
returned (useful for batch mode). Default is `False`.
Usage::
def delete(key, silent=False):
item = db.get(Item, args.key)
if confirm('Delete '+item.title, default=True, skip=silent):
item.delete()
print('Item deleted.')
else:
print('Operation cancelled.')
Returns `None` on `KeyboardInterrupt` event.
"""
MAX_ITERATIONS = 3
if skip:
| python | {
"resource": ""
} |
q271682 | Query.replace | test | 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
| python | {
"resource": ""
} |
q271683 | Query.like | test | 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 the column definition.
Patterns allow for 4 wildcard characters, whose semantics are as
follows:
* *?* - will match 0 or 1 of any character
* *\** - will match 0 or more of any character
* *+* - will match 1 or more of any character
* *!* - will match exactly 1 of any character
| python | {
"resource": ""
} |
q271684 | Query.cached_result | test | 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 (this is to ensure that any cached
query results are eventually deleted, unless you make the explicit
step to use the PERSIST command).
.. note:: Limit clauses are ignored and not passed.
| python | {
"resource": ""
} |
q271685 | Query.first | test | 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:
| python | {
"resource": ""
} |
q271686 | Query.delete | test | 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 side of a ``OneToMany``,
``ManyToOne``, or ``OneToOne`` relationship.
'''
from .columns import MODELS_REFERENCED
if not self._model._no_fk or self._model._namespace in MODELS_REFERENCED:
raise QueryError("Can't delete entities of models with foreign key relationships")
de = []
| python | {
"resource": ""
} |
q271687 | _on_delete | test | 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=NULL):
pk = ent._pk
if pk in seen_d:
# going to be deleted, don't need to modify
return
col = ent.__class__._columns[attr]
de = de if de is not NULL else col._default
if de in (None, NULL):
setattr(ent, attr, None)
elif callable(col._default):
setattr(ent, attr, col._default())
else:
setattr(ent, attr, col._default)
if pk not in seen_s:
seen_s.add(pk)
to_save.append(ent)
for self in to_delete:
for tbl, attr, action in MODELS_REFERENCED.get(self._namespace, | python | {
"resource": ""
} |
q271688 | redis_prefix_lua | test | def redis_prefix_lua(conn, dest, index, prefix, is_first, pattern=None):
'''
Performs the actual prefix, suffix, and pattern match operations.
'''
tkey = | python | {
"resource": ""
} |
q271689 | estimate_work_lua | test | 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 None else repr(float(args[0]))
args[1] = 'inf' if args[1] is None else repr(float(args[1]))
| python | {
"resource": ""
} |
q271690 | GeneralIndex.search | test | 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. ``'column:string'`` - a plain string will match a word in a
text search on the column
.. note:: Read the documentation about the ``Query`` object
for what is actually passed during text search
2. ``('column', min, max)`` - a numeric column range search,
between min and max (inclusive by default)
.. note:: Read the documentation about the ``Query`` object
for information about open-ended ranges
3. ``['column:string1', 'column:string2']`` - will match any
of the provided words in a text search on the column
4. ``Prefix('column', 'prefix')`` - will match prefixes of
words in a text search on the column
5. ``Suffix('column', 'suffix')`` - will match suffixes of
words in a text search on the column
6. ``Pattern('column', 'pattern')`` - will match patterns over
words in a text search on the column
* *order_by* - A string that names the numeric column by which to
sort the results by. Prefixing with '-' will return results in
descending order
.. note:: While you can technically pass a non-numeric index as an
*order_by* clause, the results will basically be to order the
results by string comparison of the ids (10 will come before 2).
.. note:: If you omit the ``order_by`` argument, results will be
ordered by the last filter. If the last filter was a text
filter, see the previous note. If the last filter was numeric,
| python | {
"resource": ""
} |
q271691 | GeneralIndex.count | test | 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 = | python | {
"resource": ""
} |
q271692 | _connect | test | def _connect(obj):
'''
Tries to get the _conn attribute from a model. Barring that, gets the
global default connection using other methods.
'''
| python | {
"resource": ""
} |
q271693 | FULL_TEXT | test | 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, ''):
return None
elif not isinstance(val, six.string_types):
if six.PY3 and isinstance(val, bytes):
val = val.decode('latin-1')
else:
| python | {
"resource": ""
} |
q271694 | refresh_indices | test | 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
* *block_size* - the maximum number of entities you want to fetch from
Redis at a time, defaulting to 100
This function will yield its progression through re-indexing all of your
entities.
Example use::
for progress, total in refresh_indices(MyModel, block_size=200):
print "%s of %s"%(progress, total)
.. note:: This uses the session object to handle index refresh via calls to
``.commit()``. If you have any outstanding entities known in the
| python | {
"resource": ""
} |
q271695 | clean_old_index | test | 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:
* *model* - the model whose entities you want to reindex
* *block_size* - the maximum number of items to check at a time
defaulting to 100
This function will yield its progression through re-checking all of the
data that could be left over.
Example use::
for progress, total in clean_old_index(MyModel, block_size=200):
print "%s of %s"%(progress, total)
'''
conn = _connect(model)
version = list(map(int, conn.info()['redis_version'].split('.')[:2]))
has_hscan = version >= [2, 8]
pipe = conn.pipeline(True)
prefix = '%s:'%model._namespace
index = prefix + ':'
block_size = max(block_size, 10)
force_hscan = kwargs.get('force_hscan', False)
if (has_hscan or force_hscan) and force_hscan is not None:
max_id = conn.hlen(index)
cursor = None
scanned = 0
while cursor != b'0':
cursor, remove = _scan_index_lua(conn, [index, prefix], [cursor or '0', block_size, 0, 0])
if remove:
_clean_index_lua(conn, [model._namespace], remove)
scanned += block_size
if scanned > max_id:
max_id = scanned + 1
yield scanned, max_id
# need to scan over unique indexes :/
for uniq in chain(model._unique, model._cunique):
name = uniq if isinstance(uniq, six.string_types) else ':'.join(uniq)
idx = prefix + name + ':uidx'
cursor = None
while cursor != b'0':
cursor, remove = _scan_index_lua(conn, [idx, prefix], [cursor or '0', block_size, 1, 0])
if remove:
conn.hdel(idx, *remove)
| python | {
"resource": ""
} |
q271696 | Session.add | test | def add(self, obj):
'''
Adds an entity to the session.
'''
if self.null_session:
return
self._init()
pk = obj._pk
| python | {
"resource": ""
} |
q271697 | Session.get | test | def get(self, pk):
'''
Fetches an entity from the session based on primary key.
'''
| python | {
"resource": ""
} |
q271698 | redis_writer_lua | test | 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():
ldata.extend(pair)
for item in prefix:
item.append(_prefix_score(item[-1]))
for item in suffix:
item.append(_prefix_score(item[-1]))
data = [json.dumps(x, default=_fix_bytes) for x in
(unique, udelete, delete, ldata, keys, scored, prefix, suffix, geo, is_delete, old_data)]
result = _redis_writer_lua(conn, [], [namespace, id] + data)
| python | {
"resource": ""
} |
q271699 | Model.save | test | 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 force a full re-save of the entity.
'''
# handle the pre-commit hooks
was_new = self._new
if was_new:
self._before_insert()
else:
self._before_update()
new = self.to_dict()
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.