code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def has_arithmetic_operator(line):
"""Return True if line contains any arithmetic operators."""
for operator in pycodestyle.ARITHMETIC_OP:
if operator in line:
return True
return False | Return True if line contains any arithmetic operators. | has_arithmetic_operator | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def count_unbalanced_brackets(line):
"""Return number of unmatched open/close brackets."""
count = 0
for opening, closing in ['()', '[]', '{}']:
count += abs(line.count(opening) - line.count(closing))
return count | Return number of unmatched open/close brackets. | count_unbalanced_brackets | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def split_at_offsets(line, offsets):
"""Split line at offsets.
Return list of strings.
"""
result = []
previous_offset = 0
current_offset = 0
for current_offset in sorted(offsets):
if current_offset < len(line) and previous_offset != current_offset:
result.append(line[... | Split line at offsets.
Return list of strings.
| split_at_offsets | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def match_file(filename, exclude):
"""Return True if file is okay for modifying/recursing."""
base_name = os.path.basename(filename)
if base_name.startswith('.'):
return False
for pattern in exclude:
if fnmatch.fnmatch(base_name, pattern):
return False
if fnmatch.fn... | Return True if file is okay for modifying/recursing. | match_file | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def _fix_file(parameters):
"""Helper function for optionally running fix_file() in parallel."""
if parameters[1].verbose:
print('[file:{}]'.format(parameters[0]), file=sys.stderr)
try:
return fix_file(*parameters)
except IOError as error:
print(str(error), file=sys.stderr)
... | Helper function for optionally running fix_file() in parallel. | _fix_file | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def fix_multiple_files(filenames, options, output=None):
"""Fix list of files.
Optionally fix files recursively.
"""
results = []
filenames = find_files(filenames, options.recursive, options.exclude)
if options.jobs > 1:
import multiprocessing
pool = multiprocessing.Pool(option... | Fix list of files.
Optionally fix files recursively.
| fix_multiple_files | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def is_python_file(filename):
"""Return True if filename is Python file."""
if filename.endswith('.py'):
return True
try:
with open_with_encoding(
filename,
limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f:
text = f.read(MAX_PYTHON_FILE_DETE... | Return True if filename is Python file. | is_python_file | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def is_probably_part_of_multiline(line):
"""Return True if line is likely part of a multiline string.
When multiline strings are involved, pep8 reports the error as being
at the start of the multiline string, which doesn't work for us.
"""
return (
'"""' in line or
"'''" in line or... | Return True if line is likely part of a multiline string.
When multiline strings are involved, pep8 reports the error as being
at the start of the multiline string, which doesn't work for us.
| is_probably_part_of_multiline | python | hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/master/autopep8.py | MIT |
def run(filename, command, max_line_length=79,
ignore='', check_ignore='', verbose=False,
comparison_function=None,
aggressive=0, experimental=False, line_range=None, random_range=False,
pycodestyle=True):
"""Run autopep8 on file at filename.
Return True on success.
"""
... | Run autopep8 on file at filename.
Return True on success.
| run | python | hhatto/autopep8 | test/acid.py | https://github.com/hhatto/autopep8/blob/master/test/acid.py | MIT |
def process_args():
"""Return processed arguments (options and positional arguments)."""
compare_bytecode_ignore = 'E71,E721,W'
parser = argparse.ArgumentParser()
parser.add_argument(
'--command',
default='{} {}'.format(sys.executable,
os.path.join(ROOT_PA... | Return processed arguments (options and positional arguments). | process_args | python | hhatto/autopep8 | test/acid.py | https://github.com/hhatto/autopep8/blob/master/test/acid.py | MIT |
def check(paths, args):
"""Run recursively run autopep8 on directory of files.
Return False if the fix results in broken syntax.
"""
if paths:
dir_paths = paths
else:
dir_paths = [path for path in sys.path
if os.path.isdir(path)]
filenames = dir_paths
... | Run recursively run autopep8 on directory of files.
Return False if the fix results in broken syntax.
| check | python | hhatto/autopep8 | test/acid.py | https://github.com/hhatto/autopep8/blob/master/test/acid.py | MIT |
def latest_packages(last_hours):
"""Return names of latest released packages on PyPI."""
process = subprocess.Popen(
['yolk', '--latest-releases={hours}'.format(hours=last_hours)],
stdout=subprocess.PIPE)
for line in process.communicate()[0].decode('utf-8').split('\n'):
if line:
... | Return names of latest released packages on PyPI. | latest_packages | python | hhatto/autopep8 | test/acid_pypi.py | https://github.com/hhatto/autopep8/blob/master/test/acid_pypi.py | MIT |
def get(self):
""" Returns a simple HTML form for login """
if self.user:
self.redirect_to('home', id=self.user_id)
params = {}
return self.render_template('boilerplate_login.html', **params) | Returns a simple HTML form for login | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def post(self):
"""
username: Get the username from POST dict
password: Get the password from POST dict
"""
if not self.form.validate():
return self.get()
username = self.form.username.data.lower()
try:
if utils.is_email_valid(username):
... |
username: Get the username from POST dict
password: Get the password from POST dict
| post | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def get(self):
""" Returns a simple HTML form for create a new user """
if self.user:
self.redirect_to('home', id=self.user_id)
params = {}
return self.render_template('boilerplate_register.html', **params) | Returns a simple HTML form for create a new user | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def get(self):
""" Returns a simple HTML for contact form """
if self.user:
user_info = models.User.get_by_id(long(self.user_id))
if user_info.name or user_info.last_name:
self.form.name.data = user_info.name + " " + user_info.last_name
if user_info.e... | Returns a simple HTML for contact form | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def get(self):
""" Returns a simple HTML form for edit profile """
params = {}
if self.user:
user_info = models.User.get_by_id(long(self.user_id))
self.form.username.data = user_info.username
self.form.name.data = user_info.name
self.form.last_nam... | Returns a simple HTML form for edit profile | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def get(self):
""" Returns a simple HTML form for editing password """
params = {}
return self.render_template('boilerplate_edit_password.html', **params) | Returns a simple HTML form for editing password | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def get(self):
""" Returns a simple HTML form for edit email """
params = {}
if self.user:
user_info = models.User.get_by_id(long(self.user_id))
self.form.new_email.data = user_info.email
return self.render_template('boilerplate_edit_email.html', **params) | Returns a simple HTML form for edit email | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def get(self):
""" Returns a simple HTML form for home """
params = {}
return self.render_template('boilerplate_home.html', **params) | Returns a simple HTML form for home | get | python | hhatto/autopep8 | test/e101_example.py | https://github.com/hhatto/autopep8/blob/master/test/e101_example.py | MIT |
def ismethoddescriptor(object):
"""Return true if the object is a method descriptor.
But not if ismethod() or isclass() or isfunction() are true.
This is new in Python 2.2, and, for example, is true of int.__add__.
An object passing this test has a __get__ attribute but not a __set__
attribute, bu... | Return true if the object is a method descriptor.
But not if ismethod() or isclass() or isfunction() are true.
This is new in Python 2.2, and, for example, is true of int.__add__.
An object passing this test has a __get__ attribute but not a __set__
attribute, but beyond that the set of attributes var... | ismethoddescriptor | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def isdatadescriptor(object):
"""Return true if the object is a data descriptor.
Data descriptors have both a __get__ and a __set__ attribute. Examples are
properties (defined in Python) and getsets and members (defined in C).
Typically, data descriptors will also have __name__ and __doc__ attributes
... | Return true if the object is a data descriptor.
Data descriptors have both a __get__ and a __set__ attribute. Examples are
properties (defined in Python) and getsets and members (defined in C).
Typically, data descriptors will also have __name__ and __doc__ attributes
(properties, getsets, and members... | isdatadescriptor | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def isgeneratorfunction(object):
"""Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See help(isfunction) for attributes listing."""
return bool((isfunction(object) or ismethod(object)) and
object.__code__... | Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See help(isfunction) for attributes listing. | isgeneratorfunction | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object)) | Return true if the object is any kind of function or method. | isroutine | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate."""
if isclass(object):
mro = (object,) + getmro(object)
else:
mro = ()
results = []
processed = set()
... | Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate. | getmembers | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def classify_class_attrs(cls):
"""Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via cla... | Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via classmethod()
'static meth... | classify_class_attrs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def unwrap(func, *, stop=None):
"""Get the object wrapped by *func*.
Follows the chain of :attr:`__wrapped__` attributes returning the last
object in the chain.
*stop* is an optional callback accepting an object in the wrapper chain
as its sole argument that allows the unwrapping to be terminated earl... | Get the object wrapped by *func*.
Follows the chain of :attr:`__wrapped__` attributes returning the last
object in the chain.
*stop* is an optional callback accepting an object in the wrapper chain
as its sole argument that allows the unwrapping to be terminated early if
the callback returns a true val... | unwrap | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def indentsize(line):
"""Return the indent size, in spaces, at the start of a line of text."""
expline = line.expandtabs()
return len(expline) - len(expline.lstrip()) | Return the indent size, in spaces, at the start of a line of text. | indentsize | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getdoc(object):
"""Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed."""
try:
doc = object.__doc__
... | Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed. | getdoc | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def cleandoc(doc):
"""Clean up indentation from docstrings.
Any whitespace that can be uniformly removed from the second line
onwards is removed."""
try:
lines = doc.expandtabs().split('\n')
except UnicodeError:
return None
else:
# Find minimum indentation of any non-bla... | Clean up indentation from docstrings.
Any whitespace that can be uniformly removed from the second line
onwards is removed. | cleandoc | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getfile(object):
"""Work out which source or compiled file an object was defined in."""
if ismodule(object):
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('{!r} is a built-in module'.format(object))
if isclass(object):
if hasattr(object, '__mo... | Work out which source or compiled file an object was defined in. | getfile | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getmodulename(path):
"""Return the module name for a given file, or None."""
fname = os.path.basename(path)
# Check for paths that look like an actual module file
suffixes = [(-len(suffix), suffix)
for suffix in importlib.machinery.all_suffixes()]
suffixes.sort() # try longes... | Return the module name for a given file, or None. | getmodulename | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename = getfile(object)
all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
all_bytecode_suffixes += importlib.mac... | Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
| getsourcefile | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getabsfile(object, _filename=None):
"""Return an absolute path to the source or compiled file for an object.
The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible."""
if _filename is None:
_filename = getsourcefile(object) or getfile(... | Return an absolute path to the source or compiled file for an object.
The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible. | getabsfile | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getmodule(object, _filename=None):
"""Return the module an object was defined in, or None if not found."""
if ismodule(object):
return object
if hasattr(object, '__module__'):
return sys.modules.get(object.__module__)
# Try the filename to modulename cache
if _filename is not Non... | Return the module an object was defined in, or None if not found. | getmodule | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def findsource(object):
"""Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. ... | Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An OSError
is raised if th... | findsource | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getcomments(object):
"""Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
"""
try:
lines, lnum = findsource(object)
except (OSError, TypeError):
return None
if ismodule(object):
# Look for a comment block a... | Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
| getcomments | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getblock(lines):
"""Extract the block of code at the top of the given list of lines."""
blockfinder = BlockFinder()
try:
tokens = tokenize.generate_tokens(iter(lines).__next__)
for _token in tokens:
blockfinder.tokeneater(*_token)
except (EndOfBlock, IndentationError):
... | Extract the block of code at the top of the given list of lines. | getblock | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates whe... | Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file ... | getsourcelines | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getclasstree(classes, unique=False):
"""Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes.... | Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes. If the 'unique'
argument is true, exactly ... | getclasstree | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None."""
args, ... | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None. | getargs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def _getfullargs(co):
"""Get information about the arguments accepted by a code object.
Four things are returned: (args, varargs, kwonlyargs, varkw), where
'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
and 'varkw' are the names of the * and ** arguments or None."""
if not isco... | Get information about the arguments accepted by a code object.
Four things are returned: (args, varargs, kwonlyargs, varkw), where
'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
and 'varkw' are the names of the * and ** arguments or None. | _getfullargs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names.
'args' will include keyword-only argument names.
'varargs' and 'varkw' are the names of the * and ** arg... | Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names.
'args' will include keyword-only argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults... | getargspec | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getfullargspec(func):
"""Get the names and default values of a callable object's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** ... | Get the names and default values of a callable object's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults'... | getfullargspec | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getargvalues(frame):
"""Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dicti... | Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame. | getargvalues | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def formatargspec(args, varargs=None, varkw=None, defaults=None,
kwonlyargs=(), kwonlydefaults={}, annotations={},
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda valu... | Format an argument spec from the values returned by getargspec
or getfullargspec.
The first seven arguments are (args, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, annotations). The other five arguments
are the corresponding optional formatting functions that are called to
turn names and ... | formatargspec | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value)):
"""Format an argument spec from the 4 values ret... | Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional functio... | formatargvalues | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getcallargs(*func_and_positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
func = func_and_posi... | Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'. | getcallargs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
"""
... |
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
| getclosurevars | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
Th... | Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
The optional second argument specifies the nu... | getframeinfo | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getouterframes(frame, context=1):
"""Get a list of records for a frame and all higher (calling) frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context."""
framelist = []
while frame:
framelist.append((f... | Get a list of records for a frame and all higher (calling) frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context. | getouterframes | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getinnerframes(tb, context=1):
"""Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context."""
framelist = []
while tb:
framelist.append((tb.tb_... | Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context. | getinnerframes | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getattr_static(obj, attr, default=_sentinel):
"""Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
... | Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like d... | getattr_static | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getgeneratorstate(generator):
"""Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has com... | Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed.
| getgeneratorstate | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getgeneratorlocals(generator):
"""
Get the mapping of generator local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values."""
if not isgenerator(generator):
raise TypeError("'{!r}' is not a Python generator".format(g... |
Get the mapping of generator local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values. | getgeneratorlocals | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def _signature_strip_non_python_syntax(signature):
"""
Takes a signature in Argument Clinic's extended signature format.
Returns a tuple of three things:
* that signature re-rendered in standard Python syntax,
* the index of the "self" parameter (generally 0), or None if
the function doe... |
Takes a signature in Argument Clinic's extended signature format.
Returns a tuple of three things:
* that signature re-rendered in standard Python syntax,
* the index of the "self" parameter (generally 0), or None if
the function does not have a "self" parameter, and
* the index of th... | _signature_strip_non_python_syntax | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def replace(self, *, name=_void, kind=_void,
annotation=_void, default=_void):
'''Creates a customized copy of the Parameter.'''
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotati... | Creates a customized copy of the Parameter. | replace | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def __init__(self, parameters=None, *, return_annotation=_empty,
__validate_parameters__=True):
'''Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
'''
if parameters is None:
params = Ordered... | Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
| __init__ | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def from_function(cls, func):
'''Constructs Signature for the given python function'''
is_duck_function = False
if not isfunction(func):
if _signature_is_functionlike(func):
is_duck_function = True
else:
# If it's not a pure Python functio... | Constructs Signature for the given python function | from_function | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def replace(self, *, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
... | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
| replace | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def _main():
""" Logic for inspecting an object given at command line """
import argparse
import importlib
parser = argparse.ArgumentParser()
parser.add_argument(
'object',
help="The object to be analysed. "
"It supports the 'module:qualname' syntax")
parser.add_a... | Logic for inspecting an object given at command line | _main | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def test_readlines_from_file_with_bad_encoding(self):
"""Bad encoding should not cause an exception."""
self.assertEqual(
['# -*- coding: zlatin-1 -*-\n'],
autopep8.readlines_from_file(
os.path.join(ROOT_DIR, 'test', 'bad_encoding.py'))) | Bad encoding should not cause an exception. | test_readlines_from_file_with_bad_encoding | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_fix_code_byte_string(self):
"""This feature is here for friendliness to Python 2."""
self.assertEqual(
'print(123)\n',
autopep8.fix_code(b'print( 123 )\n')) | This feature is here for friendliness to Python 2. | test_fix_code_byte_string | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e231_should_only_do_ws_comma_once(self):
"""If we don't check appropriately, we end up doing ws_comma multiple
times and skipping all other fixes."""
line = """\
print( 1 )
foo[0,:]
bar[zap[0][0]:zig[0][0],:]
"""
fixed = """\
print(1)
foo[0, :]
bar[zap[0][0]:zig[0][0], :]
"""
... | If we don't check appropriately, we end up doing ws_comma multiple
times and skipping all other fixes. | test_e231_should_only_do_ws_comma_once | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e501_with_aggressive_and_massive_number_of_logical_lines(self):
"""We do not care about results here.
We just want to know that it doesn't take a ridiculous amount of
time. Caching is currently required to avoid repeately trying
the same line.
"""
line = """\
#... | We do not care about results here.
We just want to know that it doesn't take a ridiculous amount of
time. Caching is currently required to avoid repeately trying
the same line.
| test_e501_with_aggressive_and_massive_number_of_logical_lines | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e501_avoid_breaking_at_opening_slice(self):
"""Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw[
'abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
"""
... | Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw[
'abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
| test_e501_avoid_breaking_at_opening_slice | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e501_avoid_breaking_at_multi_level_slice(self):
"""Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'][
'def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
"""
... | Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'][
'def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
| test_e501_avoid_breaking_at_multi_level_slice | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_execfile_in_lambda_should_not_be_modified(self):
"""Modifying this to the exec() form is invalid in Python 2."""
line = 'lambda: execfile("foo.py")\n'
with autopep8_context(line, options=['--aggressive']) as result:
self.assertEqual(line, result) | Modifying this to the exec() form is invalid in Python 2. | test_execfile_in_lambda_should_not_be_modified | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def check(expected_filename, input_filename, aggressive):
"""Test and compare output.
Return True on success.
"""
got = autopep8.fix_file(
input_filename,
options=autopep8.parse_args([''] + aggressive * ['--aggressive']))
try:
with autopep8.open_with_encoding(expected_file... | Test and compare output.
Return True on success.
| check | python | hhatto/autopep8 | test/test_suite.py | https://github.com/hhatto/autopep8/blob/master/test/test_suite.py | MIT |
def run(filename, aggressive):
"""Test against a specific file.
Return True on success.
Expected output should have the same base filename, but live in an "out"
directory:
foo/bar.py
foo/out/bar.py
Failed output will go to:
foo/out/bar.py.err
"""
return check(
... | Test against a specific file.
Return True on success.
Expected output should have the same base filename, but live in an "out"
directory:
foo/bar.py
foo/out/bar.py
Failed output will go to:
foo/out/bar.py.err
| run | python | hhatto/autopep8 | test/test_suite.py | https://github.com/hhatto/autopep8/blob/master/test/test_suite.py | MIT |
def __eq__(self, other):
'''Vectors can be checked for equality.
Uses epsilon floating comparison; tiny differences are still equal.
'''
for i in range(len(self._v)):
if not equal(self._v[i], other._v[i]):
return False
return True | Vectors can be checked for equality.
Uses epsilon floating comparison; tiny differences are still equal.
| __eq__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __cmp__(self, other):
'''Vectors can be compared, returning -1,0,+1.
Elements are compared in order, using epsilon floating comparison.
'''
for i in range(len(self._v)):
if not equal(self._v[i], other._v[i]):
if self._v[i] > other._v[i]: return 1
... | Vectors can be compared, returning -1,0,+1.
Elements are compared in order, using epsilon floating comparison.
| __cmp__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __neg__(self):
'''The inverse of a vector is a negative in all elements.'''
v = V(self)
for i in range(len(v._v)):
v[i] = -v[i]
v._l = self._l
return v | The inverse of a vector is a negative in all elements. | __neg__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __nonzero__(self):
'''A vector is nonzero if any of its elements are nonzero.'''
for i in range(len(self._v)):
if self._v[i]: return True
return False | A vector is nonzero if any of its elements are nonzero. | __nonzero__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def random(cls, order=3):
'''Returns a unit vector in a random direction.'''
# distribution is not without bias, need to use polar coords?
v = V(range(order))
v._l = None
short = True
while short:
for i in range(order):
v._v[i] = 2.0*random.ran... | Returns a unit vector in a random direction. | random | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __iadd__(self, other):
'''Vectors can be added to each other, or a scalar added to them.'''
if isinstance(other, V):
if len(other._v) != len(self._v):
raise ValueError, 'mismatched dimensions'
for i in range(len(self._v)):
self._v[i] += other._... | Vectors can be added to each other, or a scalar added to them. | __iadd__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __isub__(self, other):
'''Vectors can be subtracted, or a scalar subtracted from them.'''
if isinstance(other, V):
if len(other._v) != len(self._v):
raise ValueError, 'mismatched dimensions'
for i in range(len(self._v)):
self._v[i] -= other._v[... | Vectors can be subtracted, or a scalar subtracted from them. | __isub__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __imul__(self, other):
'''Vectors can be multipled by a scalar. Two 3d vectors can cross.'''
if isinstance(other, V):
self._v = self.cross(other)._v
else:
for i in range(len(self._v)):
self._v[i] *= other
self._l = None
return self | Vectors can be multipled by a scalar. Two 3d vectors can cross. | __imul__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __idiv__(self, other):
'''Vectors can be divided by scalars; each element is divided.'''
other = 1.0 / other
for i in range(len(self._v)):
self._v[i] *= other
self._l = None
return self | Vectors can be divided by scalars; each element is divided. | __idiv__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def cross(self, other):
'''Find the vector cross product between two 3d vectors.'''
if len(self._v) != 3 or len(other._v) != 3:
raise ValueError, 'cross multiplication only for 3d vectors'
p, q = self._v, other._v
r = [ p[1] * q[2] - p[2] * q[1],
p[2] * q[0] - p... | Find the vector cross product between two 3d vectors. | cross | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def dot(self, other):
'''Find the scalar dot product between this vector and another.'''
s = 0
for i in range(len(self._v)):
s += self._v[i] * other._v[i]
return s | Find the scalar dot product between this vector and another. | dot | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def magnitude(self, value=None):
'''Find the magnitude (spatial length) of this vector.
With a value, return a vector with same direction but of given length.
'''
mag = self.__mag()
if value is None: return mag
if zero(mag):
raise ValueError, 'Zero-magnitude v... | Find the magnitude (spatial length) of this vector.
With a value, return a vector with same direction but of given length.
| magnitude | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def order(self, order):
'''Remove elements from the end, or extend with new elements.'''
order = int(order)
if order < 1:
raise ValueError, 'cannot reduce a vector to zero elements'
v = V(self)
while order < len(v._v):
v._v.pop()
while order > len(... | Remove elements from the end, or extend with new elements. | order | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def conjugate(self):
'''The conjugate of a quaternion has its X, Y and Z negated.'''
twin = Q(self)
for i in range(3):
twin._v[i] = -twin._v[i]
twin._l = twin._l
return twin | The conjugate of a quaternion has its X, Y and Z negated. | conjugate | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def inverse(self):
'''The quaternion inverse is the conjugate with reciprocal W.'''
twin = self.conjugate()
if twin._v[3] != 1.0:
twin._v[3] = 1.0 / twin._v[3]
twin._l = None
return twin | The quaternion inverse is the conjugate with reciprocal W. | inverse | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def rotate(cls, axis, theta):
'''Prepare a quaternion that represents a rotation on a given axis.'''
if isinstance(axis, str):
if axis in ('x','X'): axis = V.X
elif axis in ('y','Y'): axis = V.Y
elif axis in ('z','Z'): axis = V.Z
axis = axis.normalize()
... | Prepare a quaternion that represents a rotation on a given axis. | rotate | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __init__(self, *args):
'''Constructs a new 4x4 matrix.
If no arguments are given, an identity matrix is constructed.
Any combination of V vectors, tuples, lists or scalars may be given,
but taken together in order, they must have 16 number values total.
'''
# no args ... | Constructs a new 4x4 matrix.
If no arguments are given, an identity matrix is constructed.
Any combination of V vectors, tuples, lists or scalars may be given,
but taken together in order, they must have 16 number values total.
| __init__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __str__(self):
'''Returns a multiple-line string representation of the matrix.'''
# prettier on multiple lines
n = self.__class__.__name__
ns = ' '*len(n)
t = n+'('+', '.join([ repr(self._v[i]) for i in 0,1,2,3 ])+',\n'
t += ns+' '+', '.join([ repr(self._v[i]) for i i... | Returns a multiple-line string representation of the matrix. | __str__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __setitem__(self, rc, value):
'''Injects a single element into the matrix.
May index 0-15, or with tuples of (row,column) 0-3 each.
Indexing goes across first, so m[3] is m[0,3] and m[7] is m[1,3].
'''
if not isinstance(rc, tuple): return V.__getitem__(self, rc)
self.... | Injects a single element into the matrix.
May index 0-15, or with tuples of (row,column) 0-3 each.
Indexing goes across first, so m[3] is m[0,3] and m[7] is m[1,3].
| __setitem__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def row(self, r, v=None):
'''Returns or replaces a vector representing a row of the matrix.
Rows are counted 0-3. If given, new vector must be four numbers.
'''
if r < 0 or r > 3: raise IndexError, 'row index out of range'
if v is None: return V(self._v[r*4:(r+1)*4])
e = ... | Returns or replaces a vector representing a row of the matrix.
Rows are counted 0-3. If given, new vector must be four numbers.
| row | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def col(self, c, v=None):
'''Returns or replaces a vector representing a column of the matrix.
Columns are counted 0-3. If given, new vector must be four numbers.
'''
if c < 0 or c > 3: raise IndexError, 'column index out of range'
if v is None: return V([ self._v[c+4*i] for i in... | Returns or replaces a vector representing a column of the matrix.
Columns are counted 0-3. If given, new vector must be four numbers.
| col | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def translation(self):
'''Extracts the translation component from this matrix.'''
(a,b,c,d,
e,f,g,h,
i,j,k,l,
m,n,o,p) = self._v
return V(m,n,o) | Extracts the translation component from this matrix. | translation | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def rotation(self):
'''Extracts Euler angles of rotation from this matrix.
This attempts to find alternate rotations in case of gimbal lock,
but all of the usual problems with Euler angles apply here.
All Euler angles are in radians.
'''
(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) ... | Extracts Euler angles of rotation from this matrix.
This attempts to find alternate rotations in case of gimbal lock,
but all of the usual problems with Euler angles apply here.
All Euler angles are in radians.
| rotation | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def angle(a, b):
'''Find the angle (scalar value in radians) between two 3d vectors.'''
a = a.normalize()
b = b.normalize()
if a == b: return 0.0
return math.acos(a.dot(b)) | Find the angle (scalar value in radians) between two 3d vectors. | angle | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def track(v):
'''Find the track (direction in positive radians) of a 2d vector.
E.g., track(V(1,0)) == 0 radians; track(V(0,1) == math.pi/2 radians;
track(V(-1,0)) == math.pi radians; and track(V(0,-1) is math.pi*3/2.
'''
t = math.atan2(v[1], v[0])
if t < 0:
return t + 2.*math.pi
return t | Find the track (direction in positive radians) of a 2d vector.
E.g., track(V(1,0)) == 0 radians; track(V(0,1) == math.pi/2 radians;
track(V(-1,0)) == math.pi radians; and track(V(0,-1) is math.pi*3/2.
| track | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def quangle(a, b):
'''Find a quaternion that rotates one 3d vector to parallel another.'''
x = a.cross(b)
w = a.magnitude() * b.magnitude() + a.dot(b)
return Q(x[0], x[1], x[2], w) | Find a quaternion that rotates one 3d vector to parallel another. | quangle | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def dsquared(one, two):
'''Find the square of the distance between two points.'''
# working with squared distances is common to avoid slow sqrt() calls
m = 0
for i in range(len(one._v)):
d = one._v[i] - two._v[i]
m += d * d
return m | Find the square of the distance between two points. | dsquared | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def nearest(point, neighbors):
'''Find the nearest neighbor point to a given point.'''
best = None
for other in neighbors:
d = dsquared(point, other)
if best is None or d < best[1]:
best = (other, d)
return best[0] | Find the nearest neighbor point to a given point. | nearest | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def farthest(point, neighbors):
'''Find the farthest neighbor point to a given point.'''
best = None
for other in neighbors:
d = dsquared(point, other)
if best is None or d > best[1]:
best = (other, d)
return best[0] | Find the farthest neighbor point to a given point. | farthest | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def test_keys(self):
"""areas.json - All regions are accounted for."""
expected = set([
u'Norrbotten',
u'V\xe4sterbotten',
]) | areas.json - All regions are accounted for. | test_keys | python | hhatto/autopep8 | test/suite/E10.py | https://github.com/hhatto/autopep8/blob/master/test/suite/E10.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.