_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q274900
|
SystemBundle.bundle
|
test
|
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 options.get('minify'):
self.command += ' --minify'
if options.get('skip_source_maps'):
self.command += ' --skip-source-maps'
try:
cmd = self.command.format(app=self.app, outfile=outfile, **options)
proc = subprocess.Popen(
cmd, shell=True, cwd=self.system.cwd, stdout=self.stdout,
stdin=self.stdin, stderr=self.stderr)
result, err = proc.communicate() # block until it's done
if err and self.system._has_jspm_log():
fmt = 'Could not bundle \'%s\': \n%s'
logger.warn(fmt, self.app, err)
raise BundleError(fmt % (self.app, err))
if result.strip():
logger.info(result)
except (IOError, OSError) as e:
|
python
|
{
"resource": ""
}
|
q274901
|
SystemTracer.trace
|
test
|
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_cache:
|
python
|
{
"resource": ""
}
|
q274902
|
SystemTracer.hashes_match
|
test
|
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():
|
python
|
{
"resource": ""
}
|
q274903
|
format_hexdump
|
test
|
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 =
|
python
|
{
"resource": ""
}
|
q274904
|
parse_docstring
|
test
|
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:
continue
elif str(line) == 'Args:':
section = 'args'
section_indent = None
continue
elif str(line) == 'Returns:':
section = 'return'
section_indent = None
continue
if section is not None:
stripped = line.lstrip()
margin = len(line) - len(stripped)
if section_indent is None:
section_indent = margin
if margin != section_indent:
|
python
|
{
"resource": ""
}
|
q274905
|
HierarchicalShell.valid_identifiers
|
test
|
def valid_identifiers(self):
"""Get a list of all valid identifiers for the current context.
Returns:
|
python
|
{
"resource": ""
}
|
q274906
|
HierarchicalShell._deferred_add
|
test
|
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.
|
python
|
{
"resource": ""
}
|
q274907
|
HierarchicalShell._split_line
|
test
|
def _split_line(self, line):
"""Split a line into arguments using shlex and a dequoting routine."""
parts = shlex.split(line, posix=self.posix_lex)
|
python
|
{
"resource": ""
}
|
q274908
|
HierarchicalShell._check_initialize_context
|
test
|
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.contexts])
|
python
|
{
"resource": ""
}
|
q274909
|
HierarchicalShell._builtin_help
|
test
|
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])
|
python
|
{
"resource": ""
}
|
q274910
|
HierarchicalShell.find_function
|
test
|
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 dict or class that is a typedargs context
funname (str): The name of the function to find
Returns:
|
python
|
{
"resource": ""
}
|
q274911
|
HierarchicalShell.list_dir
|
test
|
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 = ""
listing += "\n"
listing += annotate.context_name(context) + "\n"
if doc is not None:
doc = inspect.cleandoc(doc)
listing += doc + "\n"
listing += "\nDefined Functions:\n"
is_dict = False
if isinstance(context, dict):
funs = context.keys()
is_dict = True
else:
funs = utils.find_all(context)
for fun in sorted(funs):
override_name = None
if is_dict:
override_name = fun
fun = self.find_function(context, fun)
if isinstance(fun, dict):
|
python
|
{
"resource": ""
}
|
q274912
|
HierarchicalShell._is_flag
|
test
|
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 negative number.
Returns:
bool: Whether the argument is a flag.
"""
if arg == '--':
|
python
|
{
"resource": ""
}
|
q274913
|
HierarchicalShell.process_arguments
|
test
|
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=value, -f value or --field value. Positional
arguments are specified just on the command line itself.
If a keyword argument (`field`) is a boolean, it can be set to True by just passing
--field or -f without needing to explicitly pass True unless this would cause
ambiguity in parsing since the next expected positional argument is also a boolean
or a string.
Args:
func (callable): A function previously annotated with type information
args (list): A list of all of the potential arguments to this function.
Returns:
(args, kw_args, unused args): A tuple with a list of args, a dict of
keyword args and a list of any unused args that were not processed.
"""
pos_args = []
kw_args = {}
while len(args) > 0:
if func.metadata.spec_filled(pos_args, kw_args) and not self._is_flag(args[0]):
break
arg = args.pop(0)
if arg == '--':
break
elif self._is_flag(arg):
arg_value = None
arg_name = None
if len(arg) == 2:
arg_name = func.metadata.match_shortname(arg[1:], filled_args=pos_args)
else:
if not arg.startswith('--'):
raise ArgumentError("Invalid method of specifying keyword argument that did not start with --", argument=arg)
# Skip the --
arg = arg[2:]
|
python
|
{
"resource": ""
}
|
q274914
|
HierarchicalShell._extract_arg_value
|
test
|
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 == '--':
next_arg = None
# Generally we just return the next argument, however if the type
# is bool we allow not specifying anything to mean true if there
# is no ambiguity
if arg_type == "bool":
if next_arg is None or next_arg.startswith('-'):
|
python
|
{
"resource": ""
}
|
q274915
|
HierarchicalShell.invoke_one
|
test
|
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 appropriate python types.
Args:
line (list): The list of command line arguments.
Returns:
(object, list, bool): A tuple containing the return value of the function, if any,
a boolean specifying if the function created a new context (False if a new context
was created) and a list with the remainder of the command line if this function
did not consume all arguments.
"""
funname = line.pop(0)
context = self.contexts[-1]
func = self.find_function(context, funname)
#If this is a context derived from a module or package, just jump to it
#since there is no initialization function
if isinstance(func, dict):
self.contexts.append(func)
self._check_initialize_context()
return None, line, False
# If the function wants arguments directly, do not parse them, otherwise turn them
# into positional and kw arguments
if func.takes_cmdline is True:
val = func(line)
line
|
python
|
{
"resource": ""
}
|
q274916
|
HierarchicalShell.invoke
|
test
|
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.
Args:
line (list): The list of command line arguments.
Returns:
bool: A boolean specifying if the last function created a new context
(False if a new context was created) and a list with the remainder of the
|
python
|
{
"resource": ""
}
|
q274917
|
HierarchicalShell.invoke_string
|
test
|
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 with the remainder of the
command line if this function did not consume all arguments.)
"""
# Make sure line is a unicode string on all python versions
|
python
|
{
"resource": ""
}
|
q274918
|
parse_param
|
test
|
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 docstring, missing colon", declaration=param)
param_name, _space, param_type = param_def.partition(' ')
if len(param_type) < 2 or param_type[0] != '(' or param_type[-1] != ')':
|
python
|
{
"resource": ""
}
|
q274919
|
parse_return
|
test
|
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 sentence
"""
ret_def, _colon, desc = return_line.partition(':')
if _colon == "":
raise ValidationError("Invalid return declaration in docstring, missing colon", declaration=ret_def)
if not include_desc:
desc = None
if 'show-as' in ret_def:
ret_type, _showas, show_type = ret_def.partition('show-as')
ret_type = ret_type.strip()
show_type = show_type.strip()
if show_type not in ('string', 'context'):
|
python
|
{
"resource": ""
}
|
q274920
|
ParsedDocstring._classify_section
|
test
|
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"]):
|
python
|
{
"resource": ""
}
|
q274921
|
ParsedDocstring._classify_line
|
test
|
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.startswith(' '):
|
python
|
{
"resource": ""
}
|
q274922
|
ParsedDocstring._join_paragraphs
|
test
|
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:
if line.startswith(' '):
curr_para.append(line.lstrip())
continue
elif line == '':
continue
else:
if len(curr_para) > 0:
paragraphs.append(cls._join_paragraph(curr_para, leading_blanks, trailing_blanks))
curr_para = [line.lstrip()]
else:
if len(line) != 0:
|
python
|
{
"resource": ""
}
|
q274923
|
ParsedDocstring.wrap_and_format
|
test
|
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 terminal width and default
to 80 if not passed or if passed as None and the terminal
width cannot be determined.
include_return (bool): Include the return information section
in the output.
include_params (bool): Include a parameter information section
in the output.
excluded_params (list): An optional list of parameter names to exclude.
Options for excluding things are, for example, 'self' or 'cls'.
"""
if excluded_params is None:
excluded_params = []
out = StringIO()
if width is None:
width, _height = get_terminal_size()
for line in self.maindoc:
if isinstance(line, Line):
out.write(fill(line.contents, width=width))
out.write('\n')
elif isinstance(line, BlankLine):
out.write('\n')
|
python
|
{
"resource": ""
}
|
q274924
|
TypeSystem.convert_to_type
|
test
|
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 isinstance(value, bytearray):
return self.convert_from_binary(value, typename, **kwargs)
typeobj = self.get_type(typename)
|
python
|
{
"resource": ""
}
|
q274925
|
TypeSystem.convert_from_binary
|
test
|
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
"""
size = self.get_type_size(type)
if size > 0 and len(binvalue) != size:
raise ArgumentError("Could
|
python
|
{
"resource": ""
}
|
q274926
|
TypeSystem.get_type_size
|
test
|
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.
"""
|
python
|
{
"resource": ""
}
|
q274927
|
TypeSystem.format_value
|
test
|
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.convert_to_type(value, type, **kwargs)
typeobj = self.get_type(type)
#Allow types to specify default formatting functions as 'default_formatter'
#otherwise if not format is specified, just convert the value to a string
if format is None:
if hasattr(typeobj, 'default_formatter'):
format_func = getattr(typeobj, 'default_formatter')
|
python
|
{
"resource": ""
}
|
q274928
|
TypeSystem._validate_type
|
test
|
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
"""
if not (hasattr(typeobj, "convert") or hasattr(typeobj, "convert_binary")):
|
python
|
{
"resource": ""
}
|
q274929
|
TypeSystem.is_known_type
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274930
|
TypeSystem.split_type
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274931
|
TypeSystem.instantiate_type
|
test
|
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 of the subtypes are valid
for sub_type in subtypes:
try:
self.get_type(sub_type)
except KeyValueException
|
python
|
{
"resource": ""
}
|
q274932
|
TypeSystem.get_type
|
test
|
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._canonicalize_type(type_name)
# Add basic transformations on common abbreviations
if str(type_name) == 'int':
type_name = 'integer'
elif str(type_name) == 'str':
type_name = 'string'
elif str(type_name) == 'dict':
type_name = 'basic_dict'
if self.is_known_type(type_name):
return self.known_types[type_name]
base_type, is_complex, subtypes = self.split_type(type_name)
if is_complex and base_type in self.type_factories:
self.instantiate_type(type_name, base_type, subtypes)
return self.known_types[type_name]
# If we're here, this is a type that we don't know anything about, so go find it.
i = 0
for i, (source, name) in enumerate(self._lazy_type_sources):
if isinstance(source, str):
import pkg_resources
for entry in pkg_resources.iter_entry_points(source):
try:
mod = entry.load()
type_system.load_type_module(mod)
except: #pylint:disable=W0702; We want to catch everything here since we don't want external plugins breaking us
fail_info = ("Entry point group: %s, name: %s" % (source, entry.name), sys.exc_info)
logging.exception("Error loading external type source from entry point, group: %s, name: %s", source, entry.name)
self.failed_sources.append(fail_info)
else:
try:
source(self)
|
python
|
{
"resource": ""
}
|
q274933
|
TypeSystem.is_known_format
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q274934
|
TypeSystem.inject_type
|
test
|
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_type(name)
if self.is_known_type(name):
raise ArgumentError("attempting to inject a type that is already defined", type=name)
if (not is_complex) and self._is_factory(typeobj):
if name in self.type_factories:
raise ArgumentError("attempted to inject a complex type factory that is already defined", type=name)
|
python
|
{
"resource": ""
}
|
q274935
|
TypeSystem.load_type_module
|
test
|
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('_')):
|
python
|
{
"resource": ""
}
|
q274936
|
AnnotatedMetadata.spec_filled
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274937
|
AnnotatedMetadata.add_param
|
test
|
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 or n tuples that each
specify a validator defined for type_name. If a string is passed,
the validator is invoked with no extra arguments. If a tuple is
passed, the validator will be invoked with the extra arguments.
desc (str): Optional parameter description.
"""
|
python
|
{
"resource": ""
}
|
q274938
|
AnnotatedMetadata.typed_returnvalue
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274939
|
AnnotatedMetadata.custom_returnvalue
|
test
|
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.
|
python
|
{
"resource": ""
}
|
q274940
|
AnnotatedMetadata.match_shortname
|
test
|
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 list of filled positional arguments that will be
removed from consideration.
Returns:
str: The full matching parameter name
"""
filled_count = 0
if filled_args is not None:
filled_count = len(filled_args)
|
python
|
{
"resource": ""
}
|
q274941
|
AnnotatedMetadata.param_type
|
test
|
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.
"""
|
python
|
{
"resource": ""
}
|
q274942
|
AnnotatedMetadata.signature
|
test
|
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 override the default name given
in the function signature.
Returns:
str: The formatted function signature
"""
self._ensure_loaded()
if name is None:
name = self.name
|
python
|
{
"resource": ""
}
|
q274943
|
AnnotatedMetadata.format_returnvalue
|
test
|
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 not return data
"""
self._ensure_loaded()
if not self.return_info.is_data:
return None
# If the return value is typed, use the type_system to format it
|
python
|
{
"resource": ""
}
|
q274944
|
AnnotatedMetadata.convert_positional_argument
|
test
|
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.
"""
# For bound methods, skip self
if self._has_self:
|
python
|
{
"resource": ""
}
|
q274945
|
AnnotatedMetadata.check_spec
|
test
|
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.
Returns:
dict: A dictionary of argument name to argument value, pulled from either
the value passed or the default value if no argument is passed.
Raises:
ArgumentError: If a positional or keyword argument does not fit in the spec.
ValidationError: If an argument is passed twice.
"""
if kwargs is None:
kwargs = {}
if self.varargs is not None or self.kwargs is not None:
raise InternalError("check_spec cannot be called on a function that takes *args or **kwargs")
missing = object()
arg_vals = [missing]*len(self.arg_names)
kw_indices = {name: i for i, name in enumerate(self.arg_names)}
for i, arg in enumerate(pos_args):
if i >= len(arg_vals):
raise ArgumentError("Too many positional arguments, first excessive argument=%s" % str(arg))
arg_vals[i] = arg
for arg, val in kwargs.items():
index = kw_indices.get(arg)
|
python
|
{
"resource": ""
}
|
q274946
|
AnnotatedMetadata.convert_argument
|
test
|
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: The converted value.
"""
self._ensure_loaded()
type_name = self.param_type(arg_name)
if type_name is None:
return arg_value
val = typeinfo.type_system.convert_to_type(arg_value, type_name)
validators = self.annotated_params[arg_name].validators
|
python
|
{
"resource": ""
}
|
q274947
|
KeyValueException.format
|
test
|
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, class name and
key value parameters passed to create the exception.
"""
if exclude_class:
msg = self.msg
else:
|
python
|
{
"resource": ""
}
|
q274948
|
KeyValueException.to_dict
|
test
|
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
"""
|
python
|
{
"resource": ""
}
|
q274949
|
_check_and_execute
|
test
|
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_positional_argument(i, arg)
convargs.append(val)
convkw = {}
for key, val in kwargs:
convkw[key]
|
python
|
{
"resource": ""
}
|
q274950
|
_parse_validators
|
test
|
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 valids:
if isinstance(val, str):
args = []
elif len(val) > 1:
args =
|
python
|
{
"resource": ""
}
|
q274951
|
find_all
|
test
|
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 container to search for annotated functions.
Returns:
dict: A dict with all of the found functions in it.
"""
if isinstance(container, dict):
names = container.keys()
else:
names = dir(container)
built_context = BasicContext()
for name in names:
# Ignore _ and __ names
if name.startswith('_'):
continue
if isinstance(container, dict):
obj = container[name]
else:
obj = getattr(container, name)
# Check if this is an annotated object that should be included. Check the type of
# annotated to avoid issues with module imports where someone did from annotate import *
|
python
|
{
"resource": ""
}
|
q274952
|
context_from_module
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274953
|
get_help
|
test
|
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:
str: The formatted help text
"""
help_text = ""
if isinstance(func, dict):
name = context_name(func)
help_text = "\n" + name + "\n\n"
doc = inspect.getdoc(func)
if doc is not None:
doc = inspect.cleandoc(doc)
|
python
|
{
"resource": ""
}
|
q274954
|
param
|
test
|
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 conversions and validation.
Args:
name (string): name of the parameter
type_name (string): The name of a type that will be known to the type
system by the time this function is called for the first time. Types
are lazily loaded so it is not required that the type resolve correctly
at the point in the module where this function is defined.
validators (list(string or tuple)): A list of validators. Each validator
can be defined either using a string name or as an n-tuple of the form
[name, \\*extra_args]. The name is used to look up a validator function
of the form validate_name, which is called on the parameters value to
determine if it is valid. If extra_args are given, they are passed
as extra arguments to the validator function, which is called as:
|
python
|
{
"resource": ""
}
|
q274955
|
returns
|
test
|
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 parameter for specifying that this function
returns data.
|
python
|
{
"resource": ""
}
|
q274956
|
return_type
|
test
|
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.
|
python
|
{
"resource": ""
}
|
q274957
|
context
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274958
|
docannotate
|
test
|
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 make
sure there are no errors in the docstring.
"""
|
python
|
{
"resource": ""
}
|
q274959
|
annotated
|
test
|
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 we wish to mark as callable
from the command line.
name (str): Optional string that will override the function's
built-in name.
"""
if hasattr(func, 'metadata'):
if
|
python
|
{
"resource": ""
}
|
q274960
|
short_description
|
test
|
def short_description(func):
"""
Given an object with a docstring, return the first line of the docstring
|
python
|
{
"resource": ""
}
|
q274961
|
load
|
test
|
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('.')[0:-1]))
except ImportError as e:
if 'No module named' not in str(e):
|
python
|
{
"resource": ""
}
|
q274962
|
install
|
test
|
def install():
"""
Register tasks with cron.
"""
load()
tab = crontab.CronTab(user=True)
|
python
|
{
"resource": ""
}
|
q274963
|
printtasks
|
test
|
def printtasks():
"""
Print the tasks that would be installed in the
crontab, for debugging purposes.
|
python
|
{
"resource": ""
}
|
q274964
|
uninstall
|
test
|
def uninstall():
"""
Uninstall tasks from cron.
"""
tab = crontab.CronTab(user=True)
count = len(list(tab.find_comment(KRONOS_BREADCRUMB)))
|
python
|
{
"resource": ""
}
|
q274965
|
ProjectHandlerFactory.create
|
test
|
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.search(uri)
if not matches:
|
python
|
{
"resource": ""
}
|
q274966
|
ProjectHandlerBase.load
|
test
|
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 configs from %s", path)
for filename in os.listdir(path):
filename_parts = os.path.splitext(filename)
if filename_parts[1][1:] != PROJECT_CONFIG_EXTENSION:
continue
name = filename_parts[0]
|
python
|
{
"resource": ""
}
|
q274967
|
ProjectHandlerBase.save
|
test
|
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 %s", base_path)
for name, data in list(projects.items()):
|
python
|
{
"resource": ""
}
|
q274968
|
define_singleton
|
test
|
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): the singleton object type
cls_args (dict): optional dict for createing cls
"""
instance_name = "__{}".format(name)
|
python
|
{
"resource": ""
}
|
q274969
|
Project.get_dependent_projects
|
test
|
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 list(self.dependencies.items()):
try:
prj = self.vcp.projects[name]
except KeyError:
|
python
|
{
"resource": ""
}
|
q274970
|
post_process
|
test
|
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, **kwargs)
project_command = args[0]
|
python
|
{
"resource": ""
}
|
q274971
|
ProjectCommand.__init
|
test
|
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 status. ez rossz
"""
|
python
|
{
"resource": ""
}
|
q274972
|
setitem
|
test
|
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
setitem(obj, key, obj[key]) == obj
This function is used by many lenses (particularly GetitemLens) to
set items on states even when those states do not ordinarily support
``setitem``. This function is designed to have a similar signature
as python's built-in ``setitem`` except that it returns a new object
that has the item set rather than mutating the object in place.
It's what enables the ``lens[some_key]`` functionality.
The corresponding method call for this hook is
|
python
|
{
"resource": ""
}
|
q274973
|
setattr
|
test
|
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:: python
setattr(obj, 'attr', obj.attr) == obj
This function is used by many lenses (particularly GetattrLens) to set
attributes on states even when those states do not ordinarily support
``setattr``. This function is designed to have a similar signature
as python's built-in ``setattr`` except that it returns a new object
that has the attribute set rather than mutating the object in place.
It's what enables the ``lens.some_attribute`` functionality.
The corresponding method call for this hook is
|
python
|
{
"resource": ""
}
|
q274974
|
from_iter
|
test
|
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 the iterable should remain unchanged.
The following equality should hold for your definition:
|
python
|
{
"resource": ""
}
|
q274975
|
UnboundLens.set
|
test
|
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])
|
python
|
{
"resource": ""
}
|
q274976
|
UnboundLens.set_many
|
test
|
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])
|
python
|
{
"resource": ""
}
|
q274977
|
UnboundLens.modify
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q274978
|
collect_args
|
test
|
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)
'''
|
python
|
{
"resource": ""
}
|
q274979
|
LensLike.func
|
test
|
def func(self, f, state):
'''Intended to be overridden by subclasses. Raises
NotImplementedError.'''
message
|
python
|
{
"resource": ""
}
|
q274980
|
LensLike.apply
|
test
|
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
also provide a `pure`
|
python
|
{
"resource": ""
}
|
q274981
|
LensLike.view
|
test
|
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 to get any foci.
For technical reasons, this method requires there to be at least
one foci at the end of the view. It will raise ValueError when
there is none.
'''
if
|
python
|
{
"resource": ""
}
|
q274982
|
LensLike.to_list_of
|
test
|
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):
|
python
|
{
"resource": ""
}
|
q274983
|
LensLike.over
|
test
|
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
|
python
|
{
"resource": ""
}
|
q274984
|
LensLike.set
|
test
|
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):
|
python
|
{
"resource": ""
}
|
q274985
|
LensLike.iterate
|
test
|
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):
|
python
|
{
"resource": ""
}
|
q274986
|
LensLike.kind
|
test
|
def kind(self):
'''Returns a class representing the 'kind' of optic.'''
optics = [
Equality,
Isomorphism,
Prism,
Review,
Lens,
Traversal,
Getter,
Setter,
|
python
|
{
"resource": ""
}
|
q274987
|
main
|
test
|
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()
|
python
|
{
"resource": ""
}
|
q274988
|
Vector.step_towards
|
test
|
def step_towards(self, other):
'''returns the vector moved one step in the direction of the
other, potentially diagonally.'''
return self + Vector(
(
|
python
|
{
"resource": ""
}
|
q274989
|
GameState.handle_input
|
test
|
def handle_input(self, input):
'''Takes a single character string as input and alters the game
state according to that input. Mostly, this means moving the
player around. Returns a new game state and boolean indicating
whether the input had an effect on the state.'''
dirs = {
'h': (-1, 0),
'j': (0, 1),
'k': (0, -1),
'l': (1, 0),
'y': (-1, -1),
'u': (1, -1),
'n': (1, 1),
'b': (-1, 1),
}
if input in dirs:
new_self = (lens.player + dirs[input])(self)
if not new_self.player.inside():
return self, False
|
python
|
{
"resource": ""
}
|
q274990
|
GameState.advance_robots
|
test
|
def advance_robots(self):
'''Produces a new game state in which the robots have advanced
towards the player by one step. Handles the robots crashing into
one another too.'''
# move the robots towards the player
self = lens.robots.Each().call_step_towards(self.player)(self)
# robots in the same place are crashes
|
python
|
{
"resource": ""
}
|
q274991
|
GameState.end_game
|
test
|
def end_game(self, message=''):
'''Returns a completed game state object, setting an optional
message to display after the game is over.'''
|
python
|
{
"resource": ""
}
|
q274992
|
player_move
|
test
|
def player_move(board):
'''Shows the board to the player on the console and asks them to
make a move.'''
print(board, end='\n\n')
x, y =
|
python
|
{
"resource": ""
}
|
q274993
|
play
|
test
|
def play():
'Play a game of naughts and crosses against the computer.'
ai = {'X': player_move, 'O': random_move}
board = Board()
while not board.winner:
|
python
|
{
"resource": ""
}
|
q274994
|
Board.make_move
|
test
|
def make_move(self, x, y):
'''Return a board with a cell filled in by the current player. If
the cell is already occupied then return the board unchanged.'''
if self.board[y][x]
|
python
|
{
"resource": ""
}
|
q274995
|
Board.winner
|
test
|
def winner(self):
'The winner of this board if one exists.'
for potential_win in self._potential_wins():
if potential_win == tuple('XXX'):
return Outcome.win_for_crosses
elif potential_win == tuple('OOO'):
|
python
|
{
"resource": ""
}
|
q274996
|
Board._potential_wins
|
test
|
def _potential_wins(self):
'''Generates all the combinations of board positions that need
to be checked for a win.'''
|
python
|
{
"resource": ""
}
|
q274997
|
S3Pipeline.process_item
|
test
|
def process_item(self, item, spider):
"""
Process single item. Add item to items and then upload to S3 if size of items
>= max_chunk_size.
"""
self.items.append(item)
|
python
|
{
"resource": ""
}
|
q274998
|
S3Pipeline.open_spider
|
test
|
def open_spider(self, spider):
"""
Callback function when spider is open.
"""
# Store timestamp to replace {time} in S3PIPELINE_URL
|
python
|
{
"resource": ""
}
|
q274999
|
S3Pipeline._upload_chunk
|
test
|
def _upload_chunk(self, spider):
"""
Do upload items to S3.
"""
if not self.items:
return # Do nothing when items is empty.
f = self._make_fileobj()
# Build object key by replacing variables in object key template.
object_key = self.object_key_template.format(**self._get_uri_params(spider))
try:
self.s3.upload_fileobj(f, self.bucket_name, object_key)
except ClientError:
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.