partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | find_globals_and_nonlocals | search a node of parse tree to find variable names that need a
either 'global' or 'nonlocal' statements added. | uncompyle6/semantics/helper.py | 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,... | 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,... | [
"search",
"a",
"node",
"of",
"parse",
"tree",
"to",
"find",
"variable",
"names",
"that",
"need",
"a",
"either",
"global",
"or",
"nonlocal",
"statements",
"added",
"."
] | rocky/python-uncompyle6 | python | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/helper.py#L30-L45 | [
"def",
"find_globals_and_nonlocals",
"(",
"node",
",",
"globs",
",",
"nonlocals",
",",
"code",
",",
"version",
")",
":",
"for",
"n",
"in",
"node",
":",
"if",
"isinstance",
"(",
"n",
",",
"SyntaxTree",
")",
":",
"globs",
",",
"nonlocals",
"=",
"find_globa... | c5d7944e657f0ad05a0e2edd34e1acb27001abc0 |
train | flatten_list | List of expressions may be nested in groups of 32 and 1024
items. flatten that out and return the list | uncompyle6/semantics/helper.py | 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 ... | 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 ... | [
"List",
"of",
"expressions",
"may",
"be",
"nested",
"in",
"groups",
"of",
"32",
"and",
"1024",
"items",
".",
"flatten",
"that",
"out",
"and",
"return",
"the",
"list"
] | rocky/python-uncompyle6 | python | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/helper.py#L142-L162 | [
"def",
"flatten_list",
"(",
"node",
")",
":",
"flat_elems",
"=",
"[",
"]",
"for",
"elem",
"in",
"node",
":",
"if",
"elem",
"==",
"'expr1024'",
":",
"for",
"subelem",
"in",
"elem",
":",
"assert",
"subelem",
"==",
"'expr32'",
"for",
"subsubelem",
"in",
"... | c5d7944e657f0ad05a0e2edd34e1acb27001abc0 |
train | encode_to_py3bytes_or_py2str | 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* | sh.py | 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... | 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",
"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",
"*"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L268-L301 | [
"def",
"encode_to_py3bytes_or_py2str",
"(",
"s",
")",
":",
"fallback_encoding",
"=",
"\"utf8\"",
"if",
"IS_PY3",
":",
"# if we're already bytes, do nothing",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"pass",
"else",
":",
"s",
"=",
"str",
"(",
"s",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | get_exc_from_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 | sh.py | 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... | 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",
"an",
"exception",
"name",
"like",
":"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L433-L462 | [
"def",
"get_exc_from_name",
"(",
"name",
")",
":",
"exc",
"=",
"None",
"try",
":",
"return",
"rc_exc_cache",
"[",
"name",
"]",
"except",
"KeyError",
":",
"m",
"=",
"rc_exc_regex",
".",
"match",
"(",
"name",
")",
"if",
"m",
":",
"base",
"=",
"m",
".",... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | get_rc_exc | 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 type
exists, preserving i... | sh.py | 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... | 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",
"exit",
"code",
"or",
"negative",
"signal",
"number",
"and",
"produces",
"an",
"exception",
"that",
"corresponds",
"to",
"that",
"return",
"code",
".",
"positive",
"return",
"codes",
"yield",
"ErrorReturnCode",
"exception",
"negative",
"return",
"c... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L465-L488 | [
"def",
"get_rc_exc",
"(",
"rc",
")",
":",
"try",
":",
"return",
"rc_exc_cache",
"[",
"rc",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"rc",
">",
"0",
":",
"name",
"=",
"\"ErrorReturnCode_%d\"",
"%",
"rc",
"base",
"=",
"ErrorReturnCode",
"else",
":",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | which | 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 | sh.py | 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... | 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... | [
"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... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L522-L560 | [
"def",
"which",
"(",
"program",
",",
"paths",
"=",
"None",
")",
":",
"def",
"is_exe",
"(",
"fpath",
")",
":",
"return",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"fpath",
")",
"and",
"os",
".",
"access",
"(",
"fpath",
",",
"os",
".",
"X_OK",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | ob_is_tty | checks if an object (like a file-like object) is a tty. | sh.py | 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 | 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 | [
"checks",
"if",
"an",
"object",
"(",
"like",
"a",
"file",
"-",
"like",
"object",
")",
"is",
"a",
"tty",
"."
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L997-L1003 | [
"def",
"ob_is_tty",
"(",
"ob",
")",
":",
"fileno",
"=",
"get_fileno",
"(",
"ob",
")",
"is_tty",
"=",
"False",
"if",
"fileno",
":",
"is_tty",
"=",
"os",
".",
"isatty",
"(",
"fileno",
")",
"return",
"is_tty"
] | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | bufsize_validator | 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. | sh.py | 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... | 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... | [
"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"... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1026-L1051 | [
"def",
"bufsize_validator",
"(",
"kwargs",
")",
":",
"invalid",
"=",
"[",
"]",
"in_ob",
"=",
"kwargs",
".",
"get",
"(",
"\"in\"",
",",
"None",
")",
"out_ob",
"=",
"kwargs",
".",
"get",
"(",
"\"out\"",
",",
"None",
")",
"in_buf",
"=",
"kwargs",
".",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | compile_args | 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 function receives
args = ['-l', '/tmp']
... | sh.py | 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... | 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... | [
"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",... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1430-L1468 | [
"def",
"compile_args",
"(",
"args",
",",
"kwargs",
",",
"sep",
",",
"prefix",
")",
":",
"processed_args",
"=",
"[",
"]",
"encode",
"=",
"encode_to_py3bytes_or_py2str",
"# aggregate positional args",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"ar... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | aggregate_keywords | 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']
the `raw` argument indicates whether or not we should leave the argu... | sh.py | 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... | 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... | [
"take",
"our",
"keyword",
"arguments",
"and",
"a",
"separator",
"and",
"compose",
"the",
"list",
"of",
"flat",
"long",
"(",
"and",
"short",
")",
"arguments",
".",
"example"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1471-L1534 | [
"def",
"aggregate_keywords",
"(",
"keywords",
",",
"sep",
",",
"prefix",
",",
"raw",
"=",
"False",
")",
":",
"processed",
"=",
"[",
"]",
"encode",
"=",
"encode_to_py3bytes_or_py2str",
"for",
"k",
",",
"v",
"in",
"keywords",
".",
"items",
"(",
")",
":",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | setwinsize | set the terminal size of a tty file descriptor. borrowed logic
from pexpect.py | sh.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) | 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) | [
"set",
"the",
"terminal",
"size",
"of",
"a",
"tty",
"file",
"descriptor",
".",
"borrowed",
"logic",
"from",
"pexpect",
".",
"py"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1551-L1558 | [
"def",
"setwinsize",
"(",
"fd",
",",
"rows_cols",
")",
":",
"rows",
",",
"cols",
"=",
"rows_cols",
"TIOCSWINSZ",
"=",
"getattr",
"(",
"termios",
",",
"'TIOCSWINSZ'",
",",
"-",
"2146929561",
")",
"s",
"=",
"struct",
".",
"pack",
"(",
"'HHHH'",
",",
"row... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | construct_streamreader_callback | 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 arguments it takes. the reason
for this is to make it as easy as... | sh.py | 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... | 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... | [
"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",
"call... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1560-L1626 | [
"def",
"construct_streamreader_callback",
"(",
"process",
",",
"handler",
")",
":",
"# implied arg refers to the \"self\" that methods will pass in. we need to",
"# account for this implied arg when figuring out what function the user",
"# passed in based on number of args",
"implied_arg",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | handle_process_exit_code | this should only ever be called once for each child process | sh.py | 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... | 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... | [
"this",
"should",
"only",
"ever",
"be",
"called",
"once",
"for",
"each",
"child",
"process"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1646-L1657 | [
"def",
"handle_process_exit_code",
"(",
"exit_code",
")",
":",
"# if we exited from a signal, let our exit code reflect that",
"if",
"os",
".",
"WIFSIGNALED",
"(",
"exit_code",
")",
":",
"exit_code",
"=",
"-",
"os",
".",
"WTERMSIG",
"(",
"exit_code",
")",
"# otherwise... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | no_interrupt | a helper for making system calls immune to EINTR | sh.py | 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:
... | 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:
... | [
"a",
"helper",
"for",
"making",
"system",
"calls",
"immune",
"to",
"EINTR"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1660-L1675 | [
"def",
"no_interrupt",
"(",
"syscall",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"None",
"while",
"True",
":",
"try",
":",
"ret",
"=",
"syscall",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OSError",
"as",
"e... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | input_thread | 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 | sh.py | 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... | 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... | [
"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",
... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2393-L2424 | [
"def",
"input_thread",
"(",
"log",
",",
"stdin",
",",
"is_alive",
",",
"quit",
",",
"close_before_term",
")",
":",
"done",
"=",
"False",
"closed",
"=",
"False",
"alive",
"=",
"True",
"poller",
"=",
"Poller",
"(",
")",
"poller",
".",
"register_write",
"("... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | background_thread | handles the timeout logic | sh.py | 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:
... | 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:
... | [
"handles",
"the",
"timeout",
"logic"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2434-L2459 | [
"def",
"background_thread",
"(",
"timeout_fn",
",",
"timeout_event",
",",
"handle_exit_code",
",",
"is_alive",
",",
"quit",
")",
":",
"# if there's a timeout event, loop ",
"if",
"timeout_event",
":",
"while",
"not",
"quit",
".",
"is_set",
"(",
")",
":",
"timed_ou... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | output_thread | 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 | sh.py | 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:
... | 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:
... | [
"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"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2462-L2510 | [
"def",
"output_thread",
"(",
"log",
",",
"stdout",
",",
"stderr",
",",
"timeout_event",
",",
"is_alive",
",",
"quit",
",",
"stop_output_event",
")",
":",
"poller",
"=",
"Poller",
"(",
")",
"if",
"stdout",
"is",
"not",
"None",
":",
"poller",
".",
"registe... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | determine_how_to_read_input | 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: the function returned does not need to care much about... | sh.py | 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... | 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... | [
"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",
"DoneRea... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2517-L2565 | [
"def",
"determine_how_to_read_input",
"(",
"input_obj",
")",
":",
"get_chunk",
"=",
"None",
"if",
"isinstance",
"(",
"input_obj",
",",
"Queue",
")",
":",
"log_msg",
"=",
"\"queue\"",
"get_chunk",
"=",
"get_queue_chunk_reader",
"(",
"input_obj",
")",
"elif",
"cal... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | get_iter_string_reader | 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. | sh.py | 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... | 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... | [
"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",
... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2596-L2603 | [
"def",
"get_iter_string_reader",
"(",
"stdin",
")",
":",
"bufsize",
"=",
"1024",
"iter_str",
"=",
"(",
"stdin",
"[",
"i",
":",
"i",
"+",
"bufsize",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"stdin",
")",
",",
"bufsize",
")",
")",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | pushd | 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 | sh.py | 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) | 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) | [
"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"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L3087-L3096 | [
"def",
"pushd",
"(",
"path",
")",
":",
"orig_path",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"path",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"orig_path",
")"
] | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | args | allows us to temporarily override all the special keyword parameters in
a with context | sh.py | 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... | 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... | [
"allows",
"us",
"to",
"temporarily",
"override",
"all",
"the",
"special",
"keyword",
"parameters",
"in",
"a",
"with",
"context"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L3100-L3120 | [
"def",
"args",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs_str",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"%s=%r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"]",
")",
"raise",
"DeprecationWarning",... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | sudo | a nicer version of sudo that uses getpass to ask for a password, or
allows the first argument to be a string password | sh.py | 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
... | 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
... | [
"a",
"nicer",
"version",
"of",
"sudo",
"that",
"uses",
"getpass",
"to",
"ask",
"for",
"a",
"password",
"or",
"allows",
"the",
"first",
"argument",
"to",
"be",
"a",
"string",
"password"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L3277-L3300 | [
"def",
"sudo",
"(",
"orig",
")",
":",
"# pragma: no cover",
"prompt",
"=",
"\"[sudo] password for %s: \"",
"%",
"getpass",
".",
"getuser",
"(",
")",
"def",
"stdin",
"(",
")",
":",
"pw",
"=",
"getpass",
".",
"getpass",
"(",
"prompt",
"=",
"prompt",
")",
"... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | register_importer | registers our fancy importer that can let us import from a module name,
like:
import sh
tmp = sh()
from tmp import ls | sh.py | 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 =... | 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 =... | [
"registers",
"our",
"fancy",
"importer",
"that",
"can",
"let",
"us",
"import",
"from",
"a",
"module",
"name",
"like",
":"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L3384-L3403 | [
"def",
"register_importer",
"(",
")",
":",
"def",
"test",
"(",
"importer",
")",
":",
"return",
"importer",
".",
"__class__",
".",
"__name__",
"==",
"ModuleImporterFromVariables",
".",
"__name__",
"already_registered",
"=",
"any",
"(",
"[",
"True",
"for",
"i",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | RunningCommand.wait | waits for the running command to finish. this is called on all
running commands, eventually, except for ones that run in the background | sh.py | 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()
... | 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()
... | [
"waits",
"for",
"the",
"running",
"command",
"to",
"finish",
".",
"this",
"is",
"called",
"on",
"all",
"running",
"commands",
"eventually",
"except",
"for",
"ones",
"that",
"run",
"in",
"the",
"background"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L777-L802 | [
"def",
"wait",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_process_completed",
":",
"self",
".",
"_process_completed",
"=",
"True",
"exit_code",
"=",
"self",
".",
"process",
".",
"wait",
"(",
")",
"if",
"self",
".",
"process",
".",
"timed_out",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | RunningCommand.handle_command_exit_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 | sh.py | 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"],
... | 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"],
... | [
"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"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L805-L815 | [
"def",
"handle_command_exit_code",
"(",
"self",
",",
"code",
")",
":",
"ca",
"=",
"self",
".",
"call_args",
"exc_class",
"=",
"get_exc_exit_code_would_raise",
"(",
"code",
",",
"ca",
"[",
"\"ok_code\"",
"]",
",",
"ca",
"[",
"\"piped\"",
"]",
")",
"if",
"ex... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | RunningCommand.next | allow us to iterate over the output of our command | sh.py | 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:
... | 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:
... | [
"allow",
"us",
"to",
"iterate",
"over",
"the",
"output",
"of",
"our",
"command"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L847-L870 | [
"def",
"next",
"(",
"self",
")",
":",
"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",
":",
... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | Command._extract_call_args | 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 | sh.py | 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... | 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... | [
"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",
... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L1237-L1261 | [
"def",
"_extract_call_args",
"(",
"kwargs",
")",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"call_args",
"=",
"{",
"}",
"for",
"parg",
",",
"default",
"in",
"Command",
".",
"_call_args",
".",
"items",
"(",
")",
":",
"key",
"=",
"\"_\"",
"+"... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | OProc.is_alive | 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 | sh.py | 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
... | 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
... | [
"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",
"thi... | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2284-L2326 | [
"def",
"is_alive",
"(",
"self",
")",
":",
"if",
"self",
".",
"exit_code",
"is",
"not",
"None",
":",
"return",
"False",
",",
"self",
".",
"exit_code",
"# what we're doing here essentially is making sure that the main thread",
"# (or another thread), isn't calling .wait() on ... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | OProc.wait | waits for the process to complete, handles the exit code | sh.py | 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... | 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... | [
"waits",
"for",
"the",
"process",
"to",
"complete",
"handles",
"the",
"exit",
"code"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2346-L2389 | [
"def",
"wait",
"(",
"self",
")",
":",
"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... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | StreamWriter.write | 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?" | sh.py | 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... | 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... | [
"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?"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L2700-L2760 | [
"def",
"write",
"(",
"self",
")",
":",
"# get_chunk may sometimes return bytes, and sometimes return strings",
"# because of the nature of the different types of STDIN objects we",
"# support",
"try",
":",
"chunk",
"=",
"self",
".",
"get_chunk",
"(",
")",
"if",
"chunk",
"is",... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | ModuleImporterFromVariables.find_module | 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 function | sh.py | 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 ... | 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 ... | [
"mod_fullname",
"doubles",
"as",
"the",
"name",
"of",
"the",
"VARIABLE",
"holding",
"our",
"new",
"sh",
"context",
".",
"for",
"example",
":"
] | amoffat/sh | python | https://github.com/amoffat/sh/blob/858adf0c682af4c40e41f34d6926696b7a5d3b12/sh.py#L3422-L3448 | [
"def",
"find_module",
"(",
"self",
",",
"mod_fullname",
",",
"path",
"=",
"None",
")",
":",
"parent_frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"while",
"in_importlib",
"(",
"parent_frame",
")",
":",
"parent_frame",
"=",
"parent_fra... | 858adf0c682af4c40e41f34d6926696b7a5d3b12 |
train | nested_to_record | 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, optional, default: ""
sep : string, default '.'
Nested re... | qgrid/pd_json/normalize.py | 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... | 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... | [
"a",
"simplified",
"json_normalize"
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/normalize.py#L23-L90 | [
"def",
"nested_to_record",
"(",
"ds",
",",
"prefix",
"=",
"\"\"",
",",
"sep",
"=",
"\".\"",
",",
"level",
"=",
"0",
")",
":",
"singleton",
"=",
"False",
"if",
"isinstance",
"(",
"ds",
",",
"dict",
")",
":",
"ds",
"=",
"[",
"ds",
"]",
"singleton",
... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | json_normalize | "Normalize" semi-structured JSON data into a flat table
Parameters
----------
data : dict or list of dicts
Unserialized JSON objects
record_path : string or list of strings, default None
Path in each object to list of records. If not passed, data will be
assumed to be an array o... | qgrid/pd_json/normalize.py | 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 ... | 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 ... | [
"Normalize",
"semi",
"-",
"structured",
"JSON",
"data",
"into",
"a",
"flat",
"table"
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/normalize.py#L93-L265 | [
"def",
"json_normalize",
"(",
"data",
",",
"record_path",
"=",
"None",
",",
"meta",
"=",
"None",
",",
"meta_prefix",
"=",
"None",
",",
"record_prefix",
"=",
"None",
",",
"errors",
"=",
"'raise'",
",",
"sep",
"=",
"'.'",
")",
":",
"def",
"_pull_field",
... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | as_json_table_type | 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,
and Table Schema dtypes.
======... | qgrid/pd_json/table_schema.py | 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,
... | 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,
... | [
"Convert",
"a",
"NumPy",
"/",
"pandas",
"type",
"to",
"its",
"corresponding",
"json_table",
"."
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/table_schema.py#L13-L58 | [
"def",
"as_json_table_type",
"(",
"x",
")",
":",
"if",
"is_integer_dtype",
"(",
"x",
")",
":",
"return",
"'integer'",
"elif",
"is_bool_dtype",
"(",
"x",
")",
":",
"return",
"'boolean'",
"elif",
"is_numeric_dtype",
"(",
"x",
")",
":",
"return",
"'number'",
... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | set_default_names | Sets index names to 'index' for regular, or 'level_x' for Multi | qgrid/pd_json/table_schema.py | 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)
... | 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)
... | [
"Sets",
"index",
"names",
"to",
"index",
"for",
"regular",
"or",
"level_x",
"for",
"Multi"
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/table_schema.py#L61-L73 | [
"def",
"set_default_names",
"(",
"data",
")",
":",
"if",
"all",
"(",
"name",
"is",
"not",
"None",
"for",
"name",
"in",
"data",
".",
"index",
".",
"names",
")",
":",
"return",
"data",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"data",
".",
... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | read_json | Convert a JSON string to pandas object
Parameters
----------
path_or_buf : a valid JSON string or file-like, default: None
The string could be a URL. Valid URL schemes include http, ftp, s3, and
file. For file URLs, a host is expected. For instance, a local file
could be ``file://lo... | qgrid/pd_json/json.py | 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... | 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... | [
"Convert",
"a",
"JSON",
"string",
"to",
"pandas",
"object"
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/json.py#L170-L361 | [
"def",
"read_json",
"(",
"path_or_buf",
"=",
"None",
",",
"orient",
"=",
"None",
",",
"typ",
"=",
"'frame'",
",",
"dtype",
"=",
"True",
",",
"convert_axes",
"=",
"True",
",",
"convert_dates",
"=",
"True",
",",
"keep_default_dates",
"=",
"True",
",",
"num... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | Parser._try_convert_data | try to parse a ndarray like into a column by inferring dtype | qgrid/pd_json/json.py | 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... | 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",
"column",
"by",
"inferring",
"dtype"
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/json.py#L441-L513 | [
"def",
"_try_convert_data",
"(",
"self",
",",
"name",
",",
"data",
",",
"use_dtypes",
"=",
"True",
",",
"convert_dates",
"=",
"True",
")",
":",
"# don't try to coerce, unless a force conversion",
"if",
"use_dtypes",
":",
"if",
"self",
".",
"dtype",
"is",
"False"... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | Parser._try_convert_to_date | 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 | qgrid/pd_json/json.py | 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):
... | 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):
... | [
"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"... | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/pd_json/json.py#L515-L549 | [
"def",
"_try_convert_to_date",
"(",
"self",
",",
"data",
")",
":",
"# no conversion on empty",
"if",
"not",
"len",
"(",
"data",
")",
":",
"return",
"data",
",",
"False",
"new_data",
"=",
"data",
"if",
"new_data",
".",
"dtype",
"==",
"'object'",
":",
"try",... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | set_defaults | 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).
See the docu... | qgrid/grid.py | 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... | 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... | [
"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",
"optio... | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/grid.py#L135-L163 | [
"def",
"set_defaults",
"(",
"show_toolbar",
"=",
"None",
",",
"precision",
"=",
"None",
",",
"grid_options",
"=",
"None",
",",
"column_options",
"=",
"None",
")",
":",
"defaults",
".",
"set_defaults",
"(",
"show_toolbar",
"=",
"show_toolbar",
",",
"precision",... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | enable | 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 automatically use qgrid to display Series instances. | qgrid/grid.py | 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... | 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... | [
"Automatically",
"use",
"qgrid",
"to",
"display",
"all",
"DataFrames",
"and",
"/",
"or",
"Series",
"instances",
"in",
"the",
"notebook",
"."
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/grid.py#L281-L309 | [
"def",
"enable",
"(",
"dataframe",
"=",
"True",
",",
"series",
"=",
"True",
")",
":",
"try",
":",
"from",
"IPython",
".",
"core",
".",
"getipython",
"import",
"get_ipython",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'This feature requires IPy... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | show_grid | 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 ... | qgrid/grid.py | 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
... | 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
... | [
"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",
... | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/qgrid/grid.py#L322-L511 | [
"def",
"show_grid",
"(",
"data_frame",
",",
"show_toolbar",
"=",
"None",
",",
"precision",
"=",
"None",
",",
"grid_options",
"=",
"None",
",",
"column_options",
"=",
"None",
",",
"column_definitions",
"=",
"None",
",",
"row_edit_callback",
"=",
"None",
")",
... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | js_prerelease | decorator for building minified js/css prior to another command | setup.py | 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):
... | 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):
... | [
"decorator",
"for",
"building",
"minified",
"js",
"/",
"css",
"prior",
"to",
"another",
"command"
] | quantopian/qgrid | python | https://github.com/quantopian/qgrid/blob/c193f66945d9cd83b80f9ed0ce9f557404c66d81/setup.py#L30-L54 | [
"def",
"js_prerelease",
"(",
"command",
",",
"strict",
"=",
"False",
")",
":",
"class",
"DecoratedCommand",
"(",
"command",
")",
":",
"def",
"run",
"(",
"self",
")",
":",
"jsdeps",
"=",
"self",
".",
"distribution",
".",
"get_command_obj",
"(",
"'jsdeps'",
... | c193f66945d9cd83b80f9ed0ce9f557404c66d81 |
train | get_themes | return list of available themes | jupyterthemes/__init__.py | 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 | 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 | [
"return",
"list",
"of",
"available",
"themes"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/__init__.py#L20-L25 | [
"def",
"get_themes",
"(",
")",
":",
"styles_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"'styles'",
")",
"themes",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"theme",
")",
".",
"replace",
"(",
"'.less'",
",",
"''",
"... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | install_theme | Install theme to jupyter_customcss with specified font, fontsize,
md layout, and toolbar pref | jupyterthemes/__init__.py | def install_theme(theme=None,
monofont=None,
monosize=11,
nbfont=None,
nbfontsize=13,
tcfont=None,
tcfontsize=13,
dffontsize=93,
outfontsize=85,
mathfontsize=100,
... | def install_theme(theme=None,
monofont=None,
monosize=11,
nbfont=None,
nbfontsize=13,
tcfont=None,
tcfontsize=13,
dffontsize=93,
outfontsize=85,
mathfontsize=100,
... | [
"Install",
"theme",
"to",
"jupyter_customcss",
"with",
"specified",
"font",
"fontsize",
"md",
"layout",
"and",
"toolbar",
"pref"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/__init__.py#L28-L112 | [
"def",
"install_theme",
"(",
"theme",
"=",
"None",
",",
"monofont",
"=",
"None",
",",
"monosize",
"=",
"11",
",",
"nbfont",
"=",
"None",
",",
"nbfontsize",
"=",
"13",
",",
"tcfont",
"=",
"None",
",",
"tcfontsize",
"=",
"13",
",",
"dffontsize",
"=",
"... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | infer_theme | checks jupyter_config_dir() for text file containing theme name
(updated whenever user installs a new theme) | jupyterthemes/jtplot.py | 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):
... | 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):
... | [
"checks",
"jupyter_config_dir",
"()",
"for",
"text",
"file",
"containing",
"theme",
"name",
"(",
"updated",
"whenever",
"user",
"installs",
"a",
"new",
"theme",
")"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L62-L76 | [
"def",
"infer_theme",
"(",
")",
":",
"themes",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"theme",
")",
".",
"replace",
"(",
"'.less'",
",",
"''",
")",
"for",
"theme",
"in",
"glob",
"(",
"'{0}/*.less'",
".",
"format",
"(",
"styles_dir",
")",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | style | main function for styling matplotlib according to theme
::Arguments::
theme (str): 'oceans16', 'grade3', 'chesterish', 'onedork', 'monokai', 'solarizedl', 'solarizedd'. If no theme name supplied the currently installed notebook theme will be used.
context (str): 'paper' (Default), 'notebook', 'tal... | jupyterthemes/jtplot.py | 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 ... | 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 ... | [
"main",
"function",
"for",
"styling",
"matplotlib",
"according",
"to",
"theme"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L79-L109 | [
"def",
"style",
"(",
"theme",
"=",
"None",
",",
"context",
"=",
"'paper'",
",",
"grid",
"=",
"True",
",",
"gridlines",
"=",
"u'-'",
",",
"ticks",
"=",
"False",
",",
"spines",
"=",
"True",
",",
"fscale",
"=",
"1.2",
",",
"figsize",
"=",
"(",
"8.",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | set_style | 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): remove... | jupyterthemes/jtplot.py | 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... | 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... | [
"This",
"code",
"has",
"been",
"modified",
"from",
"seaborn",
".",
"rcmod",
".",
"set_style",
"()",
"::",
"Arguments",
"::",
"rcdict",
"(",
"str",
")",
":",
"dict",
"of",
"context",
"properties",
"(",
"filled",
"by",
"set_context",
"()",
")",
"theme",
"(... | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L113-L188 | [
"def",
"set_style",
"(",
"rcdict",
",",
"theme",
"=",
"None",
",",
"grid",
"=",
"True",
",",
"gridlines",
"=",
"u'-'",
",",
"ticks",
"=",
"False",
",",
"spines",
"=",
"True",
")",
":",
"# extract style and color info for theme",
"styleMap",
",",
"clist",
"... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | set_context | 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. | jupyterthemes/jtplot.py | 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... | 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... | [
"Most",
"of",
"this",
"code",
"has",
"been",
"copied",
"/",
"modified",
"from",
"seaborn",
".",
"rcmod",
".",
"plotting_context",
"()",
"::",
"Arguments",
"::",
"context",
"(",
"str",
")",
":",
"paper",
"notebook",
"talk",
"or",
"poster",
"fscale",
"(",
... | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L191-L212 | [
"def",
"set_context",
"(",
"context",
"=",
"'paper'",
",",
"fscale",
"=",
"1.",
",",
"figsize",
"=",
"(",
"8.",
",",
"7.",
")",
")",
":",
"# scale all the parameters by the same factor depending on the context",
"scaling",
"=",
"dict",
"(",
"paper",
"=",
".8",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | figsize | manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar | jupyterthemes/jtplot.py | 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... | 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... | [
"manually",
"set",
"the",
"default",
"figure",
"size",
"of",
"plots",
"::",
"Arguments",
"::",
"x",
"(",
"float",
")",
":",
"x",
"-",
"axis",
"size",
"y",
"(",
"float",
")",
":",
"y",
"-",
"axis",
"size",
"aspect",
"(",
"float",
")",
":",
"aspect",... | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L215-L223 | [
"def",
"figsize",
"(",
"x",
"=",
"8",
",",
"y",
"=",
"7.",
",",
"aspect",
"=",
"1.",
")",
":",
"# update rcparams with adjusted figsize params",
"mpl",
".",
"rcParams",
".",
"update",
"(",
"{",
"'figure.figsize'",
":",
"(",
"x",
"*",
"aspect",
",",
"y",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | get_theme_style | 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... | jupyterthemes/jtplot.py | 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... | 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... | [
"read",
"-",
"in",
"theme",
"style",
"info",
"and",
"populate",
"styleMap",
"(",
"dict",
"of",
"with",
"mpl",
".",
"rcParams",
")",
"and",
"clist",
"(",
"list",
"of",
"hex",
"codes",
"passed",
"to",
"color",
"cylcler",
")",
"::",
"Arguments",
"::",
"th... | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L226-L258 | [
"def",
"get_theme_style",
"(",
"theme",
")",
":",
"styleMap",
",",
"clist",
"=",
"get_default_jtstyle",
"(",
")",
"if",
"theme",
"==",
"'default'",
":",
"return",
"styleMap",
",",
"clist",
"syntaxVars",
"=",
"[",
"'@yellow:'",
",",
"'@orange:'",
",",
"'@red:... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | reset | full reset of matplotlib default style and colors | jupyterthemes/jtplot.py | 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... | 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... | [
"full",
"reset",
"of",
"matplotlib",
"default",
"style",
"and",
"colors"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L276-L287 | [
"def",
"reset",
"(",
")",
":",
"colors",
"=",
"[",
"(",
"0.",
",",
"0.",
",",
"1.",
")",
",",
"(",
"0.",
",",
".5",
",",
"0.",
")",
",",
"(",
"1.",
",",
"0.",
",",
"0.",
")",
",",
"(",
".75",
",",
".75",
",",
"0.",
")",
",",
"(",
".75... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | less_to_css | write less-compiled css file to jupyter_customcss in jupyter_dir | jupyterthemes/stylefx.py | 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 | 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 | [
"write",
"less",
"-",
"compiled",
"css",
"file",
"to",
"jupyter_customcss",
"in",
"jupyter_dir"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L69-L77 | [
"def",
"less_to_css",
"(",
"style_less",
")",
":",
"with",
"fileOpen",
"(",
"tempfile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"style_less",
")",
"os",
".",
"chdir",
"(",
"package_dir",
")",
"style_css",
"=",
"lesscpy",
".",
"compile"... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | set_font_properties | Parent function for setting notebook, text/md, and
codecell font-properties | jupyterthemes/stylefx.py | def set_font_properties(style_less,
nbfont=None,
tcfont=None,
monofont=None,
monosize=11,
tcfontsize=13,
nbfontsize=13,
prfontsize=95,
... | def set_font_properties(style_less,
nbfont=None,
tcfont=None,
monofont=None,
monosize=11,
tcfontsize=13,
nbfontsize=13,
prfontsize=95,
... | [
"Parent",
"function",
"for",
"setting",
"notebook",
"text",
"/",
"md",
"and",
"codecell",
"font",
"-",
"properties"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L120-L179 | [
"def",
"set_font_properties",
"(",
"style_less",
",",
"nbfont",
"=",
"None",
",",
"tcfont",
"=",
"None",
",",
"monofont",
"=",
"None",
",",
"monosize",
"=",
"11",
",",
"tcfontsize",
"=",
"13",
",",
"nbfontsize",
"=",
"13",
",",
"prfontsize",
"=",
"95",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | import_fonts | Copy all custom fonts to ~/.jupyter/custom/fonts/ and
write import statements to style_less | jupyterthemes/stylefx.py | 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',
... | 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',
... | [
"Copy",
"all",
"custom",
"fonts",
"to",
"~",
"/",
".",
"jupyter",
"/",
"custom",
"/",
"fonts",
"/",
"and",
"write",
"import",
"statements",
"to",
"style_less"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L182-L218 | [
"def",
"import_fonts",
"(",
"style_less",
",",
"fontname",
",",
"font_subdir",
")",
":",
"ftype_dict",
"=",
"{",
"'woff2'",
":",
"'woff2'",
",",
"'woff'",
":",
"'woff'",
",",
"'ttf'",
":",
"'truetype'",
",",
"'otf'",
":",
"'opentype'",
",",
"'svg'",
":",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | style_layout | Set general layout and style properties of text and code cells | jupyterthemes/stylefx.py | def style_layout(style_less,
theme='grade3',
cursorwidth=2,
cursorcolor='default',
cellwidth='980',
lineheight=170,
margins='auto',
vimext=False,
toolbar=False,
nbname... | def style_layout(style_less,
theme='grade3',
cursorwidth=2,
cursorcolor='default',
cellwidth='980',
lineheight=170,
margins='auto',
vimext=False,
toolbar=False,
nbname... | [
"Set",
"general",
"layout",
"and",
"style",
"properties",
"of",
"text",
"and",
"code",
"cells"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L221-L326 | [
"def",
"style_layout",
"(",
"style_less",
",",
"theme",
"=",
"'grade3'",
",",
"cursorwidth",
"=",
"2",
",",
"cursorcolor",
"=",
"'default'",
",",
"cellwidth",
"=",
"'980'",
",",
"lineheight",
"=",
"170",
",",
"margins",
"=",
"'auto'",
",",
"vimext",
"=",
... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | toggle_settings | Toggle main notebook toolbar (e.g., buttons), filename,
and kernel logo. | jupyterthemes/stylefx.py | 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... | 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... | [
"Toggle",
"main",
"notebook",
"toolbar",
"(",
"e",
".",
"g",
".",
"buttons",
")",
"filename",
"and",
"kernel",
"logo",
"."
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L329-L364 | [
"def",
"toggle_settings",
"(",
"toolbar",
"=",
"False",
",",
"nbname",
"=",
"False",
",",
"hideprompt",
"=",
"False",
",",
"kernellogo",
"=",
"False",
")",
":",
"toggle",
"=",
"''",
"if",
"toolbar",
":",
"toggle",
"+=",
"'div#maintoolbar {margin-left: 8px !imp... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | set_mathjax_style | Write mathjax settings, set math fontsize | jupyterthemes/stylefx.py | 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,
... | 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,
... | [
"Write",
"mathjax",
"settings",
"set",
"math",
"fontsize"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L400-L420 | [
"def",
"set_mathjax_style",
"(",
"style_css",
",",
"mathfontsize",
")",
":",
"jax_style",
"=",
"\"\"\"<script>\n MathJax.Hub.Config({\n \"HTML-CSS\": {\n /*preferredFont: \"TeX\",*/\n /*availableFonts: [\"TeX\", \"STIX\"],*/\n styles: {\n ... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | set_vim_style | Add style and compatibility with vim notebook extension | jupyterthemes/stylefx.py | 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]))
... | 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]))
... | [
"Add",
"style",
"and",
"compatibility",
"with",
"vim",
"notebook",
"extension"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L424-L445 | [
"def",
"set_vim_style",
"(",
"theme",
")",
":",
"vim_jupyter_nbext",
"=",
"os",
".",
"path",
".",
"join",
"(",
"jupyter_nbext",
",",
"'vim_binding'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"vim_jupyter_nbext",
")",
":",
"os",
".",
"maked... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | reset_default | Remove custom.css and custom fonts | jupyterthemes/stylefx.py | 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... | 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... | [
"Remove",
"custom",
".",
"css",
"and",
"custom",
"fonts"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L448-L471 | [
"def",
"reset_default",
"(",
"verbose",
"=",
"False",
")",
":",
"paths",
"=",
"[",
"jupyter_custom",
",",
"jupyter_nbext",
"]",
"for",
"fpath",
"in",
"paths",
":",
"custom",
"=",
"'{0}{1}{2}.css'",
".",
"format",
"(",
"fpath",
",",
"os",
".",
"sep",
",",... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | set_nb_theme | Set theme from within notebook | jupyterthemes/stylefx.py | 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... | 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... | [
"Set",
"theme",
"from",
"within",
"notebook"
] | dunovank/jupyter-themes | python | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L474-L481 | [
"def",
"set_nb_theme",
"(",
"name",
")",
":",
"from",
"IPython",
".",
"core",
".",
"display",
"import",
"HTML",
"styles_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"package_dir",
",",
"'styles/compiled/'",
")",
"css_path",
"=",
"glob",
"(",
"'{0}/{1}.c... | 421016c2e4fed75fa1830d664c10478d9bd25ed1 |
train | split_readme | Return split readme. | update_readme.py | 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... | 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",
"split",
"readme",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/update_readme.py#L17-L29 | [
"def",
"split_readme",
"(",
"readme_path",
",",
"before_key",
",",
"after_key",
",",
"options_key",
",",
"end_key",
")",
":",
"with",
"open",
"(",
"readme_path",
")",
"as",
"readme_file",
":",
"readme",
"=",
"readme_file",
".",
"read",
"(",
")",
"top",
","... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | help_message | Return help output. | update_readme.py | 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('~'), '~') | 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('~'), '~') | [
"Return",
"help",
"output",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/update_readme.py#L45-L51 | [
"def",
"help_message",
"(",
")",
":",
"parser",
"=",
"autopep8",
".",
"create_parser",
"(",
")",
"string_io",
"=",
"io",
".",
"StringIO",
"(",
")",
"parser",
".",
"print_help",
"(",
"string_io",
")",
"# Undo home directory expansion.",
"return",
"string_io",
"... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | check | Check code. | update_readme.py | 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) | 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) | [
"Check",
"code",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/update_readme.py#L54-L58 | [
"def",
"check",
"(",
"source",
")",
":",
"compile",
"(",
"source",
",",
"'<string>'",
",",
"'exec'",
",",
"dont_inherit",
"=",
"True",
")",
"reporter",
"=",
"pyflakes",
".",
"reporter",
".",
"Reporter",
"(",
"sys",
".",
"stderr",
",",
"sys",
".",
"stde... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | continued_indentation | Override pycodestyle's function to provide indentation information. | autopep8.py | 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
... | 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
... | [
"Override",
"pycodestyle",
"s",
"function",
"to",
"provide",
"indentation",
"information",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L204-L391 | [
"def",
"continued_indentation",
"(",
"logical_line",
",",
"tokens",
",",
"indent_level",
",",
"hang_closing",
",",
"indent_char",
",",
"noqa",
")",
":",
"first_row",
"=",
"tokens",
"[",
"0",
"]",
"[",
"2",
"]",
"[",
"0",
"]",
"nrows",
"=",
"1",
"+",
"t... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | get_w605_position | workaround get pointing out position by W605. | autopep8.py | 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',... | 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',... | [
"workaround",
"get",
"pointing",
"out",
"position",
"by",
"W605",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1360-L1392 | [
"def",
"get_w605_position",
"(",
"tokens",
")",
":",
"# TODO: When this PR(*) change is released, use pos of pycodestyle",
"# *: https://github.com/PyCQA/pycodestyle/pull/747",
"valid",
"=",
"[",
"'\\n'",
",",
"'\\\\'",
",",
"'\\''",
",",
"'\"'",
",",
"'a'",
",",
"'b'",
"... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | get_module_imports_on_top_of_file | return import or from keyword position
example:
> 0: import sys
1: import os
2:
3: def function(): | autopep8.py | 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... | 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... | [
"return",
"import",
"or",
"from",
"keyword",
"position"
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1395-L1453 | [
"def",
"get_module_imports_on_top_of_file",
"(",
"source",
",",
"import_line_index",
")",
":",
"def",
"is_string_literal",
"(",
"line",
")",
":",
"if",
"line",
"[",
"0",
"]",
"in",
"'uUbB'",
":",
"line",
"=",
"line",
"[",
"1",
":",
"]",
"if",
"line",
"an... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | get_fixed_long_line | Break up long line and return result.
Do this by generating multiple reformatted candidates and then
ranking the candidates to heuristically select the best option. | autopep8.py | 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... | 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... | [
"Break",
"up",
"long",
"line",
"and",
"return",
"result",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1464-L1509 | [
"def",
"get_fixed_long_line",
"(",
"target",
",",
"previous_line",
",",
"original",
",",
"indent_word",
"=",
"' '",
",",
"max_line_length",
"=",
"79",
",",
"aggressive",
"=",
"False",
",",
"experimental",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
"... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | join_logical_line | Return single line based on logical line input. | autopep8.py | 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' | 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",
"single",
"line",
"based",
"on",
"logical",
"line",
"input",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1517-L1522 | [
"def",
"join_logical_line",
"(",
"logical_line",
")",
":",
"indentation",
"=",
"_get_indentation",
"(",
"logical_line",
")",
"return",
"indentation",
"+",
"untokenize_without_newlines",
"(",
"generate_tokens",
"(",
"logical_line",
".",
"lstrip",
"(",
")",
")",
")",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | untokenize_without_newlines | Return source code based on tokens. | autopep8.py | 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... | 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",
"source",
"code",
"based",
"on",
"tokens",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1525-L1550 | [
"def",
"untokenize_without_newlines",
"(",
"tokens",
")",
":",
"text",
"=",
"''",
"last_row",
"=",
"0",
"last_column",
"=",
"-",
"1",
"for",
"t",
"in",
"tokens",
":",
"token_string",
"=",
"t",
"[",
"1",
"]",
"(",
"start_row",
",",
"start_column",
")",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _get_logical | Return the logical line corresponding to the result.
Assumes input is already E702-clean. | autopep8.py | 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):
... | 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",
"the",
"logical",
"line",
"corresponding",
"to",
"the",
"result",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1579-L1599 | [
"def",
"_get_logical",
"(",
"source_lines",
",",
"result",
",",
"logical_start",
",",
"logical_end",
")",
":",
"row",
"=",
"result",
"[",
"'line'",
"]",
"-",
"1",
"col",
"=",
"result",
"[",
"'column'",
"]",
"-",
"1",
"ls",
"=",
"None",
"le",
"=",
"No... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | code_almost_equal | Return True if code is similar.
Ignore whitespace when comparing specific line. | autopep8.py | 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(... | 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(... | [
"Return",
"True",
"if",
"code",
"is",
"similar",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1615-L1631 | [
"def",
"code_almost_equal",
"(",
"a",
",",
"b",
")",
":",
"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",
")",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | fix_2to3 | Fix various deprecated code (via lib2to3). | autopep8.py | 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,
... | 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,
... | [
"Fix",
"various",
"deprecated",
"code",
"(",
"via",
"lib2to3",
")",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1721-L1736 | [
"def",
"fix_2to3",
"(",
"source",
",",
"aggressive",
"=",
"True",
",",
"select",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"filename",
"=",
"''",
",",
"where",
"=",
"'global'",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"aggressive",
":... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | find_newline | Return type of newline used in source.
Input is a list of lines. | autopep8.py | 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):
... | 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",
"type",
"of",
"newline",
"used",
"in",
"source",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1747-L1764 | [
"def",
"find_newline",
"(",
"source",
")",
":",
"assert",
"not",
"isinstance",
"(",
"source",
",",
"unicode",
")",
"counter",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"line",
"in",
"source",
":",
"if",
"line",
".",
"endswith",
"(",... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _get_indentword | Return indentation type. | autopep8.py | 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... | 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",
"indentation",
"type",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1767-L1777 | [
"def",
"_get_indentword",
"(",
"source",
")",
":",
"indent_word",
"=",
"' '",
"# Default in case source has no indentation",
"try",
":",
"for",
"t",
"in",
"generate_tokens",
"(",
"source",
")",
":",
"if",
"t",
"[",
"0",
"]",
"==",
"token",
".",
"INDENT",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | get_diff_text | Return text of unified diff between old and new. | autopep8.py | 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
... | 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
... | [
"Return",
"text",
"of",
"unified",
"diff",
"between",
"old",
"and",
"new",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1789-L1806 | [
"def",
"get_diff_text",
"(",
"old",
",",
"new",
",",
"filename",
")",
":",
"newline",
"=",
"'\\n'",
"diff",
"=",
"difflib",
".",
"unified_diff",
"(",
"old",
",",
"new",
",",
"'original/'",
"+",
"filename",
",",
"'fixed/'",
"+",
"filename",
",",
"lineterm... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | shorten_line | Separate line at OPERATOR.
Multiple candidates will be yielded. | autopep8.py | 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,
... | 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",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1844-L1879 | [
"def",
"shorten_line",
"(",
"tokens",
",",
"source",
",",
"indentation",
",",
"indent_word",
",",
"max_line_length",
",",
"aggressive",
"=",
"False",
",",
"experimental",
"=",
"False",
",",
"previous_line",
"=",
"''",
")",
":",
"for",
"candidate",
"in",
"_sh... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _shorten_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. | autopep8.py | 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... | 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... | [
"Separate",
"line",
"at",
"OPERATOR",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1882-L1948 | [
"def",
"_shorten_line",
"(",
"tokens",
",",
"source",
",",
"indentation",
",",
"indent_word",
",",
"aggressive",
"=",
"False",
",",
"previous_line",
"=",
"''",
")",
":",
"for",
"(",
"token_type",
",",
"token_string",
",",
"start_offset",
",",
"end_offset",
"... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _parse_container | Parse a high-level container, such as a list, tuple, etc. | autopep8.py | 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 ... | 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",
"a",
"high",
"-",
"level",
"container",
"such",
"as",
"a",
"list",
"tuple",
"etc",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2603-L2659 | [
"def",
"_parse_container",
"(",
"tokens",
",",
"index",
",",
"for_or_if",
"=",
"None",
")",
":",
"# Store the opening bracket.",
"items",
"=",
"[",
"Atom",
"(",
"Token",
"(",
"*",
"tokens",
"[",
"index",
"]",
")",
")",
"]",
"index",
"+=",
"1",
"num_token... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _parse_tokens | Parse the tokens.
This converts the tokens into a form where we can manipulate them
more easily. | autopep8.py | 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... | 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... | [
"Parse",
"the",
"tokens",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2662-L2692 | [
"def",
"_parse_tokens",
"(",
"tokens",
")",
":",
"index",
"=",
"0",
"parsed_tokens",
"=",
"[",
"]",
"num_tokens",
"=",
"len",
"(",
"tokens",
")",
"while",
"index",
"<",
"num_tokens",
":",
"tok",
"=",
"Token",
"(",
"*",
"tokens",
"[",
"index",
"]",
")... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _reflow_lines | Reflow the lines so that it looks nice. | autopep8.py | 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... | 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... | [
"Reflow",
"the",
"lines",
"so",
"that",
"it",
"looks",
"nice",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2695-L2734 | [
"def",
"_reflow_lines",
"(",
"parsed_tokens",
",",
"indentation",
",",
"max_line_length",
",",
"start_on_prefix_line",
")",
":",
"if",
"unicode",
"(",
"parsed_tokens",
"[",
"0",
"]",
")",
"==",
"'def'",
":",
"# A function definition gets indented a bit more.",
"contin... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _shorten_line_at_tokens_new | 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. | autopep8.py | 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 ... | 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 ... | [
"Shorten",
"the",
"line",
"taking",
"its",
"length",
"into",
"account",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2737-L2762 | [
"def",
"_shorten_line_at_tokens_new",
"(",
"tokens",
",",
"source",
",",
"indentation",
",",
"max_line_length",
")",
":",
"# Yield the original source so to see if it's a better choice than the",
"# shortened candidate lines we generate here.",
"yield",
"indentation",
"+",
"source"... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _shorten_line_at_tokens | 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. | autopep8.py | 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... | 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... | [
"Separate",
"line",
"by",
"breaking",
"at",
"tokens",
"in",
"key_token_strings",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2765-L2841 | [
"def",
"_shorten_line_at_tokens",
"(",
"tokens",
",",
"source",
",",
"indentation",
",",
"indent_word",
",",
"key_token_strings",
",",
"aggressive",
")",
":",
"offsets",
"=",
"[",
"]",
"for",
"(",
"index",
",",
"_t",
")",
"in",
"enumerate",
"(",
"token_offse... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | token_offsets | Yield tokens and offsets. | autopep8.py | 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... | 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... | [
"Yield",
"tokens",
"and",
"offsets",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2844-L2872 | [
"def",
"token_offsets",
"(",
"tokens",
")",
":",
"end_offset",
"=",
"0",
"previous_end_row",
"=",
"0",
"previous_end_column",
"=",
"0",
"for",
"t",
"in",
"tokens",
":",
"token_type",
"=",
"t",
"[",
"0",
"]",
"token_string",
"=",
"t",
"[",
"1",
"]",
"("... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _execute_pep8 | Execute pycodestyle via python method calls. | autopep8.py | 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... | 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... | [
"Execute",
"pycodestyle",
"via",
"python",
"method",
"calls",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2906-L2941 | [
"def",
"_execute_pep8",
"(",
"pep8_options",
",",
"source",
")",
":",
"class",
"QuietReport",
"(",
"pycodestyle",
".",
"BaseReport",
")",
":",
"\"\"\"Version of checker that does not print.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"options",
")",
":",
"super",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _reindent_stats | 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! | autopep8.py | 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?
... | 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",
"list",
"of",
"(",
"lineno",
"indentlevel",
")",
"pairs",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3072-L3120 | [
"def",
"_reindent_stats",
"(",
"tokens",
")",
":",
"find_stmt",
"=",
"1",
"# Next token begins a fresh stmt?",
"level",
"=",
"0",
"# Current indent level.",
"stats",
"=",
"[",
"]",
"for",
"t",
"in",
"tokens",
":",
"token_type",
"=",
"t",
"[",
"0",
"]",
"slin... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _leading_space_count | Return number of leading spaces in line. | autopep8.py | 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 | 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 | [
"Return",
"number",
"of",
"leading",
"spaces",
"in",
"line",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3123-L3128 | [
"def",
"_leading_space_count",
"(",
"line",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"line",
")",
"and",
"line",
"[",
"i",
"]",
"==",
"' '",
":",
"i",
"+=",
"1",
"return",
"i"
] | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | refactor_with_2to3 | Use lib2to3 to refactor the source.
Return the refactored source code. | autopep8.py | 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... | 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... | [
"Use",
"lib2to3",
"to",
"refactor",
"the",
"source",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3131-L3146 | [
"def",
"refactor_with_2to3",
"(",
"source_text",
",",
"fixer_names",
",",
"filename",
"=",
"''",
")",
":",
"from",
"lib2to3",
".",
"refactor",
"import",
"RefactoringTool",
"fixers",
"=",
"[",
"'lib2to3.fixes.fix_'",
"+",
"name",
"for",
"name",
"in",
"fixer_names... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | check_syntax | Return True if syntax is okay. | autopep8.py | 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 | 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 | [
"Return",
"True",
"if",
"syntax",
"is",
"okay",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3149-L3154 | [
"def",
"check_syntax",
"(",
"code",
")",
":",
"try",
":",
"return",
"compile",
"(",
"code",
",",
"'<string>'",
",",
"'exec'",
",",
"dont_inherit",
"=",
"True",
")",
"except",
"(",
"SyntaxError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"F... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | filter_results | Filter out spurious reports from pycodestyle.
If aggressive is True, we allow possibly unsafe fixes (E711, E712). | autopep8.py | 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 = ... | 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 = ... | [
"Filter",
"out",
"spurious",
"reports",
"from",
"pycodestyle",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3157-L3214 | [
"def",
"filter_results",
"(",
"source",
",",
"results",
",",
"aggressive",
")",
":",
"non_docstring_string_line_numbers",
"=",
"multiline_string_lines",
"(",
"source",
",",
"include_docstrings",
"=",
"False",
")",
"all_string_line_numbers",
"=",
"multiline_string_lines",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | multiline_string_lines | Return line numbers that are within multiline strings.
The line numbers are indexed at 1.
Docstrings are ignored. | autopep8.py | 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... | 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",
"that",
"are",
"within",
"multiline",
"strings",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3217-L3246 | [
"def",
"multiline_string_lines",
"(",
"source",
",",
"include_docstrings",
"=",
"False",
")",
":",
"line_numbers",
"=",
"set",
"(",
")",
"previous_token_type",
"=",
"''",
"try",
":",
"for",
"t",
"in",
"generate_tokens",
"(",
"source",
")",
":",
"token_type",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | commented_out_code_lines | Return line numbers of comments that are likely code.
Commented-out code is bad practice, but modifying it just adds even
more clutter. | autopep8.py | 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_... | 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",
"line",
"numbers",
"of",
"comments",
"that",
"are",
"likely",
"code",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3249-L3279 | [
"def",
"commented_out_code_lines",
"(",
"source",
")",
":",
"line_numbers",
"=",
"[",
"]",
"try",
":",
"for",
"t",
"in",
"generate_tokens",
"(",
"source",
")",
":",
"token_type",
"=",
"t",
"[",
"0",
"]",
"token_string",
"=",
"t",
"[",
"1",
"]",
"start_... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | shorten_comment | 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. | autopep8.py | 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... | 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",
"trimmed",
"or",
"split",
"long",
"comment",
"line",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3282-L3314 | [
"def",
"shorten_comment",
"(",
"line",
",",
"max_line_length",
",",
"last_comment",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"line",
")",
">",
"max_line_length",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"# PEP 8 recommends 72 characters for comment text.... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | fix_code | Return fixed source code.
"encoding" will be used to decode "source" if it is a byte string. | autopep8.py | 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... | 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",
"fixed",
"source",
"code",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3347-L3359 | [
"def",
"fix_code",
"(",
"source",
",",
"options",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"apply_config",
"=",
"False",
")",
":",
"options",
"=",
"_get_options",
"(",
"options",
",",
"apply_config",
")",
"if",
"not",
"isinstance",
"(",
"source",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | _get_options | Return parsed options. | autopep8.py | 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():
... | 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",
"parsed",
"options",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3362-L3383 | [
"def",
"_get_options",
"(",
"raw_options",
",",
"apply_config",
")",
":",
"if",
"not",
"raw_options",
":",
"return",
"parse_args",
"(",
"[",
"''",
"]",
",",
"apply_config",
"=",
"apply_config",
")",
"if",
"isinstance",
"(",
"raw_options",
",",
"dict",
")",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | fix_lines | Return fixed source code. | autopep8.py | 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'... | 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'... | [
"Return",
"fixed",
"source",
"code",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3386-L3437 | [
"def",
"fix_lines",
"(",
"source_lines",
",",
"options",
",",
"filename",
"=",
"''",
")",
":",
"# Transform everything to line feed. Then change them back to original",
"# before returning fixed source code.",
"original_newline",
"=",
"find_newline",
"(",
"source_lines",
")",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | global_fixes | Yield multiple (code, function) tuples. | autopep8.py | 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... | 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... | [
"Yield",
"multiple",
"(",
"code",
"function",
")",
"tuples",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3479-L3489 | [
"def",
"global_fixes",
"(",
")",
":",
"for",
"function",
"in",
"list",
"(",
"globals",
"(",
")",
".",
"values",
"(",
")",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"function",
")",
":",
"arguments",
"=",
"_get_parameters",
"(",
"function",
")"... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | extract_code_from_function | Return code handled by function. | autopep8.py | 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
... | 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",
"code",
"handled",
"by",
"function",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3544-L3558 | [
"def",
"extract_code_from_function",
"(",
"function",
")",
":",
"if",
"not",
"function",
".",
"__name__",
".",
"startswith",
"(",
"'fix_'",
")",
":",
"return",
"None",
"code",
"=",
"re",
".",
"sub",
"(",
"'^fix_'",
",",
"''",
",",
"function",
".",
"__nam... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | create_parser | Return command-line parser. | autopep8.py | 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(
... | 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(
... | [
"Return",
"command",
"-",
"line",
"parser",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3566-L3636 | [
"def",
"create_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"docstring_summary",
"(",
"__doc__",
")",
",",
"prog",
"=",
"'autopep8'",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | parse_args | Parse command-line options. | autopep8.py | 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]... | 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]... | [
"Parse",
"command",
"-",
"line",
"options",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3639-L3722 | [
"def",
"parse_args",
"(",
"arguments",
",",
"apply_config",
"=",
"False",
")",
":",
"parser",
"=",
"create_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"arguments",
")",
"if",
"not",
"args",
".",
"files",
"and",
"not",
"args",
".",
... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
train | read_config | Read both user configuration and local configuration. | autopep8.py | 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... | 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... | [
"Read",
"both",
"user",
"configuration",
"and",
"local",
"configuration",
"."
] | hhatto/autopep8 | python | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3725-L3776 | [
"def",
"read_config",
"(",
"args",
",",
"parser",
")",
":",
"try",
":",
"from",
"configparser",
"import",
"ConfigParser",
"as",
"SafeConfigParser",
"from",
"configparser",
"import",
"Error",
"except",
"ImportError",
":",
"from",
"ConfigParser",
"import",
"SafeConf... | fda3bb39181437b6b8a0aa0185f21ae5f14385dd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.