INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
search a node of parse tree to find variable names that need a either global or nonlocal statements added.
def find_globals_and_nonlocals(node, globs, nonlocals, code, version): """search a node of parse tree to find variable names that need a either 'global' or 'nonlocal' statements added.""" for n in node: if isinstance(n, SyntaxTree): globs, nonlocals = find_globals_and_nonlocals(n, globs,...
List of expressions may be nested in groups of 32 and 1024 items. flatten that out and return the list
def flatten_list(node): """ List of expressions may be nested in groups of 32 and 1024 items. flatten that out and return the list """ flat_elems = [] for elem in node: if elem == 'expr1024': for subelem in elem: assert subelem == 'expr32' for ...
takes anything and attempts to return a py2 string or py3 bytes. this is typically used when creating command + arguments to be executed via os. exec *
def encode_to_py3bytes_or_py2str(s): """ takes anything and attempts to return a py2 string or py3 bytes. this is typically used when creating command + arguments to be executed via os.exec* """ fallback_encoding = "utf8" if IS_PY3: # if we're already bytes, do nothing if isinstan...
takes an exception name like:
def get_exc_from_name(name): """ takes an exception name, like: ErrorReturnCode_1 SignalException_9 SignalException_SIGHUP and returns the corresponding exception. this is primarily used for importing exceptions from sh into user code, for instance, to capture those exceptions...
takes a exit code or negative signal number and produces an exception that corresponds to that return code. positive return codes yield ErrorReturnCode exception negative return codes yield SignalException
def get_rc_exc(rc): """ takes a exit code or negative signal number and produces an exception that corresponds to that return code. positive return codes yield ErrorReturnCode exception, negative return codes yield SignalException we also cache the generated exception so that only one signal of that t...
takes a program name or full path plus an optional collection of search paths and returns the full path of the requested executable. if paths is specified it is the entire list of search paths and the PATH env is not used at all. otherwise PATH env is used to look for the program
def which(program, paths=None): """ takes a program name or full path, plus an optional collection of search paths, and returns the full path of the requested executable. if paths is specified, it is the entire list of search paths, and the PATH env is not used at all. otherwise, PATH env is used to l...
checks if an object ( like a file - like object ) is a tty.
def ob_is_tty(ob): """ checks if an object (like a file-like object) is a tty. """ fileno = get_fileno(ob) is_tty = False if fileno: is_tty = os.isatty(fileno) return is_tty
a validator to prevent a user from saying that they want custom buffering when they re using an in/ out object that will be os. dup d to the process and has its own buffering. an example is a pipe or a tty. it doesn t make sense to tell them to have a custom buffering since the os controls this.
def bufsize_validator(kwargs): """ a validator to prevent a user from saying that they want custom buffering when they're using an in/out object that will be os.dup'd to the process, and has its own buffering. an example is a pipe or a tty. it doesn't make sense to tell them to have a custom buffering...
takes args and kwargs as they were passed into the command instance being executed with __call__ and compose them into a flat list that will eventually be fed into exec. example:
def compile_args(args, kwargs, sep, prefix): """ takes args and kwargs, as they were passed into the command instance being executed with __call__, and compose them into a flat list that will eventually be fed into exec. example: with this call: sh.ls("-l", "/tmp", color="never") this fu...
take our keyword arguments and a separator and compose the list of flat long ( and short ) arguments. example
def aggregate_keywords(keywords, sep, prefix, raw=False): """ take our keyword arguments, and a separator, and compose the list of flat long (and short) arguments. example {'color': 'never', 't': True, 'something': True} with sep '=' becomes ['--color=never', '-t', '--something'] th...
set the terminal size of a tty file descriptor. borrowed logic from pexpect. py
def setwinsize(fd, rows_cols): """ set the terminal size of a tty file descriptor. borrowed logic from pexpect.py """ rows, cols = rows_cols TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) s = struct.pack('HHHH', rows, cols, 0, 0) fcntl.ioctl(fd, TIOCSWINSZ, s)
here we re constructing a closure for our streamreader callback. this is used in the case that we pass a callback into _out or _err meaning we want to our callback to handle each bit of output
def construct_streamreader_callback(process, handler): """ here we're constructing a closure for our streamreader callback. this is used in the case that we pass a callback into _out or _err, meaning we want to our callback to handle each bit of output we construct the closure based on how many argume...
this should only ever be called once for each child process
def handle_process_exit_code(exit_code): """ this should only ever be called once for each child process """ # if we exited from a signal, let our exit code reflect that if os.WIFSIGNALED(exit_code): exit_code = -os.WTERMSIG(exit_code) # otherwise just give us a normal exit code elif os.WIFE...
a helper for making system calls immune to EINTR
def no_interrupt(syscall, *args, **kwargs): """ a helper for making system calls immune to EINTR """ ret = None while True: try: ret = syscall(*args, **kwargs) except OSError as e: if e.errno == errno.EINTR: continue else: ...
this is run in a separate thread. it writes into our process s stdin ( a streamwriter ) and waits the process to end AND everything that can be written to be written
def input_thread(log, stdin, is_alive, quit, close_before_term): """ this is run in a separate thread. it writes into our process's stdin (a streamwriter) and waits the process to end AND everything that can be written to be written """ done = False closed = False alive = True poller = Pol...
handles the timeout logic
def background_thread(timeout_fn, timeout_event, handle_exit_code, is_alive, quit): """ handles the timeout logic """ # if there's a timeout event, loop if timeout_event: while not quit.is_set(): timed_out = event_wait(timeout_event, 0.1) if timed_out: ...
this function is run in a separate thread. it reads from the process s stdout stream ( a streamreader ) and waits for it to claim that its done
def output_thread(log, stdout, stderr, timeout_event, is_alive, quit, stop_output_event): """ this function is run in a separate thread. it reads from the process's stdout stream (a streamreader), and waits for it to claim that its done """ poller = Poller() if stdout is not None: ...
given some kind of input object return a function that knows how to read chunks of that input object. each reader function should return a chunk and raise a DoneReadingForever exception or return None when there s no more data to read
def determine_how_to_read_input(input_obj): """ given some kind of input object, return a function that knows how to read chunks of that input object. each reader function should return a chunk and raise a DoneReadingForever exception, or return None, when there's no more data to read NOTE: th...
return an iterator that returns a chunk of a string every time it is called. notice that even though bufsize_type might be line buffered we re not doing any line buffering here. that s because our StreamBufferer handles all buffering. we just need to return a reasonable - sized chunk.
def get_iter_string_reader(stdin): """ return an iterator that returns a chunk of a string every time it is called. notice that even though bufsize_type might be line buffered, we're not doing any line buffering here. that's because our StreamBufferer handles all buffering. we just need to return a r...
pushd changes the actual working directory for the duration of the context unlike the _cwd arg this will work with other built - ins such as sh. glob correctly
def pushd(path): """ pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other built-ins such as sh.glob correctly """ orig_path = os.getcwd() os.chdir(path) try: yield finally: os.chdir(orig_path)
allows us to temporarily override all the special keyword parameters in a with context
def args(**kwargs): """ allows us to temporarily override all the special keyword parameters in a with context """ kwargs_str = ",".join(["%s=%r" % (k,v) for k,v in kwargs.items()]) raise DeprecationWarning(""" sh.args() has been deprecated because it was never thread safe. use the following instead...
a nicer version of sudo that uses getpass to ask for a password or allows the first argument to be a string password
def sudo(orig): # pragma: no cover """ a nicer version of sudo that uses getpass to ask for a password, or allows the first argument to be a string password """ prompt = "[sudo] password for %s: " % getpass.getuser() def stdin(): pw = getpass.getpass(prompt=prompt) + "\n" yield pw ...
registers our fancy importer that can let us import from a module name like:
def register_importer(): """ registers our fancy importer that can let us import from a module name, like: import sh tmp = sh() from tmp import ls """ def test(importer): return importer.__class__.__name__ == ModuleImporterFromVariables.__name__ already_registered =...
waits for the running command to finish. this is called on all running commands eventually except for ones that run in the background
def wait(self): """ waits for the running command to finish. this is called on all running commands, eventually, except for ones that run in the background """ if not self._process_completed: self._process_completed = True exit_code = self.process.wait() ...
here we determine if we had an exception or an error code that we weren t expecting to see. if we did we create and raise an exception
def handle_command_exit_code(self, code): """ here we determine if we had an exception, or an error code that we weren't expecting to see. if we did, we create and raise an exception """ ca = self.call_args exc_class = get_exc_exit_code_would_raise(code, ca["ok_code"], ...
allow us to iterate over the output of our command
def next(self): """ allow us to iterate over the output of our command """ if self._stopped_iteration: raise StopIteration() # we do this because if get blocks, we can't catch a KeyboardInterrupt # so the slight timeout allows for that. while True: try: ...
takes kwargs that were passed to a command s __call__ and extracts out the special keyword arguments we return a tuple of special keyword args and kwargs that will go to the execd command
def _extract_call_args(kwargs): """ takes kwargs that were passed to a command's __call__ and extracts out the special keyword arguments, we return a tuple of special keyword args, and kwargs that will go to the execd command """ kwargs = kwargs.copy() call_args = {} for...
polls if our child process has completed without blocking. this method has side - effects such as setting our exit_code if we happen to see our child exit while this is running
def is_alive(self): """ polls if our child process has completed, without blocking. this method has side-effects, such as setting our exit_code, if we happen to see our child exit while this is running """ if self.exit_code is not None: return False, self.exit_code ...
waits for the process to complete handles the exit code
def wait(self): """ waits for the process to complete, handles the exit code """ self.log.debug("acquiring wait lock to wait for completion") # using the lock in a with-context blocks, which is what we want if # we're running wait() with self._wait_lock: self.log.deb...
attempt to get a chunk of data to write to our child process s stdin then write it. the return value answers the questions are we done writing forever?
def write(self): """ attempt to get a chunk of data to write to our child process's stdin, then write it. the return value answers the questions "are we done writing forever?" """ # get_chunk may sometimes return bytes, and sometimes return strings # because of the nature of th...
mod_fullname doubles as the name of the VARIABLE holding our new sh context. for example:
def find_module(self, mod_fullname, path=None): """ mod_fullname doubles as the name of the VARIABLE holding our new sh context. for example: derp = sh() from derp import ls here, mod_fullname will be "derp". keep that in mind as we go throug the rest of this ...
a simplified json_normalize
def nested_to_record(ds, prefix="", sep=".", level=0): """a simplified json_normalize converts a nested dict into a flat dict ("record"), unlike json_normalize, it does not attempt to extract a subset of the data. Parameters ---------- ds : dict or list of dicts prefix: the prefix, optiona...
Normalize semi - structured JSON data into a flat table
def json_normalize(data, record_path=None, meta=None, meta_prefix=None, record_prefix=None, errors='raise', sep='.'): """ "Normalize" semi-structured JSON data into a flat table Parameters ---------- data : dict or list of ...
Convert a NumPy/ pandas type to its corresponding json_table.
def as_json_table_type(x): """ Convert a NumPy / pandas type to its corresponding json_table. Parameters ---------- x : array or dtype Returns ------- t : str the Table Schema data types Notes ----- This table shows the relationship between NumPy / pandas dtypes, ...
Sets index names to index for regular or level_x for Multi
def set_default_names(data): """Sets index names to 'index' for regular, or 'level_x' for Multi""" if all(name is not None for name in data.index.names): return data data = data.copy() if data.index.nlevels > 1: names = [name if name is not None else 'level_{}'.format(i) ...
Convert a JSON string to pandas object
def read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False): """ Convert a JSON string to pandas object Parameter...
try to parse a ndarray like into a column by inferring dtype
def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True): """ try to parse a ndarray like into a column by inferring dtype """ # don't try to coerce, unless a force conversion if use_dtypes: if self.dtype is False: return...
try to parse a ndarray like into a date column try to coerce object in epoch/ iso formats and integer/ float in epcoh formats return a boolean if parsing was successful
def _try_convert_to_date(self, data): """ try to parse a ndarray like into a date column try to coerce object in epoch/iso formats and integer/float in epcoh formats, return a boolean if parsing was successful """ # no conversion on empty if not len(data): ...
Set the default qgrid options. The options that you can set here are the same ones that you can pass into QgridWidget constructor with the exception of the df option for which a default value wouldn t be particularly useful ( since the purpose of qgrid is to display a DataFrame ).
def set_defaults(show_toolbar=None, precision=None, grid_options=None, column_options=None): """ Set the default qgrid options. The options that you can set here are the same ones that you can pass into ``QgridWidget`` constructor, with the exception o...
Automatically use qgrid to display all DataFrames and/ or Series instances in the notebook.
def enable(dataframe=True, series=True): """ Automatically use qgrid to display all DataFrames and/or Series instances in the notebook. Parameters ---------- dataframe : bool Whether to automatically use qgrid to display DataFrames instances. series : bool Whether to automat...
Renders a DataFrame or Series as an interactive qgrid represented by an instance of the QgridWidget class. The QgridWidget instance is constructed using the options passed in to this function. The data_frame argument to this function is used as the df kwarg in call to the QgridWidget constructor and the rest of the par...
def show_grid(data_frame, show_toolbar=None, precision=None, grid_options=None, column_options=None, column_definitions=None, row_edit_callback=None): """ Renders a DataFrame or Series as an interactive qgrid, represented by ...
decorator for building minified js/ css prior to another command
def js_prerelease(command, strict=False): """decorator for building minified js/css prior to another command""" class DecoratedCommand(command): def run(self): jsdeps = self.distribution.get_command_obj('jsdeps') if not is_repo and all(exists(t) for t in jsdeps.targets): ...
return list of available themes
def get_themes(): """ return list of available themes """ styles_dir = os.path.join(package_dir, 'styles') themes = [os.path.basename(theme).replace('.less', '') for theme in glob('{0}/*.less'.format(styles_dir))] return themes
Install theme to jupyter_customcss with specified font fontsize md layout and toolbar pref
def install_theme(theme=None, monofont=None, monosize=11, nbfont=None, nbfontsize=13, tcfont=None, tcfontsize=13, dffontsize=93, outfontsize=85, mathfontsize=100, ...
checks jupyter_config_dir () for text file containing theme name ( updated whenever user installs a new theme )
def infer_theme(): """ checks jupyter_config_dir() for text file containing theme name (updated whenever user installs a new theme) """ themes = [os.path.basename(theme).replace('.less', '') for theme in glob('{0}/*.less'.format(styles_dir))] if os.path.exists(theme_name_file): ...
main function for styling matplotlib according to theme
def style(theme=None, context='paper', grid=True, gridlines=u'-', ticks=False, spines=True, fscale=1.2, figsize=(8., 7.)): """ main function for styling matplotlib according to theme ::Arguments:: theme (str): 'oceans16', 'grade3', 'chesterish', 'onedork', 'monokai', 'solarizedl', 'solarizedd'. If ...
This code has been modified from seaborn. rcmod. set_style ():: Arguments:: rcdict ( str ): dict of context properties ( filled by set_context () ) theme ( str ): name of theme to use when setting color properties grid ( bool ): turns off axis grid if False ( default: True ) ticks ( bool ): removes x y axis ticks if Tr...
def set_style(rcdict, theme=None, grid=True, gridlines=u'-', ticks=False, spines=True): """ This code has been modified from seaborn.rcmod.set_style() ::Arguments:: rcdict (str): dict of "context" properties (filled by set_context()) theme (str): name of theme to use when setting color prope...
Most of this code has been copied/ modified from seaborn. rcmod. plotting_context ():: Arguments:: context ( str ): paper notebook talk or poster fscale ( float ): font - size scalar applied to axes ticks legend labels etc.
def set_context(context='paper', fscale=1., figsize=(8., 7.)): """ Most of this code has been copied/modified from seaborn.rcmod.plotting_context() ::Arguments:: context (str): 'paper', 'notebook', 'talk', or 'poster' fscale (float): font-size scalar applied to axes ticks, legend, labels, et...
manually set the default figure size of plots:: Arguments:: x ( float ): x - axis size y ( float ): y - axis size aspect ( float ): aspect ratio scalar
def figsize(x=8, y=7., aspect=1.): """ manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (float): y-axis size aspect (float): aspect ratio scalar """ # update rcparams with adjusted figsize params mpl.rcParams.update({'figure.figsize': (x*as...
read - in theme style info and populate styleMap ( dict of with mpl. rcParams ) and clist ( list of hex codes passed to color cylcler ):: Arguments:: theme ( str ): theme name:: Returns:: styleMap ( dict ): dict containing theme - specific colors for figure properties clist ( list ): list of colors to replace mpl s def...
def get_theme_style(theme): """ read-in theme style info and populate styleMap (dict of with mpl.rcParams) and clist (list of hex codes passed to color cylcler) ::Arguments:: theme (str): theme name ::Returns:: styleMap (dict): dict containing theme-specific colors for figure propert...
full reset of matplotlib default style and colors
def reset(): """ full reset of matplotlib default style and colors """ colors = [(0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, .75, 0.), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.)] for code, color in zip("bgrmyck", colors): rgb = mpl.colors.colorConverter.to_rgb(color) mp...
write less - compiled css file to jupyter_customcss in jupyter_dir
def less_to_css(style_less): """ write less-compiled css file to jupyter_customcss in jupyter_dir """ with fileOpen(tempfile, 'w') as f: f.write(style_less) os.chdir(package_dir) style_css = lesscpy.compile(tempfile) style_css += '\n\n' return style_css
Parent function for setting notebook text/ md and codecell font - properties
def set_font_properties(style_less, nbfont=None, tcfont=None, monofont=None, monosize=11, tcfontsize=13, nbfontsize=13, prfontsize=95, ...
Copy all custom fonts to ~/. jupyter/ custom/ fonts/ and write import statements to style_less
def import_fonts(style_less, fontname, font_subdir): """Copy all custom fonts to ~/.jupyter/custom/fonts/ and write import statements to style_less """ ftype_dict = {'woff2': 'woff2', 'woff': 'woff', 'ttf': 'truetype', 'otf': 'opentype', ...
Set general layout and style properties of text and code cells
def style_layout(style_less, theme='grade3', cursorwidth=2, cursorcolor='default', cellwidth='980', lineheight=170, margins='auto', vimext=False, toolbar=False, nbname...
Toggle main notebook toolbar ( e. g. buttons ) filename and kernel logo.
def toggle_settings( toolbar=False, nbname=False, hideprompt=False, kernellogo=False): """Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo.""" toggle = '' if toolbar: toggle += 'div#maintoolbar {margin-left: 8px !important;}\n' toggle += '.toolbar.containe...
Write mathjax settings set math fontsize
def set_mathjax_style(style_css, mathfontsize): """Write mathjax settings, set math fontsize """ jax_style = """<script> MathJax.Hub.Config({ "HTML-CSS": { /*preferredFont: "TeX",*/ /*availableFonts: ["TeX", "STIX"],*/ styles: { scale: %d, ...
Add style and compatibility with vim notebook extension
def set_vim_style(theme): """Add style and compatibility with vim notebook extension""" vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding') if not os.path.isdir(vim_jupyter_nbext): os.makedirs(vim_jupyter_nbext) vim_less = '@import "styles{}";\n'.format(''.join([os.sep, theme])) ...
Remove custom. css and custom fonts
def reset_default(verbose=False): """Remove custom.css and custom fonts""" paths = [jupyter_custom, jupyter_nbext] for fpath in paths: custom = '{0}{1}{2}.css'.format(fpath, os.sep, 'custom') try: os.remove(custom) except Exception: pass try: dele...
Set theme from within notebook
def set_nb_theme(name): """Set theme from within notebook """ from IPython.core.display import HTML styles_dir = os.path.join(package_dir, 'styles/compiled/') css_path = glob('{0}/{1}.css'.format(styles_dir, name))[0] customcss = open(css_path, "r").read() return HTML(''.join(['<style> ', custo...
Return split readme.
def split_readme(readme_path, before_key, after_key, options_key, end_key): """Return split readme.""" with open(readme_path) as readme_file: readme = readme_file.read() top, rest = readme.split(before_key) before, rest = rest.split(after_key) _, rest = rest.split(options_key) _, bottom...
Return help output.
def help_message(): """Return help output.""" parser = autopep8.create_parser() string_io = io.StringIO() parser.print_help(string_io) # Undo home directory expansion. return string_io.getvalue().replace(os.path.expanduser('~'), '~')
Check code.
def check(source): """Check code.""" compile(source, '<string>', 'exec', dont_inherit=True) reporter = pyflakes.reporter.Reporter(sys.stderr, sys.stderr) pyflakes.api.check(source, filename='<string>', reporter=reporter)
Override pycodestyle s function to provide indentation information.
def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa): """Override pycodestyle's function to provide indentation information.""" first_row = tokens[0][2][0] nrows = 1 + tokens[-1][2][0] - first_row if noqa or nrows == 1: return ...
workaround get pointing out position by W605.
def get_w605_position(tokens): """workaround get pointing out position by W605.""" # TODO: When this PR(*) change is released, use pos of pycodestyle # *: https://github.com/PyCQA/pycodestyle/pull/747 valid = [ '\n', '\\', '\'', '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', '0', '1', '2', '3',...
return import or from keyword position
def get_module_imports_on_top_of_file(source, import_line_index): """return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function(): """ def is_string_literal(line): if line[0] in 'uUbB': line = line[1:] if lin...
Break up long line and return result.
def get_fixed_long_line(target, previous_line, original, indent_word=' ', max_line_length=79, aggressive=False, experimental=False, verbose=False): """Break up long line and return result. Do this by generating multiple reformatted candidates and then rank...
Return single line based on logical line input.
def join_logical_line(logical_line): """Return single line based on logical line input.""" indentation = _get_indentation(logical_line) return indentation + untokenize_without_newlines( generate_tokens(logical_line.lstrip())) + '\n'
Return source code based on tokens.
def untokenize_without_newlines(tokens): """Return source code based on tokens.""" text = '' last_row = 0 last_column = -1 for t in tokens: token_string = t[1] (start_row, start_column) = t[2] (end_row, end_column) = t[3] if start_row > last_row: last_co...
Return the logical line corresponding to the result.
def _get_logical(source_lines, result, logical_start, logical_end): """Return the logical line corresponding to the result. Assumes input is already E702-clean. """ row = result['line'] - 1 col = result['column'] - 1 ls = None le = None for i in range(0, len(logical_start), 1): ...
Return True if code is similar.
def code_almost_equal(a, b): """Return True if code is similar. Ignore whitespace when comparing specific line. """ split_a = split_and_strip_non_empty_lines(a) split_b = split_and_strip_non_empty_lines(b) if len(split_a) != len(split_b): return False for (index, _) in enumerate(...
Fix various deprecated code ( via lib2to3 ).
def fix_2to3(source, aggressive=True, select=None, ignore=None, filename='', where='global', verbose=False): """Fix various deprecated code (via lib2to3).""" if not aggressive: return source select = select or [] ignore = ignore or [] return refactor(source, ...
Return type of newline used in source.
def find_newline(source): """Return type of newline used in source. Input is a list of lines. """ assert not isinstance(source, unicode) counter = collections.defaultdict(int) for line in source: if line.endswith(CRLF): counter[CRLF] += 1 elif line.endswith(CR): ...
Return indentation type.
def _get_indentword(source): """Return indentation type.""" indent_word = ' ' # Default in case source has no indentation try: for t in generate_tokens(source): if t[0] == token.INDENT: indent_word = t[1] break except (SyntaxError, tokenize.TokenEr...
Return text of unified diff between old and new.
def get_diff_text(old, new, filename): """Return text of unified diff between old and new.""" newline = '\n' diff = difflib.unified_diff( old, new, 'original/' + filename, 'fixed/' + filename, lineterm=newline) text = '' for line in diff: text += line ...
Separate line at OPERATOR.
def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=False, experimental=False, previous_line=''): """Separate line at OPERATOR. Multiple candidates will be yielded. """ for candidate in _shorten_line(tokens=tokens, ...
Separate line at OPERATOR.
def _shorten_line(tokens, source, indentation, indent_word, aggressive=False, previous_line=''): """Separate line at OPERATOR. The input is expected to be free of newlines except for inside multiline strings and at the end. Multiple candidates will be yielded. """ for (token...
Parse a high - level container such as a list tuple etc.
def _parse_container(tokens, index, for_or_if=None): """Parse a high-level container, such as a list, tuple, etc.""" # Store the opening bracket. items = [Atom(Token(*tokens[index]))] index += 1 num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) if ...
Parse the tokens.
def _parse_tokens(tokens): """Parse the tokens. This converts the tokens into a form where we can manipulate them more easily. """ index = 0 parsed_tokens = [] num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) assert tok.token_type != tok...
Reflow the lines so that it looks nice.
def _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line): """Reflow the lines so that it looks nice.""" if unicode(parsed_tokens[0]) == 'def': # A function definition gets indented a bit more. continued_indent = indentation + ' ' * 2 * DEFAULT_INDEN...
Shorten the line taking its length into account.
def _shorten_line_at_tokens_new(tokens, source, indentation, max_line_length): """Shorten the line taking its length into account. The input is expected to be free of newlines except for inside multiline strings and at the end. """ # Yield the original source so to ...
Separate line by breaking at tokens in key_token_strings.
def _shorten_line_at_tokens(tokens, source, indentation, indent_word, key_token_strings, aggressive): """Separate line by breaking at tokens in key_token_strings. The input is expected to be free of newlines except for inside multiline strings and at the end. """ offset...
Yield tokens and offsets.
def token_offsets(tokens): """Yield tokens and offsets.""" end_offset = 0 previous_end_row = 0 previous_end_column = 0 for t in tokens: token_type = t[0] token_string = t[1] (start_row, start_column) = t[2] (end_row, end_column) = t[3] # Account for the white...
Execute pycodestyle via python method calls.
def _execute_pep8(pep8_options, source): """Execute pycodestyle via python method calls.""" class QuietReport(pycodestyle.BaseReport): """Version of checker that does not print.""" def __init__(self, options): super(QuietReport, self).__init__(options) self.__full_error...
Return list of ( lineno indentlevel ) pairs.
def _reindent_stats(tokens): """Return list of (lineno, indentlevel) pairs. One for each stmt and comment line. indentlevel is -1 for comment lines, as a signal that tokenize doesn't know what to do about them; indeed, they're our headache! """ find_stmt = 1 # Next token begins a fresh stmt? ...
Return number of leading spaces in line.
def _leading_space_count(line): """Return number of leading spaces in line.""" i = 0 while i < len(line) and line[i] == ' ': i += 1 return i
Use lib2to3 to refactor the source.
def refactor_with_2to3(source_text, fixer_names, filename=''): """Use lib2to3 to refactor the source. Return the refactored source code. """ from lib2to3.refactor import RefactoringTool fixers = ['lib2to3.fixes.fix_' + name for name in fixer_names] tool = RefactoringTool(fixer_names=fixers, ex...
Return True if syntax is okay.
def check_syntax(code): """Return True if syntax is okay.""" try: return compile(code, '<string>', 'exec', dont_inherit=True) except (SyntaxError, TypeError, ValueError): return False
Filter out spurious reports from pycodestyle.
def filter_results(source, results, aggressive): """Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712). """ non_docstring_string_line_numbers = multiline_string_lines( source, include_docstrings=False) all_string_line_numbers = ...
Return line numbers that are within multiline strings.
def multiline_string_lines(source, include_docstrings=False): """Return line numbers that are within multiline strings. The line numbers are indexed at 1. Docstrings are ignored. """ line_numbers = set() previous_token_type = '' try: for t in generate_tokens(source): t...
Return line numbers of comments that are likely code.
def commented_out_code_lines(source): """Return line numbers of comments that are likely code. Commented-out code is bad practice, but modifying it just adds even more clutter. """ line_numbers = [] try: for t in generate_tokens(source): token_type = t[0] token_...
Return trimmed or split long comment line.
def shorten_comment(line, max_line_length, last_comment=False): """Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text. """ assert len(line) > max_line_len...
Return fixed source code.
def fix_code(source, options=None, encoding=None, apply_config=False): """Return fixed source code. "encoding" will be used to decode "source" if it is a byte string. """ options = _get_options(options, apply_config) if not isinstance(source, unicode): source = source.decode(encoding or g...
Return parsed options.
def _get_options(raw_options, apply_config): """Return parsed options.""" if not raw_options: return parse_args([''], apply_config=apply_config) if isinstance(raw_options, dict): options = parse_args([''], apply_config=apply_config) for name, value in raw_options.items(): ...
Return fixed source code.
def fix_lines(source_lines, options, filename=''): """Return fixed source code.""" # Transform everything to line feed. Then change them back to original # before returning fixed source code. original_newline = find_newline(source_lines) tmp_source = ''.join(normalize_line_endings(source_lines, '\n'...
Yield multiple ( code function ) tuples.
def global_fixes(): """Yield multiple (code, function) tuples.""" for function in list(globals().values()): if inspect.isfunction(function): arguments = _get_parameters(function) if arguments[:1] != ['source']: continue code = extract_code_from_functi...
Return code handled by function.
def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__) if not code: return None try: int(code[1:]) except ValueError: return None ...
Return command - line parser.
def create_parser(): """Return command-line parser.""" parser = argparse.ArgumentParser(description=docstring_summary(__doc__), prog='autopep8') parser.add_argument('--version', action='version', version='%(prog)s {} ({})'.format( ...
Parse command - line options.
def parse_args(arguments, apply_config=False): """Parse command-line options.""" parser = create_parser() args = parser.parse_args(arguments) if not args.files and not args.list_fixes: parser.error('incorrect number of arguments') args.files = [decode_filename(name) for name in args.files]...
Read both user configuration and local configuration.
def read_config(args, parser): """Read both user configuration and local configuration.""" try: from configparser import ConfigParser as SafeConfigParser from configparser import Error except ImportError: from ConfigParser import SafeConfigParser from ConfigParser import Erro...