INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convert a multi values header to a case - insensitive dict:
def getdict(self, key): """Convert a multi values header to a case-insensitive dict: .. code-block:: python >>> resp = Message({ ... 'Response': 'Success', ... 'ChanVariable': [ ... 'FROM_DID=', 'SIPURI=sip:42@10.10.10.1:4242'], ...
Run a setup script in a somewhat controlled environment and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta - data ( passed as keyword args from script to setup () or the contents of the config files or command - line.
def run_setup(script_name, script_args=None, stop_after="run"): """Run a setup script in a somewhat controlled environment, and return the Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from 'script' to 'setup()', or t...
Returns data from a package directory. path should be an absolute path.
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') ...
Get primary key properties for a SQLAlchemy model.
def get_primary_keys(model): """Get primary key properties for a SQLAlchemy model. :param model: SQLAlchemy model class """ mapper = model.__mapper__ return [mapper.get_property_by_column(column) for column in mapper.primary_key]
Deserialize a serialized value to a model instance.
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. "...
Retrieve the related object from an existing instance in the DB.
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 i...
Add keyword arguments to kwargs ( in - place ) based on the passed in Column <sqlalchemy. schema. Column >.
def _add_column_kwargs(self, kwargs, column): """Add keyword arguments to kwargs (in-place) based on the passed in `Column <sqlalchemy.schema.Column>`. """ if column.nullable: kwargs["allow_none"] = True kwargs["required"] = not column.nullable and not _has_default(co...
Add keyword arguments to kwargs ( in - place ) based on the passed in relationship Property.
def _add_relationship_kwargs(self, kwargs, prop): """Add keyword arguments to kwargs (in-place) based on the passed in relationship `Property`. """ nullable = True for pair in prop.local_remote_pairs: if not pair[0].nullable: if prop.uselist is True: ...
Updates declared fields with fields converted from the SQLAlchemy model passed as the model class Meta option.
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(sc...
Retrieve an existing record by primary key ( s ). If the schema instance is transient return None.
def get_instance(self, data): """Retrieve an existing record by primary key(s). If the schema instance is transient, return None. :param data: Serialized data to inform lookup. """ if self.transient: return None props = get_primary_keys(self.opts.model) ...
Deserialize data to an instance of the model. Update an existing row if specified in self. instance or loaded by primary key ( s ) in the data ; else create a new row.
def make_instance(self, data): """Deserialize data to an instance of the model. Update an existing row if specified in `self.instance` or loaded by primary key(s) in the data; else create a new row. :param data: Data to deserialize. """ instance = self.instance or self.g...
Deserialize data to internal representation.
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 i...
Split serialized attrs to ensure association proxies are passed separately.
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 i...
Deletes old stellar tables that are not used anymore
def gc(): """Deletes old stellar tables that are not used anymore""" def after_delete(database): click.echo("Deleted table %s" % database) app = get_app() upgrade_from_old_version(app) app.delete_orphan_snapshots(after_delete)
Takes a snapshot of the database
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: def before_copy(table_...
Returns a list of snapshots
def list(): """Returns a list of snapshots""" snapshots = get_app().get_snapshots() click.echo('\n'.join( '%s: %s' % ( s.snapshot_name, humanize.naturaltime(datetime.utcnow() - s.created_at) ) for s in snapshots ))
Restores the database from a snapshot
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'] ...
Removes a snapshot
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) sys.exit(1) click.echo("Deleting snapshot %s" % name) app.remove_snapshot(snapshot) click.echo("Deleted")
Renames a snapshot
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...
Replaces a snapshot
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) sys.exit(1) app.remove_snapshot(snapshot) app.create_snapshot(name) click.echo("Replaced snapshot %s" % name)
Initializes Stellar configuration.
def init(): """Initializes Stellar configuration.""" while True: url = click.prompt( "Please enter the url for your database.\n\n" "For example:\n" "PostgreSQL: postgresql://localhost:5432/\n" "MySQL: mysql+pymysql://root@localhost/" ) if u...
Updates indexes after each epoch for shuffling
def on_epoch_end(self) -> None: 'Updates indexes after each epoch for shuffling' self.indexes = np.arange(self.nrows) if self.shuffle: np.random.shuffle(self.indexes)
Defines the default function for cleaning text.
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, transliterate=True, ...
Apply function to list of elements.
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: chunk_size = ceil(l...
Generate a function that will clean and tokenize text.
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 proces...
Combine the cleaner and tokenizer.
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=s...
Apply cleaner - > tokenizer.
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...
Analyze document length statistics for padding strategy
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']) .so...
TODO: update docs
def fit(self, data: List[str], return_tokenized_data: bool = False) -> Union[None, List[List[str]]]: """ TODO: update docs Apply cleaner and tokenzier to raw data and build vocabulary. Parameters ---------- data : List[str] These are ...
See token counts as pandas dataframe
def token_count_pandas(self): """ See token counts as pandas dataframe""" freq_df = pd.DataFrame.from_dict(self.indexer.word_counts, orient='index') freq_df.columns = ['count'] return freq_df.sort_values('count', ascending=False)
Apply cleaner and tokenzier to raw data build vocabulary and return transfomred dataset that is a List [ List [ int ]]. This will use process - based - threading on all available cores.
def fit_transform(self, data: List[str]) -> List[List[int]]: """ Apply cleaner and tokenzier to raw data, build vocabulary and return transfomred dataset that is a List[List[int]]. This will use process-based-threading on all available cores. ex: >...
Transform List of documents into List [ List [ int ]] If transforming a large number of documents consider using the method transform_parallel instead.
def transform(self, data: List[str]) -> List[List[int]]: """ Transform List of documents into List[List[int]] If transforming a large number of documents consider using the method `transform_parallel` instead. ex: >> pp = processor() >> pp.fit(docs) >> ne...
Transform List of documents into List [ List [ int ]]. Uses process based threading on all available cores. If only processing a small number of documents ( < 10k ) then consider using the method transform instead.
def transform_parallel(self, data: List[str]) -> List[List[int]]: """ Transform List of documents into List[List[int]]. Uses process based threading on all available cores. If only processing a small number of documents ( < 10k ) then consider using the method `transform` instead. ...
Vectorize and apply padding on a set of tokenized doucments ex: [[ hello world ] [ goodbye now ]]
def pad(self, docs: List[List[int]]) -> List[List[int]]: """ Vectorize and apply padding on a set of tokenized doucments ex: [['hello, 'world'], ['goodbye', 'now']] """ # First apply indexing on all the rows then pad_sequnces (i found this # faster than trying to do these...
Transforms tokenized text to a sequence of integers. Only top num_words most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments tokenized texts: List [ List [ str ]] # Returns A list of integers.
def tokenized_texts_to_sequences(self, tok_texts): """Transforms tokenized text to a sequence of integers. Only top "num_words" most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments tokenized texts: List[Lis...
Transforms tokenized text to a sequence of integers. Only top num_words most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments tokenized texts: List [ List [ str ]] # Yields Yields individual sequences.
def tokenized_texts_to_sequences_generator(self, tok_texts): """Transforms tokenized text to a sequence of integers. Only top "num_words" most frequent words will be taken into account. Only words known by the tokenizer will be taken into account. # Arguments tokenized texts:...
Perform param type mapping This requires a bit of logic since this isn t standardized. If a type doesn t map assume str
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: "re...
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
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): ...
The inverse of this bidict type i. e. one with * _fwdm_cls * and * _invm_cls * swapped.
def _inv_cls(cls): """The inverse of this bidict type, i.e. one with *_fwdm_cls* and *_invm_cls* swapped.""" if cls._fwdm_cls is cls._invm_cls: return cls if not getattr(cls, '_inv_cls_', None): class _Inv(cls): _fwdm_cls = cls._invm_cls _i...
The inverse of this bidict.
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 s...
Check * key * and * val * for any duplication in self.
def _dedup_item(self, key, val, on_dup): """ Check *key* and *val* for any duplication in self. Handle any duplication as per the duplication policies given in *on_dup*. (key, val) already present is construed as a no-op, not a duplication. If duplication is found and the corr...
Update rolling back on failure.
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: ...
A shallow copy.
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. In...
A shallow copy of this ordered bidict.
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() ...
Return whether ( key val ) duplicates an existing item.
def _isdupitem(self, key, val, dedup_result): """Return whether (key, val) duplicates an existing item.""" isdupkey, isdupval, nodeinv, nodefwd = dedup_result isdupitem = nodeinv is nodefwd if isdupitem: assert isdupkey assert isdupval return isdupitem
Order - sensitive equality check.
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 not isinstance(other, Mapping) or len(self) != len(other): ...
r Create a new subclass of * base_type * with custom accessors.
def namedbidict(typename, keyname, valname, base_type=bidict): r"""Create a new subclass of *base_type* with custom accessors. Analagous to :func:`collections.namedtuple`. The new class's ``__name__`` will be set to *typename*. Instances of it will provide access to their :attr:`inverse <Bidirect...
Create a named bidict with the indicated arguments and return an empty instance. Used to make: func: bidict. namedbidict instances picklable.
def _make_empty(typename, keyname, valname, base_type): """Create a named bidict with the indicated arguments and return an empty instance. Used to make :func:`bidict.namedbidict` instances picklable. """ cls = namedbidict(typename, keyname, valname, base_type=base_type) return cls()
Yield the items from the positional argument ( if given ) and then any from * kw *.
def _iteritems_args_kw(*args, **kw): """Yield the items from the positional argument (if given) and then any from *kw*. :raises TypeError: if more than one positional argument is given. """ args_len = len(args) if args_len > 1: raise TypeError('Expected at most 1 positional argument, got %d...
Yield the inverse items of the provided object.
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 items in `arg`, inverting each item on the fly. *See also* :attr:`bidict.BidirectionalMappi...
Remove all items.
def clear(self): """Remove all items.""" self._fwdm.clear() self._invm.clear() self._sntl.nxt = self._sntl.prv = self._sntl
u * x. popitem () → ( k v ) *
def popitem(self, last=True): # pylint: disable=arguments-differ u"""*x.popitem() → (k, v)* Remove and return the most recently added item as a (key, value) pair if *last* is True, else the least recently added item. :raises KeyError: if *x* is empty. """ if not self: ...
Move an existing key to the beginning or end of this ordered bidict.
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 = no...
Associate * key * with * val * with the specified duplication policies.
def put(self, key, val, on_dup_key=RAISE, on_dup_val=RAISE, on_dup_kv=None): """ Associate *key* with *val* with the specified duplication policies. If *on_dup_kv* is ``None``, the *on_dup_val* policy will be used for it. For example, if all given duplication policies are :attr:`~bidic...
Associate * key * with * val * unconditionally.
def forceput(self, key, val): """ Associate *key* with *val* unconditionally. Replace any existing mappings containing key *key* or value *val* as necessary to preserve uniqueness. """ self._put(key, val, self._ON_DUP_OVERWRITE)
u * x. pop ( k [ d ] ) → v *
def pop(self, key, default=_MISS): u"""*x.pop(k[, d]) → v* Remove specified key and return the corresponding value. :raises KeyError: if *key* is not found and no *default* is provided. """ try: return self._pop(key) except KeyError: if default i...
u * x. popitem () → ( k v ) *
def popitem(self): u"""*x.popitem() → (k, v)* Remove and return some item as a (key, value) pair. :raises KeyError: if *x* is empty. """ if not self: raise KeyError('mapping is empty') key, val = self._fwdm.popitem() del self._invm[val] retur...
Like: meth: putall with default duplication policies.
def update(self, *args, **kw): """Like :meth:`putall` with default duplication policies.""" if args or kw: self._update(False, None, *args, **kw)
Like a bulk: meth: forceput.
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
Like a bulk: meth: put.
def putall(self, items, on_dup_key=RAISE, on_dup_val=RAISE, on_dup_kv=None): """ Like a bulk :meth:`put`. If one of the given items causes an exception to be raised, none of the items is inserted. """ if items: on_dup = self._get_on_dup((on_dup_key, on_dup_va...
Create a new temporary file and write some initial text to it.
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 :returns: the file name of the newly created temp file :rtype: str """ with NamedTemporaryFile(mode='w+t', suffix='.yml', delete=F...
returns a list of CarddavObject objects: param address_books: list of selected address books: type address_books: list ( address_book. AddressBook ): param search: filter contact list: type search: str: param strict_search: if True search only in full name field: type strict_search: bool: returns: list of CarddavObject...
def get_contact_list_by_user_selection(address_books, search, strict_search): """returns a list of CarddavObject objects :param address_books: list of selected address books :type address_books: list(address_book.AddressBook) :param search: filter contact list :type search: str :param strict_sea...
Get a list of contacts from one or more address books.
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 qu...
Merge the parsed arguments from argparse into the config object.
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 :r...
Load all address books with the given names from the config.
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...
Prepare the search query string from the given command line args.
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 c...
TODO: Docstring for generate_contact_list.
def generate_contact_list(config, args): """TODO: Docstring for generate_contact_list. :param config: the config object to use :type config: config.Config :param args: the command line arguments :type args: argparse.Namespace :returns: the contacts for further processing (TODO) :rtype: list...
Create a new contact.
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...
Add a new email address to contacts creating new contacts if necessary.
def add_email_subcommand(input_from_stdin_or_file, selected_address_books): """Add a new email address to contacts, creating new contacts if necessary. :param input_from_stdin_or_file: the input text to search for the new email :type input_from_stdin_or_file: str :param selected_address_books: the addr...
Print birthday contact table.
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...
Print a phone application friendly contact table.
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 ...
Print a contact table. with all postal/ mailing addresses
def post_address_subcommand(search_terms, vcard_list, parsable): """Print a contact table. with all postal / mailing addresses :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 whi...
Print a mail client friendly contacts table that is compatible with the default format used by mutt. Output format: single line of text email_address \ tname \ ttype email_address \ tname \ ttype [... ]
def email_subcommand(search_terms, vcard_list, parsable, remove_first_line): """Print a mail client friendly contacts table that is compatible with the default format used by mutt. Output format: single line of text email_address\tname\ttype email_address\tname\ttype [...] ...
Print a user friendly contacts table.
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 :...
Modify a contact in an external editor.
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 b...
Remove a contact from the addressbook.
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...
Open the vcard file for a contact in an external editor.
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 editor: str :returns: None :rtype: None ...
Merge two contacts into one.
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 add...
Copy or move a contact to a different address book.
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_lis...
Parse the command line arguments and return the namespace that was creates by argparse. ArgumentParser. parse_args ().
def parse_args(argv): """Parse the command line arguments and return the namespace that was creates by argparse.ArgumentParser.parse_args(). :returns: the namespace parsed from the command line :rtype: argparse.Namespace """ # Create the base argument parser. It will be reused for the first a...
Find the name of the action for the supplied alias. If no action is asociated with the given alias None is returned.
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 :rtype: str or ...
Convert the named field to bool.
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 use...
Use this to create a new and empty contact.
def new_contact(cls, address_book, supported_private_objects, version, localize_dates): """Use this to create a new and empty contact.""" return cls(address_book, None, supported_private_objects, version, localize_dates)
Use this if you want to create a new contact from an existing. vcf file.
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. """ return cls(address_book, filename, supported_private_objects, None, localize_dates)
Use this if you want to create a new contact from user input.
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 = cls(address_book, None, supported_private_objects, version, localize_dates) ...
Use this if you want to clone an existing contact and replace its data with new user input in one step.
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 = cls(contact.address_book, contact.filename, ...
Get some part of the N entry in the vCard as a list
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 = getat...
: rtype: str
def get_first_name_last_name(self): """ :rtype: str """ names = [] if self._get_first_names(): names += self._get_first_names() if self._get_additional_names(): names += self._get_additional_names() if self._get_last_names(): na...
: rtype: str
def get_last_name_first_name(self): """ :rtype: str """ last_names = [] if self._get_last_names(): last_names += self._get_last_names() first_and_additional_names = [] if self._get_first_names(): first_and_additional_names += self._get_firs...
: returns: list of organisations sorted alphabetically: rtype: list ( list ( str ))
def _get_organisations(self): """ :returns: list of organisations, sorted alphabetically :rtype: list(list(str)) """ organisations = [] for child in self.vcard.getChildren(): if child.name == "ORG": organisations.append(child.value) ret...
: rtype: list ( list ( str ))
def _get_titles(self): """ :rtype: list(list(str)) """ titles = [] for child in self.vcard.getChildren(): if child.name == "TITLE": titles.append(child.value) return sorted(titles)
: rtype: list ( list ( str ))
def _get_roles(self): """ :rtype: list(list(str)) """ roles = [] for child in self.vcard.getChildren(): if child.name == "ROLE": roles.append(child.value) return sorted(roles)
: returns: dict of type and phone number list: rtype: dict ( str list ( str ))
def get_phone_numbers(self): """ : returns: dict of type and phone number list :rtype: dict(str, list(str)) """ phone_dict = {} for child in self.vcard.getChildren(): if child.name == "TEL": # phone types type = helpers.list_to_...
: returns: dict of type and email address list: rtype: dict ( str list ( str ))
def get_email_addresses(self): """ : returns: dict of type and email address list :rtype: dict(str, list(str)) """ email_dict = {} for child in self.vcard.getChildren(): if child.name == "EMAIL": type = helpers.list_to_string( ...
: returns: dict of type and post address list: rtype: dict ( str list ( dict ( str list|str )))
def get_post_addresses(self): """ : returns: dict of type and post address list :rtype: dict(str, list(dict(str,list|str))) """ post_adr_dict = {} for child in self.vcard.getChildren(): if child.name == "ADR": type = helpers.list_to_string( ...
: rtype: list ( str ) or list ( list ( str ))
def _get_categories(self): """ :rtype: list(str) or list(list(str)) """ category_list = [] for child in self.vcard.getChildren(): if child.name == "CATEGORIES": value = child.value category_list.append( value if isin...
categories variable must be a list
def _add_category(self, categories): """ categories variable must be a list """ categories_obj = self.vcard.add('categories') categories_obj.value = helpers.convert_to_vcard( "category", categories, ObjectType.list_with_strings)
: rtype: list ( list ( str ))
def get_nicknames(self): """ :rtype: list(list(str)) """ nicknames = [] for child in self.vcard.getChildren(): if child.name == "NICKNAME": nicknames.append(child.value) return sorted(nicknames)
: rtype: list ( list ( str ))
def _get_notes(self): """ :rtype: list(list(str)) """ notes = [] for child in self.vcard.getChildren(): if child.name == "NOTE": notes.append(child.value) return sorted(notes)
: rtype: dict ( str list ( str ))
def _get_private_objects(self): """ :rtype: dict(str, list(str)) """ private_objects = {} for child in self.vcard.getChildren(): if child.name.lower().startswith("x-"): try: key_index = [ x.lower() for x in s...