text stringlengths 81 112k |
|---|
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : pos... |
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : pos... |
Upload the release to a pypi server.
TODO: Make sure the git directory is clean before allowing a release.
Args:
target (str):
pypi target as defined in ~/.pypirc
def upload(target):
# type: (str) -> None
""" Upload the release to a pypi server.
TODO: Make sure the git direct... |
Generate ~/.pypirc with the given credentials.
Useful for CI builds. Can also get credentials through env variables
``PYPI_USER`` and ``PYPI_PASS``.
Args:
username (str):
pypi username. If not given it will try to take it from the
`` PYPI_USER`` env variable.
passwo... |
Returns a full path to the chosen SDF file. The supplied file
is not expected to contain a recognised SDF extension, this is added
automatically.
If a file with the extension `.sdf.gz` or `.sdf` is found the path to it
(excluding the extension) is returned. If this fails, `None` is returned.
:param... |
Handles external calling for this module
Execute this python module and provide the args shown below to
external call this module to send Slack messages with attachments!
:return: None
def main():
"""Handles external calling for this module
Execute this python module and provide the args shown b... |
Sets the text attribute of the payload
:param text: (str) Text of the message
:return: None
def set_text(self, text):
"""Sets the text attribute of the payload
:param text: (str) Text of the message
:return: None
"""
log = logging.getLogger(self.cls_logger + '.... |
Sets the icon_url for the message
:param icon_url: (str) Icon URL
:return: None
def set_icon(self, icon_url):
"""Sets the icon_url for the message
:param icon_url: (str) Icon URL
:return: None
"""
log = logging.getLogger(self.cls_logger + '.set_icon')
i... |
Adds an attachment to the SlackMessage payload
This public method adds a slack message to the attachment
list.
:param attachment: SlackAttachment object
:return: None
def add_attachment(self, attachment):
"""Adds an attachment to the SlackMessage payload
This public m... |
Sends the Slack message
This public method sends the Slack message along with any
attachments, then clears the attachments array.
:return: None
:raises: OSError
def send(self):
"""Sends the Slack message
This public method sends the Slack message along with any
... |
Sends a Slack message with an attachment for each cons3rt agent log
:return:
def send_cons3rt_agent_logs(self):
"""Sends a Slack message with an attachment for each cons3rt agent log
:return:
"""
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
lo... |
Sends a Slack message with the contents of a text file
:param: test_file: (str) Full path to text file to send
:return: None
:raises: Cons3rtSlackerError
def send_text_file(self, text_file):
"""Sends a Slack message with the contents of a text file
:param: test_file: (str) Ful... |
Deploy the app to the target environment.
The target environments can be configured using the ENVIRONMENTS conf
variable. This will also collect all static files and compile translation
messages
def deploy(project, version, promote, quiet):
""" Deploy the app to the target environment.
The target... |
Run devserver.
def devserver(port, admin_port, clear):
# type: (int, int, bool) -> None
""" Run devserver. """
from . import logic
logic.devserver(port, admin_port, clear) |
Convolve a spectrum by a Gaussian with different sigma for every pixel.
If all sigma are the same this routine produces the same output as
scipy.ndimage.gaussian_filter1d, except for the border treatment.
Here the first/last p pixels are filled with zeros.
When creating a template library for SDSS data,... |
For each plugins, check if a "step" method exist on it, and call it
Args:
step (str): The method to search and call on each plugin
def call_plugins(self, step):
'''
For each plugins, check if a "step" method exist on it, and call it
Args:
step (str): The method... |
Run the application
def run(self):
"""
Run the application
"""
self.call_plugins("on_run")
if vars(self.arguments).get("version", None):
self.logger.info("{app_name}: {version}".format(app_name=self.app_name, version=self.version))
else:
if self.a... |
Decorator to add a --pretend option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'pretend' if the command needs it. To get the current value you can do:
>>> from peltak.comm... |
Decorator to add a --verbose option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'verbose' if the command needs it. To get the current value you can do:
>>> from peltak.core... |
Print change log since last release.
def changelog():
# type: () -> str
""" Print change log since last release. """
# Skip 'v' prefix
versions = [x for x in git.tags() if versioning.is_valid(x[1:])]
cmd = 'git log --format=%H'
if versions:
cmd += ' {}..HEAD'.format(versions[-1])
... |
Extract all tagged items from text.
Args:
text (str):
Text to extract the tagged items from. Each tagged item is a
paragraph that starts with a tag. It can also be a text list item.
Returns:
tuple[list[str], list[str], list[str]]:
A tuple of `(features, chan... |
Method to generate real metaclass to be used::
mc = ExtensibleType._("MyClass") # note this line
@six.add_metaclass(mc)
class MyClassBase(object):
pass
:param str cls_name: name of generated class
:param class with_meta: Mix ... |
Generates new class to gether logic of all available extensions
::
mc = ExtensibleType._("MyClass")
@six.add_metaclass(mc)
class MyClassBase(object):
pass
# get class with all extensions enabled
MyClass = m... |
Adds new class *cls* to base classes
def _add_base_class(mcs, cls):
""" Adds new class *cls* to base classes
"""
# Do all magic only if subclass had defined required attributes
if getattr(mcs, '_base_classes_hash', None) is not None:
meta = getattr(cls, 'Meta', None)
... |
Method to generate real metaclass to be used
::
# Create metaclass *mc*
mc = ExtensibleByHashType._("MyClass", hashattr='name')
# Create class using *mc* as metaclass
@six.add_metaclass(mc)
class MyClassBase(object):
... |
Generates new class to gether logic of all available extensions
::
# Create metaclass *mc*
mc = ExtensibleByHashType._("MyClass", hashattr='name')
# Use metaclass *mc* to create base class for extensions
@six.add_metaclass(mc)
... |
Return's list of names (keys) registered in this tree.
For each name specific classes exists
def get_registered_names(mcs):
""" Return's list of names (keys) registered in this tree.
For each name specific classes exists
"""
return [k for k, v in six.iteritems(mcs._base_... |
Returns day number of the last day of the month
:param t: datetime
:return: int
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.mon... |
Localizes time range. Uses pytz.utc if None provided.
:param begin: Begin datetime
:param end: End datetime
:param tz: pytz timezone or None (default UTC)
:return: begin, end
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime):
"""
Localizes time range. Uses... |
Returns this week begin (inclusive) and end (exclusive).
:param today: Some date (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
def this_week(today: datetime=None, tz=None):
"""
Returns this week begin (inclusive) and end (exclusive).... |
Returns current month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
def this_month(today: datetime=None, tz=None):
"""
Returns current month begin (inclusive... |
Returns next month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
def next_month(today: datetime=None, tz=None):
"""
Returns next month begin (inclusive) and ... |
Returns last year begin (inclusive) and end (exclusive).
:param today: Some date (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
def last_year(today: datetime=None, tz=None):
"""
Returns last year begin (inclusive) and end (exclusive).... |
Adds +- n months to datetime.
Clamps to number of days in given month.
:param t: datetime
:param n: count
:return: datetime
def add_month(t: datetime, n: int=1) -> datetime:
"""
Adds +- n months to datetime.
Clamps to number of days in given month.
:param t: datetime
:param n: count... |
Iterates over time range in steps specified in delta.
:param start: Start of time range (inclusive)
:param end: End of time range (exclusive)
:param delta: Step interval
:return: Iterable collection of [(start+td*0, start+td*1), (start+td*1, start+td*2), ..., end)
def per_delta(start: datetime, end: ... |
Iterates over time range in one month steps.
Clamps to number of days in given month.
:param start: Start of time range (inclusive)
:param end: End of time range (exclusive)
:param n: Number of months to step. Default is 1.
:return: Iterable collection of [(month+0, month+1), (month+1, month+2), .... |
Return the requirements as a list of string.
def get_requirements() -> List[str]:
"""Return the requirements as a list of string."""
requirements_path = os.path.join(
os.path.dirname(__file__), 'requirements.txt'
)
with open(requirements_path) as f:
return f.read().split() |
List requirements for peltak commands configured for the project.
This list is dynamic and depends on the commands you have configured in
your project's pelconf.yaml. This will be the combined list of packages
needed to be installed in order for all the configured commands to work.
def project_dev_require... |
:type method: function
:type called_params: dict
:return:
def get_func_params(method, called_params):
"""
:type method: function
:type called_params: dict
:return:
"""
insp = inspect.getfullargspec(method)
if not isinstance(called_params, dict):
raise UserWarning()
_call... |
Разбирает строку подключения к БД и возвращает список из (host, port,
username, password, dbname)
:param dsn: Строка подключения. Например: username@localhost:5432/dname
:type: str
:param default_port: Порт по-умолчанию
:type default_port: int
:params protocol
:type protocol str
:return... |
Build all docker images for the project.
def build_images():
# type: () -> None
""" Build all docker images for the project. """
registry = conf.get('docker.registry')
docker_images = conf.get('docker.images', [])
for image in docker_images:
build_image(registry, image) |
Push all project docker images to a remote registry.
def push_images():
# type: () -> None
""" Push all project docker images to a remote registry. """
registry = conf.get('docker.registry')
docker_images = conf.get('docker.images', [])
if registry is None:
log.err("You must define docker.... |
List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker registry password.
def docker_list(registry_pass):
# type: (str) -> None
""" List docker images stored in the remote registry.
Args:
registry_pass (str):
Remote docker re... |
Build docker image.
Args:
registry (str):
The name of the registry this image belongs to. If not given, the
resulting image will have a name without the registry.
image (dict[str, Any]):
The dict containing the information about the built image. This is
... |
Push the given image to selected repository.
Args:
registry (str):
The name of the registry we're pushing to. This is the address of
the repository without the protocol specification (no http(s)://)
image (dict[str, Any]):
The dict containing the information abou... |
Returns a well formatted OPR data
def _build_opr_data(self, data, store):
"""Returns a well formatted OPR data"""
return {
"invoice_data": {
"invoice": {
"total_amount": data.get("total_amount"),
"description": data.get("description")
... |
Initiazes an OPR
First step in the OPR process is to create the OPR request.
Returns the OPR token
def create(self, data={}, store=None):
"""Initiazes an OPR
First step in the OPR process is to create the OPR request.
Returns the OPR token
"""
_store = store or... |
Second stage of an OPR request
def charge(self, data):
"""Second stage of an OPR request"""
token = data.get("token", self._response["token"])
data = {
"token": token,
"confirm_token": data.get("confirm_token")
}
return self._process('opr/charge', data) |
Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quick mode, the form will reduce the
number of question asked by using d... |
Replaces an existing AMI ID with an image created from the provided
instance ID
:param ami_id: (str) ID of the AMI to delete and replace
:param instance_id: (str) ID of the instance ID to create an image from
:return: None
def update_image(self, ami_id, instance_id):
"... |
Created a new CONS3RT-ready template from an instance ID
:param instance_id: (str) Instance ID to create the image from
:param name: (str) Name of the new image
:param description: (str) Description of the new image
:return: None
def create_cons3rt_template(self, instance_id, n... |
:param ami_id:
:return:
def copy_cons3rt_template(self, ami_id):
"""
:param ami_id:
:return:
"""
log = logging.getLogger(self.cls_logger + '.copy_cons3rt_template')
# Get the current AMI info
try:
ami_info = self.ec2.describe_images... |
This function was made to avoid byte / str type errors received in
packages like base64. Accepts all input types and will recursively
encode entire lists and dicts.
@s: the #bytes or #str item you are attempting to encode or decode
@result: the desired output, either #str or #bytes
@enc: the desire... |
Inputs are encoded to utf-8 and then decoded to the desired
output encoding
@encoding: the desired encoding
-> #str with the desired @encoding
def recode_unicode(s, encoding='utf-8'):
""" Inputs are encoded to utf-8 and then decoded to the desired
output encoding
@encodin... |
u"""Copyright:
http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/
Something you will find all over the place, in real-world text, is text
that's mistakenly encoded as utf-8, decoded in some ugly format like
latin-1 or even Windows codepage 1252, and encoded as utf-8 again.
T... |
u'''
Look for red flags that text is encoded incorrectly:
Obvious problems:
- The replacement character \ufffd, indicating a decoding error
- Unassigned or private-use Unicode characters
Very weird things:
- Adjacent letters from two different scripts
- Letters in scripts that are very rar... |
Returns the pycons3rt home directory based on OS
:return: (str) Full path to pycons3rt home
:raises: OSError
def get_pycons3rt_home_dir():
"""Returns the pycons3rt home directory based on OS
:return: (str) Full path to pycons3rt home
:raises: OSError
"""
if platform.system() == 'Linux':
... |
Initializes the pycons3rt directories
:return: None
:raises: OSError
def initialize_pycons3rt_dirs():
"""Initializes the pycons3rt directories
:return: None
:raises: OSError
"""
for pycons3rt_dir in [get_pycons3rt_home_dir(),
get_pycons3rt_user_dir(),
... |
for line in fileinput.input(logging_config_file_dest, inplace=True):
if re.search(replace_str, line):
new_line = re.sub(replace_str, log_dir_path, line, count=0)
sys.stdout.write(new_line)
else:
sys.stdout.write(line)
def main():
# Create the pycons3rt directorie... |
Add git hooks for commit and push to run linting and tests.
def add_hooks():
# type: () -> None
""" Add git hooks for commit and push to run linting and tests. """
# Detect virtualenv the hooks should use
# Detect virtualenv
virtual_env = conf.getenv('VIRTUAL_ENV')
if virtual_env is None:
... |
Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature.
def start(name):
# type: (str) -> None
""" Start working on a new feature by branching off develop.
This wi... |
Update the feature with updates committed to develop.
This will merge current develop into the current branch.
def update():
# type: () -> None
""" Update the feature with updates committed to develop.
This will merge current develop into the current branch.
"""
branch = git.current_branch(re... |
Cleanup a remotely merged branch.
def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
develop = conf.get('git.devel_branch', 'develop')
branch = git.current_branch(refresh=True)
common.assert_branch_type('feature')
# Pull develop with the merged feature
common.git_c... |
Remove all unnecessary files.
Args:
pretend (bool):
If set to **True**, do not delete any files, just show what would be
deleted.
exclude (list[str]):
A list of path patterns to exclude from deletion.
def clean(exclude):
# type: (bool, List[str]) -> None
... |
Create an empty pelconf.yaml from template
def init(quick):
# type: () -> None
""" Create an empty pelconf.yaml from template """
config_file = 'pelconf.yaml'
prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file)
if exists(config_file) and not click.confirm(shell.fmt(prompt)):
... |
Generator that yields tracebacks found in a lines iterator
The lines iterator can be:
- a file-like object
- a list (or deque) of lines.
- any other iterable sequence of strings
def tracebacks_from_lines(lines_iter):
"""Generator that yields tracebacks found in a lines iterator
The lines ite... |
Generator that yields tracebacks found in a file object
With reverse=True, searches backwards from the end of the file.
def tracebacks_from_file(fileobj, reverse=False):
"""Generator that yields tracebacks found in a file object
With reverse=True, searches backwards from the end of the file.
"""
... |
Read a file line by line, backwards
def BackwardsReader(file, BLKSIZE = 4096):
"""Read a file line by line, backwards"""
buf = ""
file.seek(0, 2)
lastchar = file.read(1)
trailing_newline = (lastchar == "\n")
while 1:
newline_pos = buf.rfind("\n")
pos = file.tell()
if ... |
r"""Obtain the inverse of a function.
Returns the numerical inverse of the function `f`. It may return a callable
that can be used to calculate the inverse, or the inverse of certain points
depending on the `y_values` argument.
In order for the numerical inverse to exist in its domain, the
input fu... |
render a progressed.io like progress bar
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10):
"""render a progressed.io like progress bar"""
status = status or ''
suffix = suffix or '%'
assert isinstance(count, int)
count_normalized = count if count <= total else total
fi... |
replace markup emoji and progressbars with actual things
# Example
```python
from habitipy.util import prettify
print(prettify('Write thesis :book: '))
```
```
Write thesis 📖 ██████████0%
```
def prettify(string):
"""
replace m... |
checks if a file is stored securely
def assert_secure_file(file):
"""checks if a file is stored securely"""
if not is_secure_file(file):
msg = """
File {0} can be read by other users.
This is not secure. Please run 'chmod 600 "{0}"'"""
raise SecurityError(dedent(msg).replace('\n... |
find and return gettext translation for package
def get_translation_for(package_name: str) -> gettext.NullTranslations:
"""find and return gettext translation for package"""
localedir = None
for localedir in pkg_resources.resource_filename(package_name, 'i18n'), None:
localefile = gettext.find(pack... |
finds and installs translation functions for package
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)):
"""finds and installs translation functions for package"""
translation = get_translation_for(package_name)
return [getattr(translation, x) for x in names] |
append _ to all python keywords
def escape_keywords(arr):
"""append _ to all python keywords"""
for i in arr:
i = i if i not in kwlist else i + '_'
i = i if '-' not in i else i.replace('-', '_')
yield i |
download API documentation from _branch_ of Habitica\'s repo on Github
def download_api(branch=None) -> str:
"""download API documentation from _branch_ of Habitica\'s repo on Github"""
habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'
if not branch:
branch = requests.get(habit... |
save `text` to apidoc cache
def save_apidoc(text: str) -> None:
"""save `text` to apidoc cache"""
apidoc_local = local.path(APIDOC_LOCAL_FILE)
if not apidoc_local.dirname.exists():
apidoc_local.dirname.mkdir()
with open(apidoc_local, 'w') as f:
f.write(text) |
read file and parse apiDoc lines
def parse_apidoc(
file_or_branch,
from_github=False,
save_github_version=True
) -> List['ApiEndpoint']:
"""read file and parse apiDoc lines"""
apis = [] # type: List[ApiEndpoint]
regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *'
regex += r'(?P... |
Get another leaf node with name `val` if possible
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']:
"""Get another leaf node with name `val` if possible"""
if val in self.paths:
return self.paths[val]
if self.param:
return self.param
raise IndexError(_... |
Determine if there is a leaf node with name `val`
def can_into(self, val: str) -> bool:
"""Determine if there is a leaf node with name `val`"""
return val in self.paths or (self.param and self.param_name == val) |
place a leaf node
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']):
"""place a leaf node"""
if part.startswith(':'):
if self.param and self.param != part:
err = """Cannot place param '{}' as '{self.param_name}' exist on node already!"""
raise ... |
return all possible paths one can take from this ApiNode
def keys(self) -> Iterator[str]:
"""return all possible paths one can take from this ApiNode"""
if self.param:
yield self.param_name
yield from self.paths.keys() |
parse and append a param
def add_param(self, group=None, type_='', field='', description=''):
"""parse and append a param"""
group = group or '(Parameter)'
group = group.lower()[1:-1]
p = Param(type_, field, description)
self.params[group][p.field] = p |
parse and append a success data param
def add_success(self, group=None, type_='', field='', description=''):
"""parse and append a success data param"""
group = group or '(200)'
group = int(group.lower()[1:-1])
self.retcode = self.retcode or group
if group != self.retcode:
... |
make a nice docstring for ipython
def render_docstring(self):
"""make a nice docstring for ipython"""
res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self)
if self.params:
for group, params in self.params.items():
res += '\n' + group + ' params:\n'
... |
check if obj has this api param
def validate(self, obj):
"""check if obj has this api param"""
if self.path:
for i in self.path:
obj = obj[i]
obj = obj[self.field]
raise NotImplementedError('Validation is not implemented yet') |
make a nice docstring for ipython
def render_docstring(self):
"""make a nice docstring for ipython"""
default = (' = ' + str(self.default)) if self.default else ''
opt = 'optional' if self.is_optional else ''
can_be = ' '.join(self.possible_values) if self.possible_values else ''
... |
validator for plumbum prompt
def is_uuid(u):
"""validator for plumbum prompt"""
if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex:
return u
return False |
Get authentication data from the AUTH_CONF file.
def load_conf(configfile, config=None):
"""Get authentication data from the AUTH_CONF file."""
default_login = 'your-login-for-api-here'
default_password = 'your-password-for-api-here'
config = config or {}
configfile = local.path(configfile)
if ... |
get content from server or cache
def get_content(api, rebuild_cache=False):
"""get content from server or cache"""
if hasattr(get_content, 'cache') and not rebuild_cache:
return get_content.cache
if not os.path.exists(CONTENT_JSON) or rebuild_cache:
import locale
content_endpoint = ... |
returns list of non-user rewards (potion, armoire, gear)
def get_additional_rewards(api):
"""returns list of non-user rewards (potion, armoire, gear)"""
c = get_content(api)
tasks = [c[i] for i in ['potion', 'armoire']]
tasks.extend(api.user.inventory.buy.get())
for task in tasks:
task['id'... |
task value/score color
def color(cls, value):
"""task value/score color"""
index = bisect(cls.breakpoints, value)
return colors.fg(cls.colors_[index]) |
Replace the existing cls.__init__() method with a new one which
also initialises the field generators and similar bookkeeping.
def augment_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the field generators and similar bookkeeping.
"""
or... |
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces.
def find_field_generators(obj):
"""
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance nam... |
Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux
def set_item_class_name(cls_obj):
"""
Return the first part of the class name ... |
obj:
The custom generator instance for which to create an item class
def make_item_class_for_custom_generator(obj):
"""
obj:
The custom generator instance for which to create an item class
"""
clsname = obj.__tohu_items_name__
attr_names = obj.field_gens.keys()
return make_item_... |
Replace the existing obj.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
(2) ..to do..
def add_new_init_method(obj... |
Attach a new `reset()` method to `obj` which resets the internal
seed generator of `obj` and then resets each of its constituent
field generators found in `obj.field_gens`.
def add_new_reset_method(obj):
"""
Attach a new `reset()` method to `obj` which resets the internal
seed generator of `obj` an... |
TODO
def add_new_next_method(obj):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
obj.__next__ = new_next |
TODO
def add_new_spawn_method(obj):
"""
TODO
"""
def new_spawn(self):
# TODO/FIXME: Check that this does the right thing:
# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour)
# (ii) ensure t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.