INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Round floating point number ( s ) mantissa to given number of digits. | def round_mantissa(arg, decimals=0):
"""
Round floating point number(s) mantissa to given number of digits.
Integers are not altered. The mantissa used is that of the floating point
number(s) when expressed in `normalized scientific notation
<https://en.wikipedia.org/wiki/Scientific_notation#Normal... |
r Format a list of numbers ( vector ) or a Numpy vector for printing. | def pprint_vector(vector, limit=False, width=None, indent=0, eng=False, frac_length=3):
r"""
Format a list of numbers (vector) or a Numpy vector for printing.
If the argument **vector** is :code:`None` the string :code:`'None'` is
returned
:param vector: Vector to pretty print or None
:type v... |
Convert number or number string to a number string in scientific notation. | def to_scientific_string(number, frac_length=None, exp_length=None, sign_always=False):
"""
Convert number or number string to a number string in scientific notation.
Full precision is maintained if the number is represented as a string
:param number: Number to convert
:type number: number or str... |
Return mantissa and exponent of a number in scientific notation. | def to_scientific_tuple(number):
"""
Return mantissa and exponent of a number in scientific notation.
Full precision is maintained if the number is represented as a string
:param number: Number
:type number: integer, float or string
:rtype: named tuple in which the first item is the mantissa... |
Seeks and removes the sourcemap comment. If found the sourcemap line is returned. | def find_sourcemap_comment(filepath, block_size=100):
"""
Seeks and removes the sourcemap comment. If found, the sourcemap line is
returned.
Bundled output files can have massive amounts of lines, and the sourceMap
comment is always at the end. So, to extract it efficiently, we read out the
lin... |
Return a tuple with the absolute path and relative path ( relative to STATIC_URL ) | def get_paths(self):
"""
Return a tuple with the absolute path and relative path (relative to STATIC_URL)
"""
outfile = self.get_outfile()
rel_path = os.path.relpath(outfile, settings.STATIC_ROOT)
return outfile, rel_path |
Check whether self. app is missing the. js extension and if it needs it. | def needs_ext(self):
"""
Check whether `self.app` is missing the '.js' extension and if it needs it.
"""
if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS:
name, ext = posixpath.splitext(self.app)
if not ext:
return True
return False |
Bundle the app and return the static url to the bundle. | def bundle(self):
"""
Bundle the app and return the static url to the bundle.
"""
outfile, rel_path = self.get_paths()
options = self.opts
if self.system._has_jspm_log():
self.command += ' --log {log}'
options.setdefault('log', 'err')
if ... |
Trace the dependencies for app. | def trace(self, app):
"""
Trace the dependencies for app.
A tracer-instance is shortlived, and re-tracing the same app should
yield the same results. Since tracing is an expensive process, cache
the result on the tracer instance.
"""
if app not in self._trace_cac... |
Compares the app deptree file hashes with the hashes stored in the cache. | def hashes_match(self, dep_tree):
"""
Compares the app deptree file hashes with the hashes stored in the
cache.
"""
hashes = self.get_hashes()
for module, info in dep_tree.items():
md5 = self.get_hash(info['path'])
if md5 != hashes[info['path']]:
... |
Convert the bytes object to a hexdump. | def format_hexdump(arg):
"""Convert the bytes object to a hexdump.
The output format will be:
<offset, 4-byte> <16-bytes of output separated by 1 space> <16 ascii characters>
"""
line = ''
for i in range(0, len(arg), 16):
if i > 0:
line += '\n'
chunk = arg[i:i +... |
Parse a docstring into ParameterInfo and ReturnInfo objects. | def parse_docstring(doc):
"""Parse a docstring into ParameterInfo and ReturnInfo objects."""
doc = inspect.cleandoc(doc)
lines = doc.split('\n')
section = None
section_indent = None
params = {}
returns = None
for line in lines:
line = line.rstrip()
if len(line) == 0:
... |
Get a list of all valid identifiers for the current context. | def valid_identifiers(self):
"""Get a list of all valid identifiers for the current context.
Returns:
list(str): A list of all of the valid identifiers for this context
"""
funcs = list(utils.find_all(self.contexts[-1])) + list(self.builtins)
return funcs |
Lazily load a callable. | def _deferred_add(cls, add_action):
"""Lazily load a callable.
Perform a lazy import of a context so that we don't have a huge initial startup time
loading all of the modules that someone might want even though they probably only
will use a few of them.
"""
module, _, o... |
Split a line into arguments using shlex and a dequoting routine. | def _split_line(self, line):
"""Split a line into arguments using shlex and a dequoting routine."""
parts = shlex.split(line, posix=self.posix_lex)
if not self.posix_lex:
parts = [self._remove_quotes(x) for x in parts]
return parts |
Check if our context matches something that we have initialization commands for. If so run them to initialize the context before proceeding with other commands. | def _check_initialize_context(self):
"""
Check if our context matches something that we have initialization commands
for. If so, run them to initialize the context before proceeding with other
commands.
"""
path = ".".join([annotate.context_name(x) for x in self.context... |
Return help information for a context or function. | def _builtin_help(self, args):
"""Return help information for a context or function."""
if len(args) == 0:
return self.list_dir(self.contexts[-1])
if len(args) == 1:
func = self.find_function(self.contexts[-1], args[0])
return annotate.get_help(func)
... |
Find a function in the given context by name. | def find_function(self, context, funname):
"""Find a function in the given context by name.
This function will first search the list of builtins and if the
desired function is not a builtin, it will continue to search
the given context.
Args:
context (object): A dic... |
Return a listing of all of the functions in this context including builtins. | def list_dir(self, context):
"""Return a listing of all of the functions in this context including builtins.
Args:
context (object): The context to print a directory for.
Returns:
str
"""
doc = inspect.getdoc(context)
listing = ""
listi... |
Check if an argument is a flag. | def _is_flag(cls, arg):
"""Check if an argument is a flag.
A flag starts with - or -- and the next character must be a letter
followed by letters, numbers, - or _. Currently we only check the
alpha'ness of the first non-dash character to make sure we're not just
looking at a ne... |
Process arguments from the command line into positional and kw args. | def process_arguments(self, func, args):
"""Process arguments from the command line into positional and kw args.
Arguments are consumed until the argument spec for the function is filled
or a -- is found or there are no more arguments. Keyword arguments can be
specified using --field=v... |
Try to find the value for a keyword argument. | def _extract_arg_value(cls, arg_name, arg_type, remaining):
"""Try to find the value for a keyword argument."""
next_arg = None
should_consume = False
if len(remaining) > 0:
next_arg = remaining[0]
should_consume = True
if next_arg == '--':
... |
Invoke a function given a list of arguments with the function listed first. | def invoke_one(self, line):
"""Invoke a function given a list of arguments with the function listed first.
The function is searched for using the current context on the context stack
and its annotated type information is used to convert all of the string parameters
passed in line to app... |
Invoke a one or more function given a list of arguments. | def invoke(self, line):
"""Invoke a one or more function given a list of arguments.
The functions are searched for using the current context on the context stack
and its annotated type information is used to convert all of the string parameters
passed in line to appropriate python types... |
Parse and invoke a string line. | def invoke_string(self, line):
"""Parse and invoke a string line.
Args:
line (str): The line that we want to parse and invoke.
Returns:
bool: A boolean specifying if the last function created a new context
(False if a new context was created) and a list ... |
Parse a single typed parameter statement. | def parse_param(param, include_desc=False):
"""Parse a single typed parameter statement."""
param_def, _colon, desc = param.partition(':')
if not include_desc:
desc = None
else:
desc = desc.lstrip()
if _colon == "":
raise ValidationError("Invalid parameter declaration in do... |
Parse a single return statement declaration. | def parse_return(return_line, include_desc=False):
"""Parse a single return statement declaration.
The valid types of return declarion are a Returns: section heading
followed a line that looks like:
type [format-as formatter]: description
OR
type [show-as (string | context)]: description sent... |
Attempt to find the canonical name of this section. | def _classify_section(cls, section):
"""Attempt to find the canonical name of this section."""
name = section.lower()
if name in frozenset(['args', 'arguments', "params", "parameters"]):
return cls.ARGS_SECTION
if name in frozenset(['returns', 'return']):
retur... |
Classify a line into a type of object. | def _classify_line(cls, line):
"""Classify a line into a type of object."""
line = line.rstrip()
if len(line) == 0:
return BlankLine('')
if ' ' not in line and line.endswith(':'):
name = line[:-1]
return SectionHeader(name)
if line.startswi... |
Join adjacent lines together into paragraphs using either a blank line or indent as separator. | def _join_paragraphs(cls, lines, use_indent=False, leading_blanks=False, trailing_blanks=False):
"""Join adjacent lines together into paragraphs using either a blank line or indent as separator."""
curr_para = []
paragraphs = []
for line in lines:
if use_indent:
... |
Wrap format and print this docstring for a specific width. | def wrap_and_format(self, width=None, include_params=False, include_return=False, excluded_params=None):
"""Wrap, format and print this docstring for a specific width.
Args:
width (int): The number of characters per line. If set to None
this will be inferred from the termin... |
Convert value to type typename | def convert_to_type(self, value, typename, **kwargs):
"""
Convert value to type 'typename'
If the conversion routine takes various kwargs to
modify the conversion process, \\**kwargs is passed
through to the underlying conversion function
"""
try:
if ... |
Convert binary data to type type. | def convert_from_binary(self, binvalue, type, **kwargs):
"""
Convert binary data to type 'type'.
'type' must have a convert_binary function. If 'type'
supports size checking, the size function is called to ensure
that binvalue is the correct size for deserialization
"""... |
Get the size of this type for converting a hex string to the type. Return 0 if the size is not known. | def get_type_size(self, type):
"""
Get the size of this type for converting a hex string to the
type. Return 0 if the size is not known.
"""
typeobj = self.get_type(type)
if hasattr(typeobj, 'size'):
return typeobj.size()
return 0 |
Convert value to type and format it as a string | def format_value(self, value, type, format=None, **kwargs):
"""
Convert value to type and format it as a string
type must be a known type in the type system and format,
if given, must specify a valid formatting option for the
specified type.
"""
typed_val = self... |
Validate that all required type methods are implemented. | def _validate_type(cls, typeobj):
"""
Validate that all required type methods are implemented.
At minimum a type must have:
- a convert() or convert_binary() function
- a default_formatter() function
Raises an ArgumentError if the type is not valid
"""
... |
Check if type is known to the type system. | def is_known_type(self, type_name):
"""Check if type is known to the type system.
Returns:
bool: True if the type is a known instantiated simple type, False otherwise
"""
type_name = str(type_name)
if type_name in self.known_types:
return True
r... |
Given a potentially complex type split it into its base type and specializers | def split_type(self, typename):
"""
Given a potentially complex type, split it into its base type and specializers
"""
name = self._canonicalize_type(typename)
if '(' not in name:
return name, False, []
base, sub = name.split('(')
if len(sub) == 0 or... |
Instantiate a complex type. | def instantiate_type(self, typename, base, subtypes):
"""Instantiate a complex type."""
if base not in self.type_factories:
raise ArgumentError("unknown complex base type specified", passed_type=typename, base_type=base)
base_type = self.type_factories[base]
#Make sure all... |
Return the type object corresponding to a type name. | def get_type(self, type_name):
"""Return the type object corresponding to a type name.
If type_name is not found, this triggers the loading of
external types until a matching type is found or until there
are no more external type sources.
"""
type_name = self._canonical... |
Check if format is known for given type. | def is_known_format(self, type, format):
"""
Check if format is known for given type.
Returns boolean indicating if format is valid for the specified type.
"""
typeobj = self.get_type(type)
formatter = "format_%s" % str(format)
if not hasattr(typeobj, formatter... |
Given a module - like object that defines a type add it to our type system so that it can be used with the iotile tool and with other annotated API functions. | def inject_type(self, name, typeobj):
"""
Given a module-like object that defines a type, add it to our type system so that
it can be used with the iotile tool and with other annotated API functions.
"""
name = self._canonicalize_type(name)
_, is_complex, _ = self.split_... |
Given a module that contains a list of some types find all symbols in the module that do not start with _ and attempt to import them as types. | def load_type_module(self, module):
"""
Given a module that contains a list of some types find all symbols in the module that
do not start with _ and attempt to import them as types.
"""
for name in (x for x in dir(module) if not x.startswith('_')):
typeobj = getattr... |
Given a path to a python package or module load that module search for all defined variables inside of it that do not start with _ or __ and inject them into the type system. If any of the types cannot be injected silently ignore them unless verbose is True. If path points to a module it should not contain the trailing... | def load_external_types(self, path):
"""
Given a path to a python package or module, load that module, search for all defined variables
inside of it that do not start with _ or __ and inject them into the type system. If any of the
types cannot be injected, silently ignore them unless v... |
Check if we have enough arguments to call this function. | def spec_filled(self, pos_args, kw_args):
"""Check if we have enough arguments to call this function.
Args:
pos_args (list): A list of all the positional values we have.
kw_args (dict): A dict of all of the keyword args we have.
Returns:
bool: True if we hav... |
Add type information for a parameter by name. | def add_param(self, name, type_name, validators, desc=None):
"""Add type information for a parameter by name.
Args:
name (str): The name of the parameter we wish to annotate
type_name (str): The name of the parameter's type
validators (list): A list of either strings... |
Add type information to the return value of this function. | def typed_returnvalue(self, type_name, formatter=None):
"""Add type information to the return value of this function.
Args:
type_name (str): The name of the type of the return value.
formatter (str): An optional name of a formatting function specified
for the typ... |
Use a custom function to print the return value. | def custom_returnvalue(self, printer, desc=None):
"""Use a custom function to print the return value.
Args:
printer (callable): A function that should take in the return
value and convert it to a string.
desc (str): An optional description of the return value.
... |
Try to convert a prefix into a parameter name. | def match_shortname(self, name, filled_args=None):
"""Try to convert a prefix into a parameter name.
If the result could be ambiguous or there is no matching
parameter, throw an ArgumentError
Args:
name (str): A prefix for a parameter name
filled_args (list): A ... |
Get the parameter type information by name. | def param_type(self, name):
"""Get the parameter type information by name.
Args:
name (str): The full name of a parameter.
Returns:
str: The type name or None if no type information is given.
"""
self._ensure_loaded()
if name not in self.annota... |
Return our function signature as a string. | def signature(self, name=None):
"""Return our function signature as a string.
By default this function uses the annotated name of the function
however if you need to override that with a custom name you can
pass name=<custom name>
Args:
name (str): Optional name to ... |
Format the return value of this function as a string. | def format_returnvalue(self, value):
"""Format the return value of this function as a string.
Args:
value (object): The return value that we are supposed to format.
Returns:
str: The formatted return value, or None if this function indicates
that it does... |
Convert and validate a positional argument. | def convert_positional_argument(self, index, arg_value):
"""Convert and validate a positional argument.
Args:
index (int): The positional index of the argument
arg_value (object): The value to convert and validate
Returns:
object: The converted value.
... |
Check if there are any missing or duplicate arguments. | def check_spec(self, pos_args, kwargs=None):
"""Check if there are any missing or duplicate arguments.
Args:
pos_args (list): A list of arguments that will be passed as positional
arguments.
kwargs (dict): A dictionary of the keyword arguments that will be passed... |
Given a parameter with type information convert and validate it. | def convert_argument(self, arg_name, arg_value):
"""Given a parameter with type information, convert and validate it.
Args:
arg_name (str): The name of the argument to convert and validate
arg_value (object): The value to convert and validate
Returns:
object... |
Format this exception as a string including class name. | def format(self, exclude_class=False):
"""Format this exception as a string including class name.
Args:
exclude_class (bool): Whether to exclude the exception class
name when formatting this exception
Returns:
string: a multiline string with the message,... |
Convert this exception to a dictionary. | def to_dict(self):
"""Convert this exception to a dictionary.
Returns:
dist: A dictionary of information about this exception,
Has a 'reason' key, a 'type' key and a dictionary of params
"""
out = {}
out['reason'] = self.msg
out['type'] = se... |
Check the type of all parameters with type information converting as appropriate and then execute the function. | def _check_and_execute(func, *args, **kwargs):
"""
Check the type of all parameters with type information, converting
as appropriate and then execute the function.
"""
convargs = []
#Convert and validate all arguments
for i, arg in enumerate(args):
val = func.metadata.convert_posit... |
Parse a list of validator names or n - tuples checking for errors. | def _parse_validators(valids):
"""Parse a list of validator names or n-tuples, checking for errors.
Returns:
list((func_name, [args...])): A list of validator function names and a
potentially empty list of optional parameters for each function.
"""
outvals = []
for val in vali... |
Find all annotated function inside of a container. | def find_all(container):
"""Find all annotated function inside of a container.
Annotated functions are identified as those that:
- do not start with a _ character
- are either annotated with metadata
- or strings that point to lazily loaded modules
Args:
container (object): The contain... |
Given a module create a context from all of the top level annotated symbols in that module. | def context_from_module(module):
"""
Given a module, create a context from all of the top level annotated
symbols in that module.
"""
con = find_all(module)
if hasattr(module, "__doc__"):
setattr(con, "__doc__", module.__doc__)
name = module.__name__
if hasattr(module, "_name_... |
Return usage information about a context or function. | def get_help(func):
"""Return usage information about a context or function.
For contexts, just return the context name and its docstring
For functions, return the function signature as well as its
argument types.
Args:
func (callable): An annotated callable function
Returns:
... |
Decorate a function to give type information about its parameters. | def param(name, type_name, *validators, **kwargs):
"""Decorate a function to give type information about its parameters.
This function stores a type name, optional description and optional list
of validation functions along with the decorated function it is called
on in order to allow run time type con... |
Specify how the return value of this function should be handled. | def returns(desc=None, printer=None, data=True):
"""Specify how the return value of this function should be handled.
Args:
desc (str): A deprecated description of the return value
printer (callable): A callable function that can format this return value
data (bool): A deprecated paramet... |
Specify that this function returns a typed value. | def return_type(type_name, formatter=None):
"""Specify that this function returns a typed value.
Args:
type_name (str): A type name known to the global typedargs type system
formatter (str): An optional name of a formatting function specified
for the type given in type_name.
"""... |
Declare that a class defines a context. | def context(name=None):
"""Declare that a class defines a context.
Contexts are for use with HierarchicalShell for discovering
and using functionality from the command line.
Args:
name (str): Optional name for this context if you don't want
to just use the class name.
"""
... |
Annotate a function using information from its docstring. | def docannotate(func):
"""Annotate a function using information from its docstring.
The annotation actually happens at the time the function is first called
to improve startup time. For this function to work, the docstring must be
formatted correctly. You should use the typedargs pylint plugin to mak... |
Mark a function as callable from the command line. | def annotated(func, name=None):
"""Mark a function as callable from the command line.
This function is meant to be called as decorator. This function
also initializes metadata about the function's arguments that is
built up by the param decorator.
Args:
func (callable): The function that ... |
Given an object with a docstring return the first line of the docstring | def short_description(func):
"""
Given an object with a docstring, return the first line of the docstring
"""
doc = inspect.getdoc(func)
if doc is not None:
doc = inspect.cleandoc(doc)
lines = doc.splitlines()
return lines[0]
return "" |
Load cron modules for applications listed in INSTALLED_APPS. | def load():
"""
Load ``cron`` modules for applications listed in ``INSTALLED_APPS``.
"""
autodiscover_modules('cron')
if PROJECT_MODULE:
if '.' in PROJECT_MODULE.__name__:
try:
import_module('%s.cron' % '.'.join(
PROJECT_MODULE.__name__.split(... |
Register tasks with cron. | def install():
"""
Register tasks with cron.
"""
load()
tab = crontab.CronTab(user=True)
for task in registry:
tab.new(task.command, KRONOS_BREADCRUMB).setall(task.schedule)
tab.write()
return len(registry) |
Print the tasks that would be installed in the crontab for debugging purposes. | def printtasks():
"""
Print the tasks that would be installed in the
crontab, for debugging purposes.
"""
load()
tab = crontab.CronTab('')
for task in registry:
tab.new(task.command, KRONOS_BREADCRUMB).setall(task.schedule)
print(tab.render()) |
Uninstall tasks from cron. | def uninstall():
"""
Uninstall tasks from cron.
"""
tab = crontab.CronTab(user=True)
count = len(list(tab.find_comment(KRONOS_BREADCRUMB)))
tab.remove_all(comment=KRONOS_BREADCRUMB)
tab.write()
return count |
Create a project handler | def create(self, uri, local_path):
"""Create a project handler
Args:
uri (str): schema://something formatted uri
local_path (str): the project configs directory
Return:
ProjectHandler derived class instance
"""
matches = self.schema_pattern.s... |
Load the projects config data from local path | def load(self):
"""Load the projects config data from local path
Returns:
Dict: project_name -> project_data
"""
projects = {}
path = os.path.expanduser(self.path)
if not os.path.isdir(path):
return projects
logger.debug("Load project c... |
Save the projects configs to local path | def save(self, projects):
"""Save the projects configs to local path
Args:
projects (dict): project_name -> project_data
"""
base_path = os.path.expanduser(self.path)
if not os.path.isdir(base_path):
return
logger.debug("Save projects config to... |
Creates a property with the given name but the cls will created only with the first call | def define_singleton(carrier, name, cls, cls_args = {}):
"""Creates a property with the given name, but the cls will created only with the first call
Args:
carrier: an instance of the class where want to reach the cls instance
name (str): the variable name of the cls instance
cls (type)... |
Get the dependencies of the Project | def get_dependent_projects(self, recursive = True):
"""Get the dependencies of the Project
Args:
recursive (bool): add the dependant project's dependencies too
Returns:
dict of project name and project instances
"""
projects = {}
for name, ref in... |
Calls the project handler same named function | def post_process(func):
"""Calls the project handler same named function
Note: the project handler may add some extra arguments to the command,
so when use this decorator, add **kwargs to the end of the arguments
"""
@wraps(func)
def wrapper(*args, **kwargs):
res = func(*args, **... |
REFACTOR status to project init result ENUM jelenleg ha a project init False akkor torlunk minden adatot a projectrol de van egy atmenet mikor csak a lang init nem sikerult erre valo jelenleg a status. ez rossz | def __init(self, project, path, force, init_languages):
status = {}
"""
REFACTOR status to project init result ENUM
jelenleg ha a project init False, akkor torlunk minden adatot a projectrol
de van egy atmenet, mikor csak a lang init nem sikerult
erre valo jelenleg a stat... |
Takes an object a key and a value and produces a new object that is a copy of the original but with value as the new value of key. | def setitem(self, key, value):
# type: (Any, Any, Any) -> Any
'''Takes an object, a key, and a value and produces a new object
that is a copy of the original but with ``value`` as the new value of
``key``.
The following equality should hold for your definition:
.. code-block:: python
... |
Takes an object a string and a value and produces a new object that is a copy of the original but with the attribute called name set to value. | def setattr(self, name, value):
# type: (Any, Any, Any) -> Any
'''Takes an object, a string, and a value and produces a new object
that is a copy of the original but with the attribute called ``name``
set to ``value``.
The following equality should hold for your definition:
.. code-block:: pyt... |
Takes a collection and an item and returns a new collection of the same type that contains the item. The notion of contains is defined by the object itself ; The following must be True: | def contains_add(self, item):
# type (Any, Any) -> Any
'''Takes a collection and an item and returns a new collection
of the same type that contains the item. The notion of "contains"
is defined by the object itself; The following must be ``True``:
.. code-block:: python
item in contains_a... |
Takes a collection and an item and returns a new collection of the same type with that item removed. The notion of contains is defined by the object itself ; the following must be True: | def contains_remove(self, item):
# type (Any, Any) -> Any
'''Takes a collection and an item and returns a new collection
of the same type with that item removed. The notion of "contains"
is defined by the object itself; the following must be ``True``:
.. code-block:: python
item not in con... |
Takes an object and an iterable and produces a new object that is a copy of the original with data from iterable reincorporated. It is intended as the inverse of the to_iter function. Any state in self that is not modelled by the iterable should remain unchanged. | def from_iter(self, iterable):
# type: (Any, Any) -> Any
'''Takes an object and an iterable and produces a new object that is
a copy of the original with data from ``iterable`` reincorporated. It
is intended as the inverse of the ``to_iter`` function. Any state in
``self`` that is not modelled by th... |
Set the focus to newvalue. | def set(self, newvalue):
# type: (B) -> Callable[[S], T]
'''Set the focus to `newvalue`.
>>> from lenses import lens
>>> set_item_one_to_four = lens[1].set(4)
>>> set_item_one_to_four([1, 2, 3])
[1, 4, 3]
'''
def setter(state):
... |
Set many foci to values taken by iterating over new_values. | def set_many(self, new_values):
# type: (Iterable[B]) -> Callable[[S], T]
'''Set many foci to values taken by iterating over `new_values`.
>>> from lenses import lens
>>> lens.Each().set_many(range(4, 7))([0, 1, 2])
[4, 5, 6]
'''
def setter_many(stat... |
Apply a function to the focus. | def modify(self, func):
# type: (Callable[[A], B]) -> Callable[[S], T]
'''Apply a function to the focus.
>>> from lenses import lens
>>> convert_item_one_to_string = lens[1].modify(str)
>>> convert_item_one_to_string([1, 2, 3])
[1, '2', 3]
>>>... |
Applies func to the data inside the args functors incrementally. func must be a curried function that takes len ( args ) arguments. | def multiap(func, *args):
'''Applies `func` to the data inside the `args` functors
incrementally. `func` must be a curried function that takes
`len(args)` arguments.
>>> func = lambda a: lambda b: a + b
>>> multiap(func, [1, 10], [100])
[101, 110]
'''
functor = typeclass.fma... |
Returns a function that can be called n times with a single argument before returning all the args that have been passed to it in a tuple. Useful as a substitute for functions that can t easily be curried. | def collect_args(n):
'''Returns a function that can be called `n` times with a single
argument before returning all the args that have been passed to it
in a tuple. Useful as a substitute for functions that can't easily be
curried.
>>> collect_args(3)(1)(2)(3)
(1, 2, 3)
'''
args... |
Intended to be overridden by subclasses. Raises NotImplementedError. | def func(self, f, state):
'''Intended to be overridden by subclasses. Raises
NotImplementedError.'''
message = 'Tried to use unimplemented lens {}.'
raise NotImplementedError(message.format(type(self))) |
Runs the lens over the state applying f to all the foci collecting the results together using the applicative functor functions defined in lenses. typeclass. f must return an applicative functor. For the case when no focus exists you must also provide a pure which should take a focus and return the pure form of the fun... | def apply(self, f, pure, state):
'''Runs the lens over the `state` applying `f` to all the foci
collecting the results together using the applicative functor
functions defined in `lenses.typeclass`. `f` must return an
applicative functor. For the case when no focus exists you must
... |
Previews a potentially non - existant focus within state. Returns Just ( focus ) if it exists Nothing otherwise. | def preview(self, state):
# type: (S) -> Just[B]
'''Previews a potentially non-existant focus within
`state`. Returns `Just(focus)` if it exists, Nothing otherwise.
Requires kind Fold.
'''
if not self._is_kind(Fold):
raise TypeError('Must be an instance of Fo... |
Returns the focus within state. If multiple items are focused then it will attempt to join them together as a monoid. See lenses. typeclass. mappend. | def view(self, state):
# type: (S) -> B
'''Returns the focus within `state`. If multiple items are
focused then it will attempt to join them together as a monoid.
See `lenses.typeclass.mappend`.
Requires kind Fold. This method will raise TypeError if the
optic has no way... |
Returns a list of all the foci within state. | def to_list_of(self, state):
# type: (S) -> List[B]
'''Returns a list of all the foci within `state`.
Requires kind Fold. This method will raise TypeError if the
optic has no way to get any foci.
'''
if not self._is_kind(Fold):
raise TypeError('Must be an ins... |
Applies a function fn to all the foci within state. | def over(self, state, fn):
# type: (S, Callable[[A], B]) -> T
'''Applies a function `fn` to all the foci within `state`.
Requires kind Setter. This method will raise TypeError when the
optic has no way to set foci.
'''
if not self._is_kind(Setter):
raise Type... |
Sets all the foci within state to value. | def set(self, state, value):
# type: (S, B) -> T
'''Sets all the foci within `state` to `value`.
Requires kind Setter. This method will raise TypeError when the
optic has no way to set foci.
'''
if not self._is_kind(Setter):
raise TypeError('Must be an instan... |
Sets all the foci within state to values taken from iterable. | def iterate(self, state, iterable):
# type: (S, Iterable[B]) -> T
'''Sets all the foci within `state` to values taken from `iterable`.
Requires kind Setter. This method will raise TypeError when the
optic has no way to set foci.
'''
if not self._is_kind(Setter):
... |
Returns a class representing the kind of optic. | def kind(self):
'''Returns a class representing the 'kind' of optic.'''
optics = [
Equality,
Isomorphism,
Prism,
Review,
Lens,
Traversal,
Getter,
Setter,
Fold,
]
for optic in optic... |
The main function. Instantiates a GameState object and then enters a REPL - like main loop waiting for input updating the state based on the input then outputting the new state. | def main():
'''The main function. Instantiates a GameState object and then
enters a REPL-like main loop, waiting for input, updating the state
based on the input, then outputting the new state.'''
state = GameState()
print(state)
while state.running:
input = get_single_char()
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.