text
stringlengths
81
112k
Creates a superuser from a specified dict/object bundle located at ``user_config_path``. Skips if the specified object contains no email or no username. If a user with the specified username already exists and has no usable password it updates user's password with a specified one. ``user_config_path`` ...
Runs gunicorn with a specified config. :param application: Django uwsgi application :param gunicorn_module_name: gunicorn settings module name :return: ``Application().run()`` def run_gunicorn(application: WSGIHandler, gunicorn_module_name: str = 'gunicorn_prod'): """ Runs gunicorn with a specifie...
Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal def set_color( fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, ): """Set the console color. >>> set_...
Print string in to stdout using colored font. See L{set_color} for more details about colors. Args: text (str): Text that needs to be printed. def cprint( text, fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, parse=False, ): ...
r"""Print output to console using provided color mappings. Color mapping is dict with regular expressions as key and tuple of two as values. Key is used to match if line should be colorized and tuple contains color to be used and boolean value that indicates if dark foreground is used. For ex...
Print single line to console with ability to colorize parts of it. def _colorize_single_line(line, regexp, color_def): """Print single line to console with ability to colorize parts of it.""" match = regexp.match(line) groupdict = match.groupdict() groups = match.groups() if not groupdict: ...
Terminal height. def height(self): """Terminal height. """ if self.interactive: if self._height is None: self._height = self.term.height return self._height
Clear last N lines of terminal output. def clear_last_lines(self, n): """Clear last N lines of terminal output. """ self.term.stream.write( self.term.move_up * n + self.term.clear_eos) self.term.stream.flush()
Move back N lines and overwrite line with `text`. def overwrite_line(self, n, text): """Move back N lines and overwrite line with `text`. """ with self._moveback(n): self.term.stream.write(text)
Move back N lines in terminal. def move_to(self, n): """Move back N lines in terminal. """ self.term.stream.write(self.term.move_up * n)
Tries to read a ``variable_path`` from each of the passed parsers. It stops if read was successful and returns a retrieved value. If none of the parsers contain a value for the specified path it returns ``default``. :param variable_path: a path to variable in config :param default: a de...
Resolves and imports all modules specified in ``parser_modules``. Short names from the local scope are supported (the scope is ``django_docker_helpers.config.backends``). :param parser_modules: a list of dot-separated module paths :return: a generator of [probably] :class:`~django_docker_helper...
Extracts arguments from ``parser_class.__init__`` and populates them from environment variables. Uses ``__init__`` argument type annotations for correct type casting. .. note:: Environment variables should be prefixed with ``<UPPERCASEPARSERCLASSNAME>__``. :param parser_class: a ...
Creates an instance of :class:`~django_docker_helpers.config.ConfigLoader` with parsers initialized from environment variables. By default it tries to initialize all bundled parsers. Parsers may be customized with ``parser_modules`` argument or ``CONFIG__PARSERS`` environment variable. ...
Prints all read (in call order) options. :param max_col_width: limit column width, ``50`` by default :param use_color: use terminal colors :return: nothing def print_config_read_queue( self, use_color: bool = False, max_col_width: int = 50): """ ...
Prepares a string with pretty printed config read queue. :param use_color: use terminal colors :param max_col_width: limit column width, ``50`` by default :return: def format_config_read_queue(self, use_color: bool = False, max_...
Given a Flask response, find the rdflib Graph def get_graph(cls, response): """ Given a Flask response, find the rdflib Graph """ if cls.is_graph(response): # single graph object return response if hasattr(response, '__getitem__'): # indexable tuple if len(response) > 0 and \ cls.is_graph(response[0...
Replace the rdflib Graph in a Flask response def replace_graph(cls, response, serialized): """ Replace the rdflib Graph in a Flask response """ if cls.is_graph(response): # single graph object return serialized if hasattr(response, '__getitem__'): # indexable tuple if len(response) > 0 and \ cls.is_...
Convert hex digest to sequence of bytes. def _from_hex_digest(digest): """Convert hex digest to sequence of bytes.""" return "".join( [chr(int(digest[x : x + 2], 16)) for x in range(0, len(digest), 2)] )
Perform encryption of provided data. def encrypt(data, digest=True): """Perform encryption of provided data.""" alg = get_best_algorithm() enc = implementations["encryption"][alg]( data, implementations["get_key"]() ) return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc))
Decrypt provided data. def decrypt(data, digest=True): """Decrypt provided data.""" alg, _, data = data.rpartition("$") if not alg: return data data = _from_hex_digest(data) if digest else data try: return implementations["decryption"][alg]( data, implementations["get_ke...
Reconstructs a directed acyclic graph according to prior information of edge significance. This function first ranks all edges and introduce the most significant one by one, avoiding those that would create a loop. Optional constraints on the maximum total number of edges, the number of incoming or outgoing edges fo...
Generate vocabulary list from a tokenized file def gen_vocab(cli, args): ''' Generate vocabulary list from a tokenized file ''' if args.topk and args.topk <= 0: topk = None cli.logger.warning("Invalid k will be ignored (k should be greater than or equal to 1)") else: topk = args.top...
ChirpText Tools main function def main(): ''' ChirpText Tools main function ''' app = CLIApp(desc='ChirpText Tools', logger=__name__, show_version=show_version) # add tasks vocab_task = app.add_task('vocab', func=gen_vocab) vocab_task.add_argument('input', help='Input file') vocab_task.add_argu...
Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance. def add_attachment(message, attachment, rfc2231=True): '''Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance...
Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. def _login(self): '''Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ''' server, port, mode, debug = self.connection_details if mode...
Send an email. Connect/Disconnect if not already connected Arguments: email: Email instance to send. attachments: iterable containing Attachment instances def send(self, email, attachments=()): '''Send an email. Connect/Disconnect if not already connected Arguments: ...
Return a dict mapping column name to type for all columns in table def column_types(self): """Return a dict mapping column name to type for all columns in table """ column_types = {} for c in self.sqla_columns: column_types[c.name] = c.type return column_types
Check if the table name is obviously invalid. def _valid_table_name(self, table_name): """Check if the table name is obviously invalid. """ if table_name is None or not len(table_name.strip()): raise ValueError("Invalid table name: %r" % table_name) return table_name.strip()
Add primary key constraint to specified column def add_primary_key(self, column="id"): """Add primary key constraint to specified column """ if not self.primary_key: sql = """ALTER TABLE {s}.{t} ADD PRIMARY KEY ({c}) """.format( ...
Drop the table from the database def drop(self): """Drop the table from the database """ if self._is_dropped is False: self.table.drop(self.engine) self._is_dropped = True
Explicitely create a new column ``name`` of a specified type. ``type`` must be a `SQLAlchemy column type <http://docs.sqlalchemy.org/en/rel_0_8/core/types.html>`_. :: table.create_column('created_at', sqlalchemy.DateTime) def create_column(self, name, type): """ Explicitely...
Drop the column ``name`` :: table.drop_column('created_at') def drop_column(self, name): """ Drop the column ``name`` :: table.drop_column('created_at') """ self._check_dropped() if name in list(self.table.columns.keys()): se...
Create an index to speed up queries on a table. If no ``name`` is given a random name is created. :: table.create_index(['name', 'country']) def create_index(self, columns, name=None, index_type="btree"): """ Create an index to speed up queries on a table. If no ``na...
Returns all rows of a table, but removes rows in with duplicate values in ``columns``. Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_. :: # returns only one row per year, ignoring the rest table.distinct('year') # works...
Add a row (type: dict) by inserting it into the table. Columns must exist. :: data = dict(title='I am a banana!') table.insert(data) Returns the inserted row's primary key. def insert(self, row): """ Add a row (type: dict) by inserting it into the table. ...
Add many rows at a time, which is significantly faster than adding them one by one. Per default the rows are processed in chunks of 1000 per commit, unless you specify a different ``chunk_size``. See :py:meth:`insert() <dataset.Table.insert>` for details on the other parameters. ...
Rename the table def rename(self, name): """Rename the table """ sql = """ALTER TABLE {s}.{t} RENAME TO {name} """.format( s=self.schema, t=self.name, name=name ) self.engine.execute(sql) self.table = SQLATable(name, self.metadata, schema=self.s...
Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None. :: row = table.find_one(country='United States') def find_one(self, **kwargs): """ Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None. :: r...
Performs a simple search on the table. Simply pass keyword arguments as ``filter``. :: results = table.find(country='France') results = table.find(country='France', year=1980) Using ``_limit``:: # just return the first 10 rows results = table.find(country=...
Open a new connection to postgres via psycopg2/sqlalchemy def connect(url=None, schema=None, sql_path=None, multiprocessing=False): """Open a new connection to postgres via psycopg2/sqlalchemy """ if url is None: url = os.environ.get("DATABASE_URL") return Database(url, schema, sql_path=sql_pat...
Create a new database def create_db(url=None): """Create a new database """ if url is None: url = os.environ.get("DATABASE_URL") parsed_url = urlparse(url) db_name = parsed_url.path db_name = db_name.strip("/") db = connect("postgresql://" + parsed_url.netloc) # check that db do...
Drop specified database def drop_db(url): """Drop specified database """ parsed_url = urlparse(url) db_name = parsed_url.path db_name = db_name.strip("/") db = connect("postgresql://" + parsed_url.netloc) # check that db exists q = """SELECT 1 as exists FROM pg_database ...
Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret. :param field_names: a list of key names that can possibly contain sensitive data :param key_name: a key name to check :param value: a value to mask :return: an unchanged value if nothing to hide...
Provides an access to elements of a mixed dict/object type by a delimiter-separated path. :: class O1: my_dict = {'a': {'b': 1}} class O2: def __init__(self): self.nested = O1() class O3: final = O2() o = O3() assert uti...
Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpath.util.get``. :param obj: dict like ``{'some': {'value': 3}}`` :param path: ``'some.value'`` :param separator: ``'.'`` or ``'/'`` or whatever :param default: default for KeyError :return: dict value or de...
Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``. :param bundle: a dict to traverse :param separator: build paths with a given separator :return: a generator of tuples ``(materialized_path, value)`` Example: >>> list(_materialize_dict({'test': {'path': 1}, 'key...
Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ``('path.to.value', <value>)``. Output is ordered by depth: the deepest element first. :param bundle: a dict to materialize :param separator: build paths with a given separator :return: a depth descen...
Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ``('path.to.value', b'<some>')``. If the ``<some>`` value is not an instance of a basic type, it's serialized with ``serialize`` callback. If this value is an empty string, it's serialized anyway to enforce co...
Writes a given ``raw_str`` into a ``stream``. Ignores output if ``prevent_completion_polluting`` is set and there's no extra ``sys.argv`` arguments present (a bash completion issue). :param raw_str: a raw string to print :param flush: execute ``flush()`` :param prevent_completion_polluting: don't write...
Converts a given string ``val`` into a boolean. :param val: any string representation of boolean :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object :return: ``True`` if ``val`` is thruthy, ``False`` otherwise. :raises ValueError: if ``strict`` specified and ``val``...
Converts an environment variable into a boolean. Empty string (presence in env) is treated as ``True``. :param flag_name: an environment variable name :param strict: raise ``ValueError`` if a ``flag_name`` value connot be coerced into a boolean in obvious way :param env: a dict with environment variables, ...
A decorator to prevent ``manage.py`` from running code twice for everything. (https://stackoverflow.com/questions/16546652/why-does-django-run-everything-twice) :param f: function or method to decorate :return: callable def run_env_once(f: t.Callable) -> t.Callable: """ A decorator to prevent ``ma...
Reads env ``DOCKERIZED`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``DOCKERIZED`` env, ``False`` otherwise def is_dockerized(flag_name: str = 'DOCKERIZED', strict:...
Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise def is_production(flag_name: str = 'PRODUCTION', strict:...
This function loads downsampled data files from the Geuvadis study (Lappalainen, T. et al. Transcriptome and genome sequencing uncovers functional variation in humans. Nature 501, 506-511 (2013)), including expression levels of 10 miRNAs and 3000 genes for 360 European individuals. Among them, all miRNAs and 1000 genes...
Run the given code line by line with printing, as list of lines, and return variable 'ans'. def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signal(SignalOptions.EXEC_CONCURRENT) def validation_function(ar...
Execute each passed endpoint and collect the results. If a result is anoter `MultipleResults` it will extend the results with those contained therein. If the result is `NoResult`, skip the addition. def exec_all_endpoints(self, *args, **kwargs): """Execute each passed endpoint and collect the r...
Call all the registered handlers with the arguments passed. If this signal is a class member, call also the handlers registered at class-definition time. If an external publish function is supplied, call it with the provided arguments. :returns: an instance of `~.utils.MultipleResults` ...
Discover the minimum and maximum UID number. def login_defs(): """Discover the minimum and maximum UID number.""" uid_min = None uid_max = None login_defs_path = '/etc/login.defs' if os.path.exists(login_defs_path): with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as lo...
Runs Django ``collectstatic`` command in silent mode. :return: always ``True`` def collect_static() -> bool: """ Runs Django ``collectstatic`` command in silent mode. :return: always ``True`` """ from django.core.management import execute_from_command_line # from django.conf import settin...
Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config def inner_parser(self) -> BaseParser: ""...
Generate command to add a user. args: proposed_user (User): User manage_home: bool returns: list: The command string split into shell-like syntax def generate_add_user_command(proposed_user=None, manage_home=None): """Generate command to add a user. args: proposed_use...
Generate command to modify existing user to become the proposed user. args: task (dict): A proposed user and the differences between it and the existing user returns: list: The command string split into shell-like syntax def generate_modify_user_command(task=None, manage_home=None): """Ge...
Generate command to delete a user. args: username (str): user name manage_home (bool): manage home directory returns: list: The user delete command string split into shell-like syntax def generate_delete_user_command(username=None, manage_home=None): """Generate command to delete ...
Check if supplied User instance exists in supplied Users list and, if so, return the differences. args: passed_user (User): the user instance to check for differences user_list (Users): the Users instance containing a list of Users instances returns: dict: Details of the matching user ...
Force double quoted gecos. returns: str: The double quoted gecos. def gecos(self): """Force double quoted gecos. returns: str: The double quoted gecos. """ if not self._gecos: return None if self._gecos.startswith(text_type('\'')) an...
Return the user as a dict. def to_dict(self): """ Return the user as a dict. """ public_keys = [public_key.b64encoded for public_key in self.public_keys] return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos, home_dir=self.home_dir, she...
Insert an instance of User into the collection. def insert(self, index, value): """Insert an instance of User into the collection.""" self.check(value) self._user_list.insert(index, value)
Remove User instance based on supplied user name. def remove(self, username=None): """Remove User instance based on supplied user name.""" self._user_list = [user for user in self._user_list if user.name != username]
Return a list of users matching a filter (if provided). def describe_users(self, users_filter=None): """Return a list of users matching a filter (if provided).""" user_list = Users(oktypes=User) for user in self._user_list: if users_filter and (users_filter.get('name') == user.name ...
Create collection from a YAML file. def from_yaml(cls, file_path=None): """Create collection from a YAML file.""" try: import yaml except ImportError: # pragma: no cover yaml = None if not yaml: import sys sys.exit('PyYAML is not installe...
Create collection from a JSON file. def from_json(cls, file_path=None): """Create collection from a JSON file.""" with io.open(file_path, encoding=text_type('utf-8')) as stream: try: users_json = json.load(stream) except ValueError: raise ValueErr...
Create collection from locally discovered data, e.g. /etc/passwd. def from_passwd(uid_min=None, uid_max=None): """Create collection from locally discovered data, e.g. /etc/passwd.""" import pwd users = Users(oktypes=User) passwd_list = pwd.getpwall() if not uid_min: ...
Construct a list of User objects from a list of dicts. def construct_user_list(raw_users=None): """Construct a list of User objects from a list of dicts.""" users = Users(oktypes=User) for user_dict in raw_users: public_keys = None if user_dict.get('public_keys'): ...
Return a dict of the users. def to_dict(self): """ Return a dict of the users. """ users = dict(users=list()) for user in self: users['users'].append(user.to_dict()) return users
Write the users to a file. def export(self, file_path=None, export_format=None): """ Write the users to a file. """ with io.open(file_path, mode='w', encoding="utf-8") as export_file: if export_format == 'yaml': import yaml yaml.safe_dump(self.to_dict(), expo...
Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read() def read(path, mode='tsv'): ''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. read('~/data/myfile') is the same as Docu...
Helper function to write doc to TTL-TXT format def write(path, doc, mode=MODE_TSV, **kwargs): ''' Helper function to write doc to TTL-TXT format ''' if mode == MODE_TSV: with TxtWriter.from_path(path) as writer: writer.write_doc(doc) elif mode == MODE_JSON: write_json(path, doc,...
Create a tokens-concepts map def tcmap(self): ''' Create a tokens-concepts map ''' tcmap = dd(list) for concept in self.__concept_map.values(): for w in concept.tokens: tcmap[w].append(concept) return tcmap
Return a generator of tokens with more than one sense. def msw(self): ''' Return a generator of tokens with more than one sense. ''' return (t for t, c in self.tcmap().items() if len(c) > 1)
Get surface string that is associated with a tag object def surface(self, tag): ''' Get surface string that is associated with a tag object ''' if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0: return self.text[tag.cfrom:tag.cto] else: ...
Create a sentence-level tag def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs): ''' Create a sentence-level tag ''' tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs) return self.add_tag(tag_obj)
Get the first tag of a particular type def get_tag(self, tagtype): ''' Get the first tag of a particular type''' for tag in self.__tags: if tag.tagtype == tagtype: return tag return None
Get all tags of a type def get_tags(self, tagtype): ''' Get all tags of a type ''' return [t for t in self.__tags if t.tagtype == tagtype]
Add a token object into this sentence def add_token_object(self, token): ''' Add a token object into this sentence ''' token.sent = self # take ownership of given token self.__tokens.append(token) return token
Create a new concept object and add it to concept list tokens can be a list of Token objects or token indices def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs): ''' Create a new concept object and add it to concept list tokens can be a list of Token objects or token indice...
Add a concept to current concept list def add_concept(self, concept_obj): ''' Add a concept to current concept list ''' if concept_obj is None: raise Exception("Concept object cannot be None") elif concept_obj in self.__concepts: raise Exception("Concept object is alread...
Get concept by concept ID def concept(self, cid, **kwargs): ''' Get concept by concept ID ''' if cid not in self.__concept_map: if 'default' in kwargs: return kwargs['default'] else: raise KeyError("Invalid cid") else: return s...
Import a list of string as tokens def import_tokens(self, tokens, import_hook=None, ignorecase=True): ''' Import a list of string as tokens ''' text = self.text.lower() if ignorecase else self.text has_hooker = import_hook and callable(import_hook) cfrom = 0 if self.__tokens: ...
Build a map from tagtype to list of tags def tag_map(self): ''' Build a map from tagtype to list of tags ''' tm = dd(list) for tag in self.__tags: tm[tag.tagtype].append(tag) return tm
Get the first tag with a type in this token def find(self, tagtype, **kwargs): '''Get the first tag with a type in this token ''' for t in self.__tags: if t.tagtype == tagtype: return t if 'default' in kwargs: return kwargs['default'] else: ...
Find all token-level tags with the specified tagtype def find_all(self, tagtype): ''' Find all token-level tags with the specified tagtype ''' return [t for t in self.__tags if t.tagtype == tagtype]
Create a new tag on this token def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs): ''' Create a new tag on this token ''' if cfrom is None: cfrom = self.cfrom if cto is None: cto = self.cto tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=...
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised. def get(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, ...
Add a ttl.Sentence object to this document def add_sent(self, sent_obj): ''' Add a ttl.Sentence object to this document ''' if sent_obj is None: raise Exception("Sentence object cannot be None") elif sent_obj.ID is None: # if sentID is None, create a new ID s...
Create a new sentence and add it to this Document def new_sent(self, text, ID=None, **kwargs): ''' Create a new sentence and add it to this Document ''' if ID is None: ID = next(self.__idgen) return self.add_sent(Sentence(text, ID=ID, **kwargs))
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised. def pop(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, ...
Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) def read(self): ''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) ''' warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning) with TxtReader.fro...