Search is not available for this dataset
text stringlengths 75 104k |
|---|
def randtld(self):
""" -> a random #str tld via :mod:tlds """
self.tlds = tuple(tlds.tlds) if not self.tlds else self.tlds
return self.random.choice(self.tlds) |
def randurl(self):
""" -> a random url-like #str via :prop:randdomain, :prop:randtld,
and :prop:randpath
"""
return "{}://{}.{}/{}".format(
self.random.choice(("http", "https")),
self.randdomain, self.randtld, self.randpath) |
def randtuple(self):
""" -> a #tuple of random #int """
return tuple(
self.randint
for x in range(0, self.random.randint(3, 10))) |
def randdeque(self):
""" -> a :class:collections.deque of random #int """
return deque(
self.randint
for x in range(0, self.random.randint(3, 10))) |
def randdict(self):
""" -> a #dict of |{random_string: random_int}| """
return {
self.randstr: self._map_type(int)
for x in range(self.random.randint(3, 10))} |
def randset(self):
""" -> a #set of random integers """
return {
self._map_type(int)
for x in range(self.random.randint(3, 10))} |
def _to_tuple(self, _list):
""" Recursively converts lists to tuples """
result = list()
for l in _list:
if isinstance(l, list):
result.append(tuple(self._to_tuple(l)))
else:
result.append(l)
return tuple(result) |
def dict(self, key_depth=1000, tree_depth=1):
""" Creates a random #dict
@key_depth: #int number of keys per @tree_depth to generate random
values for
@tree_depth: #int dict tree dimensions size, i.e.
1=|{key: value}|
2=|{key: {key: value}... |
def defaultdict(self, key_depth=1000, tree_depth=1):
""" Creates a random :class:collections.defaultdict
@key_depth: #int number of keys per @tree_depth to generate random
values for
@tree_depth: #int dict tree dimensions size, i.e.
1=|{key: value}|
... |
def tuple(self, size=1000, tree_depth=1):
""" Creates a random #tuple
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|(value1, value2)|
2=|((value1, value2), (value1, value2))|
... |
def generator(self, size=1000, tree_depth=1):
""" Creates a random #generator
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|(value1, value2)|
2=|((value1, value2), (value1, value2))... |
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None):
""" Generates random values for sequence-like objects
@struct: the sequence-like structure you want to fill with random
data
@size: #int number of random values to include in each @tree_depth
... |
def mapping(self, struct, key_depth=1000, tree_depth=1,
update_callable=None):
""" Generates random values for dict-like objects
@struct: the dict-like structure you want to fill with random data
@size: #int number of random values to include in each @tree_depth
... |
def _dict_prefix(self, key, value, i, dj=0, color=None, separator=":"):
just = self._justify if i > 0 else dj
key = cut(str(key), self._key_maxlen).rjust(just)
key = colorize(key, color=color)
pref = "{}{} {}".format(key, separator, value)
"""pref = "{}{} {}".format(colorize(str(... |
def _format_numeric_sequence(self, _sequence, separator="."):
""" Length of the highest index in chars = justification size """
if not _sequence:
return colorize(_sequence, "purple")
_sequence = _sequence if _sequence is not None else self.obj
minus = (2 if self._depth > 0 el... |
def objname(self, obj=None):
""" Formats object names in a pretty fashion """
obj = obj or self.obj
_objname = self.pretty_objname(obj, color=None)
_objname = "'{}'".format(colorize(_objname, "blue"))
return _objname |
def pretty(self, obj=None, display=True):
""" Formats @obj or :prop:obj
@obj: the object you'd like to prettify
-> #str pretty object
"""
ret = self._format_obj(obj if obj is not None else self.obj)
if display:
print(ret)
else:
re... |
def _format_obj(self, item=None):
""" Determines the type of the object and maps it to the correct
formatter
"""
# Order here matters, odd behavior with tuples
if item is None:
return getattr(self, 'number')(item)
elif isinstance(item, self.str_):
... |
def pretty_objname(self, obj=None, maxlen=50, color="boldcyan"):
""" Pretty prints object name
@obj: the object whose name you want to pretty print
@maxlen: #int maximum length of an object name to print
@color: your choice of :mod:colors or |None|
-> #str prett... |
def set_level(self, level):
""" Sets :attr:loglevel to @level
@level: #str one or several :attr:levels
"""
if not level:
return None
self.levelmap = set()
for char in level:
self.levelmap = self.levelmap.union(self.levels[char])
self.l... |
def log(self, flag_message=None, padding=None, color=None, force=False):
""" Log Level: :attr:LOG
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area wit... |
def success(self, flag_message="Success", padding=None, force=False):
""" Log Level: :attr:SUCCESS
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area wi... |
def complete(self, flag_message="Complete", padding=None, force=False):
""" Log Level: :attr:COMPLETE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area... |
def notice(self, flag_message="Notice", padding=None, force=False):
""" Log Level: :attr:NOTICE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with ... |
def warning(self, flag_message="Warning", padding=None, force=False):
""" Log Level: :attr:WARNING
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area wi... |
def error(self, flag_message="Error", padding=None, force=False):
""" Log Level: :attr:ERROR
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :fu... |
def timing(self, flag_message, padding=None, force=False):
""" Log Level: :attr:TIMING
@flag_message: time-like #float
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@force: #bool whether or not to force the mes... |
def count(self, flag_message, padding=None, force=False):
""" Log Level: :attr:COUNT
@flag_message: time-like #float
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area with :func:padd
@force: #bool whether or not to force the messa... |
def format_message(self, message):
""" Formats a message with :class:Look """
look = Look(message)
return look.pretty(display=False) |
def format_messages(self, messages):
""" Formats several messages with :class:Look, encodes them
with :func:vital.tools.encoding.stdout_encode """
mess = ""
for message in self.message:
if self.pretty:
mess = "{}{}".format(mess, self.format_message(message... |
def _print_message(self, flag_message=None, color=None, padding=None,
reverse=False):
""" Outputs the message to the terminal """
if flag_message:
flag_message = stdout_encode(flag(flag_message,
color=color if self.pretty e... |
def format_bar(self):
""" Builds the progress bar """
pct = floor(round(self.progress/self.size, 2)*100)
pr = floor(pct*.33)
bar = "".join(
["‒" for x in range(pr)] + ["↦"] +
[" " for o in range(self._barsize-pr-1)])
subprogress = self.format_parent_bar() ... |
def finish(self):
""" Resets the progress bar and clears it from the terminal """
pct = floor(round(self.progress/self.size, 2)*100)
pr = floor(pct*.33)
bar = "".join([" " for x in range(pr-1)] + ["↦"])
subprogress = self.format_parent_bar() if self.parent_bar else ""
fin... |
def update(self, progress=0):
""" Updates the progress bar with @progress if given, otherwise
increments :prop:progress by 1. Also prints the progress bar.
@progress: #int to assign to :prop:progress
"""
self.progress += (progress or 1)
if self.visible:
... |
def start(self):
""" Starts the timer """
if not self._start:
self._first_start = time.perf_counter()
self._start = self._first_start
else:
self._start = time.perf_counter() |
def stop(self, precision=0):
""" Stops the timer, adds it as an interval to :prop:intervals
@precision: #int number of decimal places to round to
-> #str formatted interval time
"""
self._stop = time.perf_counter()
return self.add_interval(precision) |
def format_time(self, sec):
""" Pretty-formats a given time in a readable manner
@sec: #int or #float seconds
-> #str formatted time
"""
# µsec
if sec < 0.001:
return "{}{}".format(
colorize(round(sec*1000000, 2), "purple"), bold("µs")... |
def format_size(self, bytes):
""" Pretty-formats given bytes size in a readable manner
@bytes: #int or #float bytes
-> #str formatted bytes
"""
# b
if bytes < 1024:
return "{}{}".format(colorize(round(
bytes, 2), "purple"),
... |
def add_interval(self, precision=0):
""" Adds an interval to :prop:intervals
-> #str formatted time
"""
precision = precision or self.precision
interval = round((self._stop - self._start), precision)
self.intervals.append(interval)
self._intervals_len += 1
... |
def time(self, intervals=1, *args, _show_progress=True, _print=True,
_collect_garbage=True, _quiet=True, **kwargs):
""" Measures the execution time of :prop:_callable for @intervals
@intervals: #int number of intervals to measure the execution time
of the function for
... |
def mean(self):
""" -> #float :func:numpy.mean of the timing intervals """
return round(np.mean(self.array), self.precision)\
if len(self.array) else None |
def median(self):
""" -> #float :func:numpy.median of the timing intervals """
return round(float(np.median(self.array)), self.precision)\
if len(self.array) else None |
def max(self):
""" -> #float :func:numpy.max of the timing intervals """
return round(np.max(self.array), self.precision)\
if len(self.array) else None |
def min(self):
""" -> #float :func:numpy.min of the timing intervals """
return round(np.min(self.array), self.precision)\
if len(self.array) else None |
def stdev(self):
""" -> #float :func:numpy.std of the timing intervals """
return round(np.std(self.array), self.precision)\
if len(self.array) else None |
def stats(self):
""" -> :class:collections.OrderedDict of stats about the time intervals
"""
return OrderedDict([
("Intervals", len(self.array)),
("Mean", self.format_time(self.mean or 0)),
("Min", self.format_time(self.min or 0)),
("Median", self.... |
def _pct_diff(self, best, other):
""" Calculates and colorizes the percent difference between @best
and @other
"""
return colorize("{}%".format(
round(((best-other)/best)*100, 2)).rjust(10), "red") |
def info(self, verbose=None):
""" Prints and formats the results of the timing
@_print: #bool whether or not to print out to terminal
@verbose: #bool True if you'd like to print the individual timing
results in additions to the comparison results
"""
if se... |
def fi_iban_load_map(filename: str) -> dict:
"""
Loads Finnish monetary institution codes and BICs in CSV format.
Map which is based on 3 digits as in FIXX<3 digits>.
Can be used to map Finnish IBAN number to bank information.
Format: dict('<3 digits': (BIC, name), ...)
:param filename: CSV file... |
def async_lru(size=100):
""" An LRU cache for asyncio coroutines in Python 3.5
..
@async_lru(1024)
async def slow_coroutine(*args, **kwargs):
return await some_other_slow_coroutine()
..
"""
cache = collections.OrderedDict()
def decorator(fn):
... |
def choices_label(choices: tuple, value) -> str:
"""
Iterates (value,label) list and returns label matching the choice
:param choices: [(choice1, label1), (choice2, label2), ...]
:param value: Value to find
:return: label or None
"""
for key, label in choices:
if key == value:
... |
def info(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Print sys message to stdout.
System messages should inform about the flow of the script. This should
be a major milestones during the build.
"""
if len(args) or len(kw):
msg = msg.format(*args, **kw)
shell.cprint('-... |
def err(msg, *args, **kw):
# type: (str, *Any, **Any) -> None
""" Per step status messages
Use this locally in a command definition to highlight more important
information.
"""
if len(args) or len(kw):
msg = msg.format(*args, **kw)
shell.cprint('-- <31>{}<0>'.format(msg)) |
def is_username(string, minlen=1, maxlen=15):
""" Determines whether the @string pattern is username-like
@string: #str being tested
@minlen: minimum required username length
@maxlen: maximum username length
-> #bool
"""
if string:
string = string.strip()
ret... |
def bigint_to_string(val):
""" Converts @val to a string if it is a big integer (|>2**53-1|)
@val: #int or #float
-> #str if @val is a big integer, otherwise @val
"""
if isinstance(val, _NUMBERS) and not abs(val) <= 2**53-1:
return str(val)
return val |
def rbigint_to_string(obj):
""" Recursively converts big integers (|>2**53-1|) to strings
@obj: Any python object
-> @obj, with any big integers converted to #str objects
"""
if isinstance(obj, (str, bytes)) or not obj:
# the input is the desired one, return as is
return ob... |
def remove_blank_lines(string):
""" Removes all blank lines in @string
-> #str without blank lines
"""
return "\n".join(line
for line in string.split("\n")
if len(line.strip())) |
def _manage_cmd(cmd, settings=None):
# type: () -> None
""" Run django ./manage.py command manually.
This function eliminates the need for having ``manage.py`` (reduces file
clutter).
"""
import sys
from os import environ
from peltak.core import conf
from peltak.core import context
... |
def current_branch():
# type: () -> BranchDetails
""" Return the BranchDetails for the current branch.
Return:
BranchDetails: The details of the current branch.
"""
cmd = 'git symbolic-ref --short HEAD'
branch_name = shell.run(
cmd,
capture=True,
never_pretend=Tr... |
def commit_branches(sha1):
# type: (str) -> List[str]
""" Get the name of the branches that this commit belongs to. """
cmd = 'git branch --contains {}'.format(sha1)
return shell.run(
cmd,
capture=True,
never_pretend=True
).stdout.strip().split() |
def guess_base_branch():
# type: (str) -> Optional[str, None]
""" Try to guess the base branch for the current branch.
Do not trust this guess. git makes it pretty much impossible to guess
the base branch reliably so this function implements few heuristics that
will work on most common use cases bu... |
def commit_author(sha1=''):
# type: (str) -> Author
""" Return the author of the given commit.
Args:
sha1 (str):
The sha1 of the commit to query. If not given, it will return the
sha1 for the current commit.
Returns:
Author: A named tuple ``(name, email)`` with t... |
def unstaged():
# type: () -> List[str]
""" Return a list of unstaged files in the project repository.
Returns:
list[str]: The list of files not tracked by project git repo.
"""
with conf.within_proj_dir():
status = shell.run(
'git status --porcelain',
captur... |
def ignore():
# type: () -> List[str]
""" Return a list of patterns in the project .gitignore
Returns:
list[str]: List of patterns set to be ignored by git.
"""
def parse_line(line): # pylint: disable=missing-docstring
# Decode if necessary
if not isinstance(line, string_... |
def branches():
# type: () -> List[str]
""" Return a list of branches in the current repo.
Returns:
list[str]: A list of branches in the current repo.
"""
out = shell.run(
'git branch',
capture=True,
never_pretend=True
).stdout.strip()
return [x.strip('* \t\n... |
def tag(name, message, author=None):
# type: (str, str, Author, bool) -> None
""" Tag the current commit.
Args:
name (str):
The tag name.
message (str):
The tag message. Same as ``-m`` parameter in ``git tag``.
author (Author):
The commit author. ... |
def config():
# type: () -> dict[str, Any]
""" Return the current git configuration.
Returns:
dict[str, Any]: The current git config taken from ``git config --list``.
"""
out = shell.run(
'git config --list',
capture=True,
never_pretend=True
).stdout.strip()
... |
def tags():
# type: () -> List[str]
""" Returns all tags in the repo.
Returns:
list[str]: List of all tags in the repo, sorted as versions.
All tags returned by this function will be parsed as if the contained
versions (using ``v:refname`` sorting).
"""
return shell.run(
'g... |
def verify_branch(branch_name):
# type: (str) -> bool
""" Verify if the given branch exists.
Args:
branch_name (str):
The name of the branch to check.
Returns:
bool: **True** if a branch with name *branch_name* exits, **False**
otherwise.
"""
try:
sh... |
def protected_branches():
# type: () -> list[str]
""" Return branches protected by deletion.
By default those are master and devel branches as configured in pelconf.
Returns:
list[str]: Names of important branches that should not be deleted.
"""
master = conf.get('git.master_branch', '... |
def branches(self):
# type: () -> List[str]
""" List of all branches this commit is a part of. """
if self._branches is None:
cmd = 'git branch --contains {}'.format(self.sha1)
out = shell.run(
cmd,
capture=True,
never_prete... |
def parents(self):
# type: () -> List[CommitDetails]
""" Parents of the this commit. """
if self._parents is None:
self._parents = [CommitDetails.get(x) for x in self.parents_sha1]
return self._parents |
def number(self):
# type: () -> int
""" Return this commits number.
This is the same as the total number of commits in history up until
this commit.
This value can be useful in some CI scenarios as it allows to track
progress on any given branch (although there can be t... |
def get(cls, sha1=''):
# type: (str) -> CommitDetails
""" Return details about a given commit.
Args:
sha1 (str):
The sha1 of the commit to query. If not given, it will return
the details for the latest commit.
Returns:
CommitDetai... |
def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
log = logging.getLogger(Logify.get_name() + '.logify.main')
log.info('logger name is: %s', Logify.get_name())
log.debug('This is DEBUG')
log... |
def set_log_level(cls, log_level):
"""Sets the log level for cons3rt assets
This method sets the logging level for cons3rt assets using
pycons3rt. The loglevel is read in from a deployment property
called loglevel and set appropriately.
:type log_level: str
:return: Tru... |
def get_record_by_name(self, index, name):
"""
Searches for a single document in the given index on the 'name' field .
Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query.
Args:
index: `str`. The name of an Elasticsearch index (i.e. biosa... |
def getattr_in(obj, name):
""" Finds an in @obj via a period-delimited string @name.
@obj: (#object)
@name: (#str) |.|-separated keys to search @obj in
..
obj.deep.attr = 'deep value'
getattr_in(obj, 'obj.deep.attr')
..
|'deep value'|
"""
for p... |
def import_from(name):
""" Imports a module, class or method from string and unwraps it
if wrapped by functools
@name: (#str) name of the python object
-> imported object
"""
obj = name
if isinstance(name, str) and len(name):
try:
obj = locate(name)
... |
def unwrap_obj(obj):
""" Gets the actual object from a decorated or wrapped function
@obj: (#object) the object to unwrap
"""
try:
obj = obj.fget
except (AttributeError, TypeError):
pass
try:
# Cached properties
if obj.func.__doc__ == obj.__doc__:
... |
def add_modality(output_path, modality):
"""Modality can be appended to the file name (such as 'bold') or use in the
folder (such as "func"). You should always use the specific modality ('bold').
This function converts it to the folder name.
"""
if modality is None:
return output_path
el... |
def load():
# type: () -> None
""" Load configuration from file.
This will search the directory structure upwards to find the project root
(directory containing ``pelconf.py`` file). Once found it will import the
config file which should initialize all the configuration (using
`peltak.core.conf... |
def load_yaml_config(conf_file):
# type: (str) -> None
""" Load a YAML configuration.
This will not update the configuration but replace it entirely.
Args:
conf_file (str):
Path to the YAML config. This function will not check the file name
or extension and will just cr... |
def load_py_config(conf_file):
# type: (str) -> None
""" Import configuration from a python file.
This will just import the file into python. Sky is the limit. The file
has to deal with the configuration all by itself (i.e. call conf.init()).
You will also need to add your src directory to sys.path... |
def load_template(filename):
# type: (str) -> str
""" Load template from file.
The templates are part of the package and must be included as
``package_data`` in project ``setup.py``.
Args:
filename (str):
The template path. Relative to `peltak` package directory.
Returns:
... |
def proj_path(*path_parts):
# type: (str) -> str
""" Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path.
"""
path_parts = p... |
def within_proj_dir(path='.'):
# type: (Optional[str]) -> str
""" Return an absolute path to the given project relative path.
:param path:
Project relative path that will be converted to the system wide absolute
path.
:return:
Absolute path.
"""
curr_dir = os.getcwd()
... |
def get(name, *default):
# type: (str, Any) -> Any
""" Get config value with the given name and optional default.
Args:
name (str):
The name of the config value.
*default (Any):
If given and the key doesn't not exist, this will be returned
instead. If it'... |
def get_path(name, *default):
# type: (str, Any) -> Any
""" Get config value as path relative to the project directory.
This allows easily defining the project configuration within the fabfile
as always relative to that fabfile.
Args:
name (str):
The name of the config value co... |
def _find_proj_root():
# type: () -> Optional[str]
""" Find the project path by going up the file tree.
This will look in the current directory and upwards for the pelconf file
(.yaml or .py)
"""
proj_files = frozenset(('pelconf.py', 'pelconf.yaml'))
curr = os.getcwd()
while curr.start... |
def verify(verified_entity, verification_key):
"""
Метод должен райзить ошибки
:param verified_entity: сущность
:param verification_key: ключ
:return:
"""
verification = get_object_or_none(Verification, verified_entity=verified_entity)
if verification is ... |
def _xml_element_value(el: Element, int_tags: list):
"""
Gets XML Element value.
:param el: Element
:param int_tags: List of tags that should be treated as ints
:return: value of the element (int/str)
"""
# None
if el.text is None:
return None
# int
try:
if el.tag... |
def _xml_tag_filter(s: str, strip_namespaces: bool) -> str:
"""
Returns tag name and optionally strips namespaces.
:param el: Element
:param strip_namespaces: Strip namespace prefix
:return: str
"""
if strip_namespaces:
ns_end = s.find('}')
if ns_end != -1:
s = s[... |
def xml_to_dict(xml_bytes: bytes, tags: list=[], array_tags: list=[], int_tags: list=[],
strip_namespaces: bool=True, parse_attributes: bool=True,
value_key: str='@', attribute_prefix: str='@',
document_tag: bool=False) -> dict:
"""
Parses XML string to dict. In c... |
def dict_to_element(doc: dict, value_key: str='@', attribute_prefix: str='@') -> Element:
"""
Generates XML Element from dict.
Generates complex elements by assuming element attributes are prefixed with '@', and value is stored to plain '@'
in case of complex element. Children are sub-dicts.
For ex... |
def local_property():
""" Property structure which maps within the :func:local() thread
(c)2014, Marcel Hellkamp
"""
ls = local()
def fget(self):
try:
return ls.var
except AttributeError:
raise RuntimeError("Request context not initialized.")
def fse... |
def download(download_info):
"""Module method for downloading from S3
This public module method takes a key and the full path to
the destination directory, assumes that the args have been
validated by the public caller methods, and attempts to
download the specified key to the dest_dir.
:para... |
def find_bucket_keys(bucket_name, regex, region_name=None, aws_access_key_id=None, aws_secret_access_key=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an emp... |
def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
log.debug('This is DEBUG!')
log.info('This is INFO!')
log.warning('This is WARNING!')
log.... |
def validate_bucket(self):
"""Verify the specified bucket exists
This method validates that the bucket name passed in the S3Util
constructor actually exists.
:return: None
"""
log = logging.getLogger(self.cls_logger + '.validate_bucket')
log.info('Attempting to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.