id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,100 | sphinx-gallery/sphinx-gallery | sphinx_gallery/downloads.py | list_downloadable_sources | def list_downloadable_sources(target_dir):
"""Returns a list of python source files is target_dir
Parameters
----------
target_dir : str
path to the directory where python source file are
Returns
-------
list
list of paths to all Python source files in `target_dir`
"""
return [os.path.join(target_dir, fname)
for fname in os.listdir(target_dir)
if fname.endswith('.py')] | python | def list_downloadable_sources(target_dir):
return [os.path.join(target_dir, fname)
for fname in os.listdir(target_dir)
if fname.endswith('.py')] | [
"def",
"list_downloadable_sources",
"(",
"target_dir",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"fname",
")",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"target_dir",
")",
"if",
"fname",
".",
"endswith",
"(",... | Returns a list of python source files is target_dir
Parameters
----------
target_dir : str
path to the directory where python source file are
Returns
-------
list
list of paths to all Python source files in `target_dir` | [
"Returns",
"a",
"list",
"of",
"python",
"source",
"files",
"is",
"target_dir"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/downloads.py#L81-L95 |
230,101 | sphinx-gallery/sphinx-gallery | sphinx_gallery/downloads.py | generate_zipfiles | def generate_zipfiles(gallery_dir):
"""
Collects all Python source files and Jupyter notebooks in
gallery_dir and makes zipfiles of them
Parameters
----------
gallery_dir : str
path of the gallery to collect downloadable sources
Return
------
download_rst: str
RestructuredText to include download buttons to the generated files
"""
listdir = list_downloadable_sources(gallery_dir)
for directory in sorted(os.listdir(gallery_dir)):
if os.path.isdir(os.path.join(gallery_dir, directory)):
target_dir = os.path.join(gallery_dir, directory)
listdir.extend(list_downloadable_sources(target_dir))
py_zipfile = python_zip(listdir, gallery_dir)
jy_zipfile = python_zip(listdir, gallery_dir, ".ipynb")
def rst_path(filepath):
return filepath.replace(os.sep, '/')
dw_rst = CODE_ZIP_DOWNLOAD.format(os.path.basename(py_zipfile),
rst_path(py_zipfile),
os.path.basename(jy_zipfile),
rst_path(jy_zipfile))
return dw_rst | python | def generate_zipfiles(gallery_dir):
listdir = list_downloadable_sources(gallery_dir)
for directory in sorted(os.listdir(gallery_dir)):
if os.path.isdir(os.path.join(gallery_dir, directory)):
target_dir = os.path.join(gallery_dir, directory)
listdir.extend(list_downloadable_sources(target_dir))
py_zipfile = python_zip(listdir, gallery_dir)
jy_zipfile = python_zip(listdir, gallery_dir, ".ipynb")
def rst_path(filepath):
return filepath.replace(os.sep, '/')
dw_rst = CODE_ZIP_DOWNLOAD.format(os.path.basename(py_zipfile),
rst_path(py_zipfile),
os.path.basename(jy_zipfile),
rst_path(jy_zipfile))
return dw_rst | [
"def",
"generate_zipfiles",
"(",
"gallery_dir",
")",
":",
"listdir",
"=",
"list_downloadable_sources",
"(",
"gallery_dir",
")",
"for",
"directory",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"gallery_dir",
")",
")",
":",
"if",
"os",
".",
"path",
".",
... | Collects all Python source files and Jupyter notebooks in
gallery_dir and makes zipfiles of them
Parameters
----------
gallery_dir : str
path of the gallery to collect downloadable sources
Return
------
download_rst: str
RestructuredText to include download buttons to the generated files | [
"Collects",
"all",
"Python",
"source",
"files",
"and",
"Jupyter",
"notebooks",
"in",
"gallery_dir",
"and",
"makes",
"zipfiles",
"of",
"them"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/downloads.py#L98-L130 |
230,102 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | codestr2rst | def codestr2rst(codestr, lang='python', lineno=None):
"""Return reStructuredText code block from code string"""
if lineno is not None:
if LooseVersion(sphinx.__version__) >= '1.3':
# Sphinx only starts numbering from the first non-empty line.
blank_lines = codestr.count('\n', 0, -len(codestr.lstrip()))
lineno = ' :lineno-start: {0}\n'.format(lineno + blank_lines)
else:
lineno = ' :linenos:\n'
else:
lineno = ''
code_directive = "\n.. code-block:: {0}\n{1}\n".format(lang, lineno)
indented_block = indent(codestr, ' ' * 4)
return code_directive + indented_block | python | def codestr2rst(codestr, lang='python', lineno=None):
if lineno is not None:
if LooseVersion(sphinx.__version__) >= '1.3':
# Sphinx only starts numbering from the first non-empty line.
blank_lines = codestr.count('\n', 0, -len(codestr.lstrip()))
lineno = ' :lineno-start: {0}\n'.format(lineno + blank_lines)
else:
lineno = ' :linenos:\n'
else:
lineno = ''
code_directive = "\n.. code-block:: {0}\n{1}\n".format(lang, lineno)
indented_block = indent(codestr, ' ' * 4)
return code_directive + indented_block | [
"def",
"codestr2rst",
"(",
"codestr",
",",
"lang",
"=",
"'python'",
",",
"lineno",
"=",
"None",
")",
":",
"if",
"lineno",
"is",
"not",
"None",
":",
"if",
"LooseVersion",
"(",
"sphinx",
".",
"__version__",
")",
">=",
"'1.3'",
":",
"# Sphinx only starts numb... | Return reStructuredText code block from code string | [
"Return",
"reStructuredText",
"code",
"block",
"from",
"code",
"string"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L178-L191 |
230,103 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | md5sum_is_current | def md5sum_is_current(src_file):
"""Checks whether src_file has the same md5 hash as the one on disk"""
src_md5 = get_md5sum(src_file)
src_md5_file = src_file + '.md5'
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
return src_md5 == ref_md5
return False | python | def md5sum_is_current(src_file):
src_md5 = get_md5sum(src_file)
src_md5_file = src_file + '.md5'
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
return src_md5 == ref_md5
return False | [
"def",
"md5sum_is_current",
"(",
"src_file",
")",
":",
"src_md5",
"=",
"get_md5sum",
"(",
"src_file",
")",
"src_md5_file",
"=",
"src_file",
"+",
"'.md5'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"src_md5_file",
")",
":",
"with",
"open",
"(",
"src_md5_... | Checks whether src_file has the same md5 hash as the one on disk | [
"Checks",
"whether",
"src_file",
"has",
"the",
"same",
"md5",
"hash",
"as",
"the",
"one",
"on",
"disk"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L227-L239 |
230,104 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | save_thumbnail | def save_thumbnail(image_path_template, src_file, file_conf, gallery_conf):
"""Generate and Save the thumbnail image
Parameters
----------
image_path_template : str
holds the template where to save and how to name the image
src_file : str
path to source python file
gallery_conf : dict
Sphinx-Gallery configuration dictionary
"""
# read specification of the figure to display as thumbnail from main text
thumbnail_number = file_conf.get('thumbnail_number', 1)
if not isinstance(thumbnail_number, int):
raise TypeError(
'sphinx_gallery_thumbnail_number setting is not a number, '
'got %r' % (thumbnail_number,))
thumbnail_image_path, ext = _find_image_ext(image_path_template,
thumbnail_number)
thumb_dir = os.path.join(os.path.dirname(thumbnail_image_path), 'thumb')
if not os.path.exists(thumb_dir):
os.makedirs(thumb_dir)
base_image_name = os.path.splitext(os.path.basename(src_file))[0]
thumb_file = os.path.join(thumb_dir,
'sphx_glr_%s_thumb.%s' % (base_image_name, ext))
if src_file in gallery_conf['failing_examples']:
img = os.path.join(glr_path_static(), 'broken_example.png')
elif os.path.exists(thumbnail_image_path):
img = thumbnail_image_path
elif not os.path.exists(thumb_file):
# create something to replace the thumbnail
img = os.path.join(glr_path_static(), 'no_image.png')
img = gallery_conf.get("default_thumb_file", img)
else:
return
if ext == 'svg':
copyfile(img, thumb_file)
else:
scale_image(img, thumb_file, *gallery_conf["thumbnail_size"]) | python | def save_thumbnail(image_path_template, src_file, file_conf, gallery_conf):
# read specification of the figure to display as thumbnail from main text
thumbnail_number = file_conf.get('thumbnail_number', 1)
if not isinstance(thumbnail_number, int):
raise TypeError(
'sphinx_gallery_thumbnail_number setting is not a number, '
'got %r' % (thumbnail_number,))
thumbnail_image_path, ext = _find_image_ext(image_path_template,
thumbnail_number)
thumb_dir = os.path.join(os.path.dirname(thumbnail_image_path), 'thumb')
if not os.path.exists(thumb_dir):
os.makedirs(thumb_dir)
base_image_name = os.path.splitext(os.path.basename(src_file))[0]
thumb_file = os.path.join(thumb_dir,
'sphx_glr_%s_thumb.%s' % (base_image_name, ext))
if src_file in gallery_conf['failing_examples']:
img = os.path.join(glr_path_static(), 'broken_example.png')
elif os.path.exists(thumbnail_image_path):
img = thumbnail_image_path
elif not os.path.exists(thumb_file):
# create something to replace the thumbnail
img = os.path.join(glr_path_static(), 'no_image.png')
img = gallery_conf.get("default_thumb_file", img)
else:
return
if ext == 'svg':
copyfile(img, thumb_file)
else:
scale_image(img, thumb_file, *gallery_conf["thumbnail_size"]) | [
"def",
"save_thumbnail",
"(",
"image_path_template",
",",
"src_file",
",",
"file_conf",
",",
"gallery_conf",
")",
":",
"# read specification of the figure to display as thumbnail from main text",
"thumbnail_number",
"=",
"file_conf",
".",
"get",
"(",
"'thumbnail_number'",
","... | Generate and Save the thumbnail image
Parameters
----------
image_path_template : str
holds the template where to save and how to name the image
src_file : str
path to source python file
gallery_conf : dict
Sphinx-Gallery configuration dictionary | [
"Generate",
"and",
"Save",
"the",
"thumbnail",
"image"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L242-L284 |
230,105 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | _memory_usage | def _memory_usage(func, gallery_conf):
"""Get memory usage of a function call."""
if gallery_conf['show_memory']:
from memory_profiler import memory_usage
assert callable(func)
mem, out = memory_usage(func, max_usage=True, retval=True,
multiprocess=True)
mem = mem[0]
else:
out = func()
mem = 0
return out, mem | python | def _memory_usage(func, gallery_conf):
if gallery_conf['show_memory']:
from memory_profiler import memory_usage
assert callable(func)
mem, out = memory_usage(func, max_usage=True, retval=True,
multiprocess=True)
mem = mem[0]
else:
out = func()
mem = 0
return out, mem | [
"def",
"_memory_usage",
"(",
"func",
",",
"gallery_conf",
")",
":",
"if",
"gallery_conf",
"[",
"'show_memory'",
"]",
":",
"from",
"memory_profiler",
"import",
"memory_usage",
"assert",
"callable",
"(",
"func",
")",
"mem",
",",
"out",
"=",
"memory_usage",
"(",
... | Get memory usage of a function call. | [
"Get",
"memory",
"usage",
"of",
"a",
"function",
"call",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L392-L403 |
230,106 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | _get_memory_base | def _get_memory_base(gallery_conf):
"""Get the base amount of memory used by running a Python process."""
if not gallery_conf['show_memory']:
memory_base = 0
else:
# There might be a cleaner way to do this at some point
from memory_profiler import memory_usage
sleep, timeout = (1, 2) if sys.platform == 'win32' else (0.5, 1)
proc = subprocess.Popen(
[sys.executable, '-c',
'import time, sys; time.sleep(%s); sys.exit(0)' % sleep],
close_fds=True)
memories = memory_usage(proc, interval=1e-3, timeout=timeout)
kwargs = dict(timeout=timeout) if sys.version_info >= (3, 5) else {}
proc.communicate(**kwargs)
# On OSX sometimes the last entry can be None
memories = [mem for mem in memories if mem is not None] + [0.]
memory_base = max(memories)
return memory_base | python | def _get_memory_base(gallery_conf):
if not gallery_conf['show_memory']:
memory_base = 0
else:
# There might be a cleaner way to do this at some point
from memory_profiler import memory_usage
sleep, timeout = (1, 2) if sys.platform == 'win32' else (0.5, 1)
proc = subprocess.Popen(
[sys.executable, '-c',
'import time, sys; time.sleep(%s); sys.exit(0)' % sleep],
close_fds=True)
memories = memory_usage(proc, interval=1e-3, timeout=timeout)
kwargs = dict(timeout=timeout) if sys.version_info >= (3, 5) else {}
proc.communicate(**kwargs)
# On OSX sometimes the last entry can be None
memories = [mem for mem in memories if mem is not None] + [0.]
memory_base = max(memories)
return memory_base | [
"def",
"_get_memory_base",
"(",
"gallery_conf",
")",
":",
"if",
"not",
"gallery_conf",
"[",
"'show_memory'",
"]",
":",
"memory_base",
"=",
"0",
"else",
":",
"# There might be a cleaner way to do this at some point",
"from",
"memory_profiler",
"import",
"memory_usage",
"... | Get the base amount of memory used by running a Python process. | [
"Get",
"the",
"base",
"amount",
"of",
"memory",
"used",
"by",
"running",
"a",
"Python",
"process",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L406-L424 |
230,107 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | execute_code_block | def execute_code_block(compiler, block, example_globals,
script_vars, gallery_conf):
"""Executes the code block of the example file"""
blabel, bcontent, lineno = block
# If example is not suitable to run, skip executing its blocks
if not script_vars['execute_script'] or blabel == 'text':
script_vars['memory_delta'].append(0)
return ''
cwd = os.getcwd()
# Redirect output to stdout and
orig_stdout = sys.stdout
src_file = script_vars['src_file']
# First cd in the original example dir, so that any file
# created by the example get created in this directory
my_stdout = MixedEncodingStringIO()
os.chdir(os.path.dirname(src_file))
sys_path = copy.deepcopy(sys.path)
sys.path.append(os.getcwd())
sys.stdout = LoggingTee(my_stdout, logger, src_file)
try:
dont_inherit = 1
code_ast = compile(bcontent, src_file, 'exec',
ast.PyCF_ONLY_AST | compiler.flags, dont_inherit)
ast.increment_lineno(code_ast, lineno - 1)
# don't use unicode_literals at the top of this file or you get
# nasty errors here on Py2.7
_, mem = _memory_usage(_exec_once(
compiler(code_ast, src_file, 'exec'), example_globals),
gallery_conf)
except Exception:
sys.stdout.flush()
sys.stdout = orig_stdout
except_rst = handle_exception(sys.exc_info(), src_file, script_vars,
gallery_conf)
# python2.7: Code was read in bytes needs decoding to utf-8
# unless future unicode_literals is imported in source which
# make ast output unicode strings
if hasattr(except_rst, 'decode') and not \
isinstance(except_rst, unicode):
except_rst = except_rst.decode('utf-8')
code_output = u"\n{0}\n\n\n\n".format(except_rst)
# still call this even though we won't use the images so that
# figures are closed
save_figures(block, script_vars, gallery_conf)
mem = 0
else:
sys.stdout.flush()
sys.stdout = orig_stdout
sys.path = sys_path
os.chdir(cwd)
my_stdout = my_stdout.getvalue().strip().expandtabs()
if my_stdout:
stdout = CODE_OUTPUT.format(indent(my_stdout, u' ' * 4))
else:
stdout = ''
images_rst = save_figures(block, script_vars, gallery_conf)
code_output = u"\n{0}\n\n{1}\n\n".format(images_rst, stdout)
finally:
os.chdir(cwd)
sys.path = sys_path
sys.stdout = orig_stdout
script_vars['memory_delta'].append(mem)
return code_output | python | def execute_code_block(compiler, block, example_globals,
script_vars, gallery_conf):
blabel, bcontent, lineno = block
# If example is not suitable to run, skip executing its blocks
if not script_vars['execute_script'] or blabel == 'text':
script_vars['memory_delta'].append(0)
return ''
cwd = os.getcwd()
# Redirect output to stdout and
orig_stdout = sys.stdout
src_file = script_vars['src_file']
# First cd in the original example dir, so that any file
# created by the example get created in this directory
my_stdout = MixedEncodingStringIO()
os.chdir(os.path.dirname(src_file))
sys_path = copy.deepcopy(sys.path)
sys.path.append(os.getcwd())
sys.stdout = LoggingTee(my_stdout, logger, src_file)
try:
dont_inherit = 1
code_ast = compile(bcontent, src_file, 'exec',
ast.PyCF_ONLY_AST | compiler.flags, dont_inherit)
ast.increment_lineno(code_ast, lineno - 1)
# don't use unicode_literals at the top of this file or you get
# nasty errors here on Py2.7
_, mem = _memory_usage(_exec_once(
compiler(code_ast, src_file, 'exec'), example_globals),
gallery_conf)
except Exception:
sys.stdout.flush()
sys.stdout = orig_stdout
except_rst = handle_exception(sys.exc_info(), src_file, script_vars,
gallery_conf)
# python2.7: Code was read in bytes needs decoding to utf-8
# unless future unicode_literals is imported in source which
# make ast output unicode strings
if hasattr(except_rst, 'decode') and not \
isinstance(except_rst, unicode):
except_rst = except_rst.decode('utf-8')
code_output = u"\n{0}\n\n\n\n".format(except_rst)
# still call this even though we won't use the images so that
# figures are closed
save_figures(block, script_vars, gallery_conf)
mem = 0
else:
sys.stdout.flush()
sys.stdout = orig_stdout
sys.path = sys_path
os.chdir(cwd)
my_stdout = my_stdout.getvalue().strip().expandtabs()
if my_stdout:
stdout = CODE_OUTPUT.format(indent(my_stdout, u' ' * 4))
else:
stdout = ''
images_rst = save_figures(block, script_vars, gallery_conf)
code_output = u"\n{0}\n\n{1}\n\n".format(images_rst, stdout)
finally:
os.chdir(cwd)
sys.path = sys_path
sys.stdout = orig_stdout
script_vars['memory_delta'].append(mem)
return code_output | [
"def",
"execute_code_block",
"(",
"compiler",
",",
"block",
",",
"example_globals",
",",
"script_vars",
",",
"gallery_conf",
")",
":",
"blabel",
",",
"bcontent",
",",
"lineno",
"=",
"block",
"# If example is not suitable to run, skip executing its blocks",
"if",
"not",
... | Executes the code block of the example file | [
"Executes",
"the",
"code",
"block",
"of",
"the",
"example",
"file"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L427-L498 |
230,108 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | executable_script | def executable_script(src_file, gallery_conf):
"""Validate if script has to be run according to gallery configuration
Parameters
----------
src_file : str
path to python script
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
bool
True if script has to be executed
"""
filename_pattern = gallery_conf.get('filename_pattern')
execute = re.search(filename_pattern, src_file) and gallery_conf[
'plot_gallery']
return execute | python | def executable_script(src_file, gallery_conf):
filename_pattern = gallery_conf.get('filename_pattern')
execute = re.search(filename_pattern, src_file) and gallery_conf[
'plot_gallery']
return execute | [
"def",
"executable_script",
"(",
"src_file",
",",
"gallery_conf",
")",
":",
"filename_pattern",
"=",
"gallery_conf",
".",
"get",
"(",
"'filename_pattern'",
")",
"execute",
"=",
"re",
".",
"search",
"(",
"filename_pattern",
",",
"src_file",
")",
"and",
"gallery_c... | Validate if script has to be run according to gallery configuration
Parameters
----------
src_file : str
path to python script
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
bool
True if script has to be executed | [
"Validate",
"if",
"script",
"has",
"to",
"be",
"run",
"according",
"to",
"gallery",
"configuration"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L501-L521 |
230,109 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | execute_script | def execute_script(script_blocks, script_vars, gallery_conf):
"""Execute and capture output from python script already in block structure
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
the corresponding content string of block and the leading line number
script_vars : dict
Configuration and run time variables
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
output_blocks : list
List of strings where each element is the restructured text
representation of the output of each block
time_elapsed : float
Time elapsed during execution
"""
example_globals = {
# A lot of examples contains 'print(__doc__)' for example in
# scikit-learn so that running the example prints some useful
# information. Because the docstring has been separated from
# the code blocks in sphinx-gallery, __doc__ is actually
# __builtin__.__doc__ in the execution context and we do not
# want to print it
'__doc__': '',
# Examples may contain if __name__ == '__main__' guards
# for in example scikit-learn if the example uses multiprocessing
'__name__': '__main__',
# Don't ever support __file__: Issues #166 #212
}
argv_orig = sys.argv[:]
if script_vars['execute_script']:
# We want to run the example without arguments. See
# https://github.com/sphinx-gallery/sphinx-gallery/pull/252
# for more details.
sys.argv[0] = script_vars['src_file']
sys.argv[1:] = []
t_start = time()
gc.collect()
_, memory_start = _memory_usage(lambda: None, gallery_conf)
compiler = codeop.Compile()
# include at least one entry to avoid max() ever failing
script_vars['memory_delta'] = [memory_start]
output_blocks = [execute_code_block(compiler, block,
example_globals,
script_vars, gallery_conf)
for block in script_blocks]
time_elapsed = time() - t_start
script_vars['memory_delta'] = ( # actually turn it into a delta now
max(script_vars['memory_delta']) - memory_start)
sys.argv = argv_orig
# Write md5 checksum if the example was meant to run (no-plot
# shall not cache md5sum) and has built correctly
if script_vars['execute_script']:
with open(script_vars['target_file'] + '.md5', 'w') as file_checksum:
file_checksum.write(get_md5sum(script_vars['target_file']))
gallery_conf['passing_examples'].append(script_vars['src_file'])
return output_blocks, time_elapsed | python | def execute_script(script_blocks, script_vars, gallery_conf):
example_globals = {
# A lot of examples contains 'print(__doc__)' for example in
# scikit-learn so that running the example prints some useful
# information. Because the docstring has been separated from
# the code blocks in sphinx-gallery, __doc__ is actually
# __builtin__.__doc__ in the execution context and we do not
# want to print it
'__doc__': '',
# Examples may contain if __name__ == '__main__' guards
# for in example scikit-learn if the example uses multiprocessing
'__name__': '__main__',
# Don't ever support __file__: Issues #166 #212
}
argv_orig = sys.argv[:]
if script_vars['execute_script']:
# We want to run the example without arguments. See
# https://github.com/sphinx-gallery/sphinx-gallery/pull/252
# for more details.
sys.argv[0] = script_vars['src_file']
sys.argv[1:] = []
t_start = time()
gc.collect()
_, memory_start = _memory_usage(lambda: None, gallery_conf)
compiler = codeop.Compile()
# include at least one entry to avoid max() ever failing
script_vars['memory_delta'] = [memory_start]
output_blocks = [execute_code_block(compiler, block,
example_globals,
script_vars, gallery_conf)
for block in script_blocks]
time_elapsed = time() - t_start
script_vars['memory_delta'] = ( # actually turn it into a delta now
max(script_vars['memory_delta']) - memory_start)
sys.argv = argv_orig
# Write md5 checksum if the example was meant to run (no-plot
# shall not cache md5sum) and has built correctly
if script_vars['execute_script']:
with open(script_vars['target_file'] + '.md5', 'w') as file_checksum:
file_checksum.write(get_md5sum(script_vars['target_file']))
gallery_conf['passing_examples'].append(script_vars['src_file'])
return output_blocks, time_elapsed | [
"def",
"execute_script",
"(",
"script_blocks",
",",
"script_vars",
",",
"gallery_conf",
")",
":",
"example_globals",
"=",
"{",
"# A lot of examples contains 'print(__doc__)' for example in",
"# scikit-learn so that running the example prints some useful",
"# information. Because the do... | Execute and capture output from python script already in block structure
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
the corresponding content string of block and the leading line number
script_vars : dict
Configuration and run time variables
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
output_blocks : list
List of strings where each element is the restructured text
representation of the output of each block
time_elapsed : float
Time elapsed during execution | [
"Execute",
"and",
"capture",
"output",
"from",
"python",
"script",
"already",
"in",
"block",
"structure"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L524-L592 |
230,110 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | rst_blocks | def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
"""Generates the rst string containing the script prose, code and output
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
the corresponding content string of block and the leading line number
output_blocks : list
List of strings where each element is the restructured text
representation of the output of each block
file_conf : dict
File-specific settings given in source file comments as:
``# sphinx_gallery_<name> = <value>``
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
out : str
rst notebook
"""
# A simple example has two blocks: one for the
# example introduction/explanation and one for the code
is_example_notebook_like = len(script_blocks) > 2
example_rst = u"" # there can be unicode content
for (blabel, bcontent, lineno), code_output in \
zip(script_blocks, output_blocks):
if blabel == 'code':
if not file_conf.get('line_numbers',
gallery_conf.get('line_numbers', False)):
lineno = None
code_rst = codestr2rst(bcontent, lang=gallery_conf['lang'],
lineno=lineno) + '\n'
if is_example_notebook_like:
example_rst += code_rst
example_rst += code_output
else:
example_rst += code_output
if 'sphx-glr-script-out' in code_output:
# Add some vertical space after output
example_rst += "\n\n|\n\n"
example_rst += code_rst
else:
block_separator = '\n\n' if not bcontent.endswith('\n') else '\n'
example_rst += bcontent + block_separator
return example_rst | python | def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
# A simple example has two blocks: one for the
# example introduction/explanation and one for the code
is_example_notebook_like = len(script_blocks) > 2
example_rst = u"" # there can be unicode content
for (blabel, bcontent, lineno), code_output in \
zip(script_blocks, output_blocks):
if blabel == 'code':
if not file_conf.get('line_numbers',
gallery_conf.get('line_numbers', False)):
lineno = None
code_rst = codestr2rst(bcontent, lang=gallery_conf['lang'],
lineno=lineno) + '\n'
if is_example_notebook_like:
example_rst += code_rst
example_rst += code_output
else:
example_rst += code_output
if 'sphx-glr-script-out' in code_output:
# Add some vertical space after output
example_rst += "\n\n|\n\n"
example_rst += code_rst
else:
block_separator = '\n\n' if not bcontent.endswith('\n') else '\n'
example_rst += bcontent + block_separator
return example_rst | [
"def",
"rst_blocks",
"(",
"script_blocks",
",",
"output_blocks",
",",
"file_conf",
",",
"gallery_conf",
")",
":",
"# A simple example has two blocks: one for the",
"# example introduction/explanation and one for the code",
"is_example_notebook_like",
"=",
"len",
"(",
"script_bloc... | Generates the rst string containing the script prose, code and output
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
the corresponding content string of block and the leading line number
output_blocks : list
List of strings where each element is the restructured text
representation of the output of each block
file_conf : dict
File-specific settings given in source file comments as:
``# sphinx_gallery_<name> = <value>``
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
out : str
rst notebook | [
"Generates",
"the",
"rst",
"string",
"containing",
"the",
"script",
"prose",
"code",
"and",
"output"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L669-L719 |
230,111 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_rst.py | save_rst_example | def save_rst_example(example_rst, example_file, time_elapsed,
memory_used, gallery_conf):
"""Saves the rst notebook to example_file including header & footer
Parameters
----------
example_rst : str
rst containing the executed file content
example_file : str
Filename with full path of python example file in documentation folder
time_elapsed : float
Time elapsed in seconds while executing file
memory_used : float
Additional memory used during the run.
gallery_conf : dict
Sphinx-Gallery configuration dictionary
"""
ref_fname = os.path.relpath(example_file, gallery_conf['src_dir'])
ref_fname = ref_fname.replace(os.path.sep, "_")
binder_conf = check_binder_conf(gallery_conf.get('binder'))
binder_text = (" or run this example in your browser via Binder"
if len(binder_conf) else "")
example_rst = (".. note::\n"
" :class: sphx-glr-download-link-note\n\n"
" Click :ref:`here <sphx_glr_download_{0}>` "
"to download the full example code{1}\n"
".. rst-class:: sphx-glr-example-title\n\n"
".. _sphx_glr_{0}:\n\n"
).format(ref_fname, binder_text) + example_rst
if time_elapsed >= gallery_conf["min_reported_time"]:
time_m, time_s = divmod(time_elapsed, 60)
example_rst += TIMING_CONTENT.format(time_m, time_s)
if gallery_conf['show_memory']:
example_rst += ("**Estimated memory usage:** {0: .0f} MB\n\n"
.format(memory_used))
# Generate a binder URL if specified
binder_badge_rst = ''
if len(binder_conf) > 0:
binder_badge_rst += gen_binder_rst(example_file, binder_conf,
gallery_conf)
fname = os.path.basename(example_file)
example_rst += CODE_DOWNLOAD.format(fname,
replace_py_ipynb(fname),
binder_badge_rst,
ref_fname)
example_rst += SPHX_GLR_SIG
write_file_new = re.sub(r'\.py$', '.rst.new', example_file)
with codecs.open(write_file_new, 'w', encoding="utf-8") as f:
f.write(example_rst)
# in case it wasn't in our pattern, only replace the file if it's
# still stale.
_replace_md5(write_file_new) | python | def save_rst_example(example_rst, example_file, time_elapsed,
memory_used, gallery_conf):
ref_fname = os.path.relpath(example_file, gallery_conf['src_dir'])
ref_fname = ref_fname.replace(os.path.sep, "_")
binder_conf = check_binder_conf(gallery_conf.get('binder'))
binder_text = (" or run this example in your browser via Binder"
if len(binder_conf) else "")
example_rst = (".. note::\n"
" :class: sphx-glr-download-link-note\n\n"
" Click :ref:`here <sphx_glr_download_{0}>` "
"to download the full example code{1}\n"
".. rst-class:: sphx-glr-example-title\n\n"
".. _sphx_glr_{0}:\n\n"
).format(ref_fname, binder_text) + example_rst
if time_elapsed >= gallery_conf["min_reported_time"]:
time_m, time_s = divmod(time_elapsed, 60)
example_rst += TIMING_CONTENT.format(time_m, time_s)
if gallery_conf['show_memory']:
example_rst += ("**Estimated memory usage:** {0: .0f} MB\n\n"
.format(memory_used))
# Generate a binder URL if specified
binder_badge_rst = ''
if len(binder_conf) > 0:
binder_badge_rst += gen_binder_rst(example_file, binder_conf,
gallery_conf)
fname = os.path.basename(example_file)
example_rst += CODE_DOWNLOAD.format(fname,
replace_py_ipynb(fname),
binder_badge_rst,
ref_fname)
example_rst += SPHX_GLR_SIG
write_file_new = re.sub(r'\.py$', '.rst.new', example_file)
with codecs.open(write_file_new, 'w', encoding="utf-8") as f:
f.write(example_rst)
# in case it wasn't in our pattern, only replace the file if it's
# still stale.
_replace_md5(write_file_new) | [
"def",
"save_rst_example",
"(",
"example_rst",
",",
"example_file",
",",
"time_elapsed",
",",
"memory_used",
",",
"gallery_conf",
")",
":",
"ref_fname",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"example_file",
",",
"gallery_conf",
"[",
"'src_dir'",
"]",
")... | Saves the rst notebook to example_file including header & footer
Parameters
----------
example_rst : str
rst containing the executed file content
example_file : str
Filename with full path of python example file in documentation folder
time_elapsed : float
Time elapsed in seconds while executing file
memory_used : float
Additional memory used during the run.
gallery_conf : dict
Sphinx-Gallery configuration dictionary | [
"Saves",
"the",
"rst",
"notebook",
"to",
"example_file",
"including",
"header",
"&",
"footer"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_rst.py#L722-L780 |
230,112 | sphinx-gallery/sphinx-gallery | sphinx_gallery/docs_resolv.py | get_data | def get_data(url, gallery_dir):
"""Persistent dictionary usage to retrieve the search indexes"""
# shelve keys need to be str in python 2
if sys.version_info[0] == 2 and isinstance(url, unicode):
url = url.encode('utf-8')
cached_file = os.path.join(gallery_dir, 'searchindex')
search_index = shelve.open(cached_file)
if url in search_index:
data = search_index[url]
else:
data = _get_data(url)
search_index[url] = data
search_index.close()
return data | python | def get_data(url, gallery_dir):
# shelve keys need to be str in python 2
if sys.version_info[0] == 2 and isinstance(url, unicode):
url = url.encode('utf-8')
cached_file = os.path.join(gallery_dir, 'searchindex')
search_index = shelve.open(cached_file)
if url in search_index:
data = search_index[url]
else:
data = _get_data(url)
search_index[url] = data
search_index.close()
return data | [
"def",
"get_data",
"(",
"url",
",",
"gallery_dir",
")",
":",
"# shelve keys need to be str in python 2",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
"and",
"isinstance",
"(",
"url",
",",
"unicode",
")",
":",
"url",
"=",
"url",
".",
"encode"... | Persistent dictionary usage to retrieve the search indexes | [
"Persistent",
"dictionary",
"usage",
"to",
"retrieve",
"the",
"search",
"indexes"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/docs_resolv.py#L61-L77 |
230,113 | sphinx-gallery/sphinx-gallery | sphinx_gallery/docs_resolv.py | parse_sphinx_docopts | def parse_sphinx_docopts(index):
"""
Parse the Sphinx index for documentation options.
Parameters
----------
index : str
The Sphinx index page
Returns
-------
docopts : dict
The documentation options from the page.
"""
pos = index.find('var DOCUMENTATION_OPTIONS')
if pos < 0:
raise ValueError('Documentation options could not be found in index.')
pos = index.find('{', pos)
if pos < 0:
raise ValueError('Documentation options could not be found in index.')
endpos = index.find('};', pos)
if endpos < 0:
raise ValueError('Documentation options could not be found in index.')
block = index[pos + 1:endpos].strip()
docopts = {}
for line in block.splitlines():
key, value = line.split(':', 1)
key = key.strip().strip('"')
value = value.strip()
if value[-1] == ',':
value = value[:-1].rstrip()
if value[0] in '"\'':
value = value[1:-1]
elif value == 'false':
value = False
elif value == 'true':
value = True
else:
try:
value = int(value)
except ValueError:
# In Sphinx 1.7.5, URL_ROOT is a JavaScript fragment.
# Ignoring this entry since URL_ROOT is not used
# elsewhere.
# https://github.com/sphinx-gallery/sphinx-gallery/issues/382
continue
docopts[key] = value
return docopts | python | def parse_sphinx_docopts(index):
pos = index.find('var DOCUMENTATION_OPTIONS')
if pos < 0:
raise ValueError('Documentation options could not be found in index.')
pos = index.find('{', pos)
if pos < 0:
raise ValueError('Documentation options could not be found in index.')
endpos = index.find('};', pos)
if endpos < 0:
raise ValueError('Documentation options could not be found in index.')
block = index[pos + 1:endpos].strip()
docopts = {}
for line in block.splitlines():
key, value = line.split(':', 1)
key = key.strip().strip('"')
value = value.strip()
if value[-1] == ',':
value = value[:-1].rstrip()
if value[0] in '"\'':
value = value[1:-1]
elif value == 'false':
value = False
elif value == 'true':
value = True
else:
try:
value = int(value)
except ValueError:
# In Sphinx 1.7.5, URL_ROOT is a JavaScript fragment.
# Ignoring this entry since URL_ROOT is not used
# elsewhere.
# https://github.com/sphinx-gallery/sphinx-gallery/issues/382
continue
docopts[key] = value
return docopts | [
"def",
"parse_sphinx_docopts",
"(",
"index",
")",
":",
"pos",
"=",
"index",
".",
"find",
"(",
"'var DOCUMENTATION_OPTIONS'",
")",
"if",
"pos",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Documentation options could not be found in index.'",
")",
"pos",
"=",
"inde... | Parse the Sphinx index for documentation options.
Parameters
----------
index : str
The Sphinx index page
Returns
-------
docopts : dict
The documentation options from the page. | [
"Parse",
"the",
"Sphinx",
"index",
"for",
"documentation",
"options",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/docs_resolv.py#L80-L131 |
230,114 | sphinx-gallery/sphinx-gallery | sphinx_gallery/docs_resolv.py | embed_code_links | def embed_code_links(app, exception):
"""Embed hyperlinks to documentation into example code"""
if exception is not None:
return
# No need to waste time embedding hyperlinks when not running the examples
# XXX: also at the time of writing this fixes make html-noplot
# for some reason I don't fully understand
if not app.builder.config.plot_gallery:
return
# XXX: Whitelist of builders for which it makes sense to embed
# hyperlinks inside the example html. Note that the link embedding
# require searchindex.js to exist for the links to the local doc
# and there does not seem to be a good way of knowing which
# builders creates a searchindex.js.
if app.builder.name not in ['html', 'readthedocs']:
return
logger.info('embedding documentation hyperlinks...', color='white')
gallery_conf = app.config.sphinx_gallery_conf
gallery_dirs = gallery_conf['gallery_dirs']
if not isinstance(gallery_dirs, list):
gallery_dirs = [gallery_dirs]
for gallery_dir in gallery_dirs:
_embed_code_links(app, gallery_conf, gallery_dir) | python | def embed_code_links(app, exception):
if exception is not None:
return
# No need to waste time embedding hyperlinks when not running the examples
# XXX: also at the time of writing this fixes make html-noplot
# for some reason I don't fully understand
if not app.builder.config.plot_gallery:
return
# XXX: Whitelist of builders for which it makes sense to embed
# hyperlinks inside the example html. Note that the link embedding
# require searchindex.js to exist for the links to the local doc
# and there does not seem to be a good way of knowing which
# builders creates a searchindex.js.
if app.builder.name not in ['html', 'readthedocs']:
return
logger.info('embedding documentation hyperlinks...', color='white')
gallery_conf = app.config.sphinx_gallery_conf
gallery_dirs = gallery_conf['gallery_dirs']
if not isinstance(gallery_dirs, list):
gallery_dirs = [gallery_dirs]
for gallery_dir in gallery_dirs:
_embed_code_links(app, gallery_conf, gallery_dir) | [
"def",
"embed_code_links",
"(",
"app",
",",
"exception",
")",
":",
"if",
"exception",
"is",
"not",
"None",
":",
"return",
"# No need to waste time embedding hyperlinks when not running the examples",
"# XXX: also at the time of writing this fixes make html-noplot",
"# for some reas... | Embed hyperlinks to documentation into example code | [
"Embed",
"hyperlinks",
"to",
"documentation",
"into",
"example",
"code"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/docs_resolv.py#L382-L410 |
230,115 | sphinx-gallery/sphinx-gallery | sphinx_gallery/docs_resolv.py | SphinxDocLinkResolver._get_link | def _get_link(self, cobj):
"""Get a valid link, False if not found"""
fullname = cobj['module_short'] + '.' + cobj['name']
try:
value = self._searchindex['objects'][cobj['module_short']]
match = value[cobj['name']]
except KeyError:
link = False
else:
fname_idx = match[0]
objname_idx = str(match[1])
anchor = match[3]
fname = self._searchindex['filenames'][fname_idx]
# In 1.5+ Sphinx seems to have changed from .rst.html to only
# .html extension in converted files. Find this from the options.
ext = self._docopts.get('FILE_SUFFIX', '.rst.html')
fname = os.path.splitext(fname)[0] + ext
if self._is_windows:
fname = fname.replace('/', '\\')
link = os.path.join(self.doc_url, fname)
else:
link = posixpath.join(self.doc_url, fname)
if anchor == '':
anchor = fullname
elif anchor == '-':
anchor = (self._searchindex['objnames'][objname_idx][1] + '-' +
fullname)
link = link + '#' + anchor
return link | python | def _get_link(self, cobj):
fullname = cobj['module_short'] + '.' + cobj['name']
try:
value = self._searchindex['objects'][cobj['module_short']]
match = value[cobj['name']]
except KeyError:
link = False
else:
fname_idx = match[0]
objname_idx = str(match[1])
anchor = match[3]
fname = self._searchindex['filenames'][fname_idx]
# In 1.5+ Sphinx seems to have changed from .rst.html to only
# .html extension in converted files. Find this from the options.
ext = self._docopts.get('FILE_SUFFIX', '.rst.html')
fname = os.path.splitext(fname)[0] + ext
if self._is_windows:
fname = fname.replace('/', '\\')
link = os.path.join(self.doc_url, fname)
else:
link = posixpath.join(self.doc_url, fname)
if anchor == '':
anchor = fullname
elif anchor == '-':
anchor = (self._searchindex['objnames'][objname_idx][1] + '-' +
fullname)
link = link + '#' + anchor
return link | [
"def",
"_get_link",
"(",
"self",
",",
"cobj",
")",
":",
"fullname",
"=",
"cobj",
"[",
"'module_short'",
"]",
"+",
"'.'",
"+",
"cobj",
"[",
"'name'",
"]",
"try",
":",
"value",
"=",
"self",
".",
"_searchindex",
"[",
"'objects'",
"]",
"[",
"cobj",
"[",
... | Get a valid link, False if not found | [
"Get",
"a",
"valid",
"link",
"False",
"if",
"not",
"found"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/docs_resolv.py#L191-L224 |
230,116 | sphinx-gallery/sphinx-gallery | sphinx_gallery/docs_resolv.py | SphinxDocLinkResolver.resolve | def resolve(self, cobj, this_url):
"""Resolve the link to the documentation, returns None if not found
Parameters
----------
cobj : dict
Dict with information about the "code object" for which we are
resolving a link.
cobj['name'] : function or class name (str)
cobj['module_short'] : shortened module name (str)
cobj['module'] : module name (str)
this_url: str
URL of the current page. Needed to construct relative URLs
(only used if relative=True in constructor).
Returns
-------
link : str or None
The link (URL) to the documentation.
"""
full_name = cobj['module_short'] + '.' + cobj['name']
link = self._link_cache.get(full_name, None)
if link is None:
# we don't have it cached
link = self._get_link(cobj)
# cache it for the future
self._link_cache[full_name] = link
if link is False or link is None:
# failed to resolve
return None
if self.relative:
link = os.path.relpath(link, start=this_url)
if self._is_windows:
# replace '\' with '/' so it on the web
link = link.replace('\\', '/')
# for some reason, the relative link goes one directory too high up
link = link[3:]
return link | python | def resolve(self, cobj, this_url):
full_name = cobj['module_short'] + '.' + cobj['name']
link = self._link_cache.get(full_name, None)
if link is None:
# we don't have it cached
link = self._get_link(cobj)
# cache it for the future
self._link_cache[full_name] = link
if link is False or link is None:
# failed to resolve
return None
if self.relative:
link = os.path.relpath(link, start=this_url)
if self._is_windows:
# replace '\' with '/' so it on the web
link = link.replace('\\', '/')
# for some reason, the relative link goes one directory too high up
link = link[3:]
return link | [
"def",
"resolve",
"(",
"self",
",",
"cobj",
",",
"this_url",
")",
":",
"full_name",
"=",
"cobj",
"[",
"'module_short'",
"]",
"+",
"'.'",
"+",
"cobj",
"[",
"'name'",
"]",
"link",
"=",
"self",
".",
"_link_cache",
".",
"get",
"(",
"full_name",
",",
"Non... | Resolve the link to the documentation, returns None if not found
Parameters
----------
cobj : dict
Dict with information about the "code object" for which we are
resolving a link.
cobj['name'] : function or class name (str)
cobj['module_short'] : shortened module name (str)
cobj['module'] : module name (str)
this_url: str
URL of the current page. Needed to construct relative URLs
(only used if relative=True in constructor).
Returns
-------
link : str or None
The link (URL) to the documentation. | [
"Resolve",
"the",
"link",
"to",
"the",
"documentation",
"returns",
"None",
"if",
"not",
"found"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/docs_resolv.py#L226-L267 |
230,117 | sphinx-gallery/sphinx-gallery | sphinx_gallery/__init__.py | glr_path_static | def glr_path_static():
"""Returns path to packaged static files"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static')) | python | def glr_path_static():
return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static')) | [
"def",
"glr_path_static",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'_static'",
")",
")"
] | Returns path to packaged static files | [
"Returns",
"path",
"to",
"packaged",
"static",
"files"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/__init__.py#L10-L12 |
230,118 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | gen_binder_url | def gen_binder_url(fpath, binder_conf, gallery_conf):
"""Generate a Binder URL according to the configuration in conf.py.
Parameters
----------
fpath: str
The path to the `.py` file for which a Binder badge will be generated.
binder_conf: dict or None
The Binder configuration dictionary. See `gen_binder_rst` for details.
Returns
-------
binder_url : str
A URL that can be used to direct the user to the live Binder
environment.
"""
# Build the URL
fpath_prefix = binder_conf.get('filepath_prefix')
link_base = binder_conf.get('notebooks_dir')
# We want to keep the relative path to sub-folders
relative_link = os.path.relpath(fpath, gallery_conf['src_dir'])
path_link = os.path.join(
link_base, replace_py_ipynb(relative_link))
# In case our website is hosted in a sub-folder
if fpath_prefix is not None:
path_link = '/'.join([fpath_prefix.strip('/'), path_link])
# Make sure we have the right slashes (in case we're on Windows)
path_link = path_link.replace(os.path.sep, '/')
# Create the URL
binder_url = binder_conf['binderhub_url']
binder_url = '/'.join([binder_conf['binderhub_url'],
'v2', 'gh',
binder_conf['org'],
binder_conf['repo'],
binder_conf['branch']])
if binder_conf.get('use_jupyter_lab', False) is True:
binder_url += '?urlpath=lab/tree/{}'.format(path_link)
else:
binder_url += '?filepath={}'.format(path_link)
return binder_url | python | def gen_binder_url(fpath, binder_conf, gallery_conf):
# Build the URL
fpath_prefix = binder_conf.get('filepath_prefix')
link_base = binder_conf.get('notebooks_dir')
# We want to keep the relative path to sub-folders
relative_link = os.path.relpath(fpath, gallery_conf['src_dir'])
path_link = os.path.join(
link_base, replace_py_ipynb(relative_link))
# In case our website is hosted in a sub-folder
if fpath_prefix is not None:
path_link = '/'.join([fpath_prefix.strip('/'), path_link])
# Make sure we have the right slashes (in case we're on Windows)
path_link = path_link.replace(os.path.sep, '/')
# Create the URL
binder_url = binder_conf['binderhub_url']
binder_url = '/'.join([binder_conf['binderhub_url'],
'v2', 'gh',
binder_conf['org'],
binder_conf['repo'],
binder_conf['branch']])
if binder_conf.get('use_jupyter_lab', False) is True:
binder_url += '?urlpath=lab/tree/{}'.format(path_link)
else:
binder_url += '?filepath={}'.format(path_link)
return binder_url | [
"def",
"gen_binder_url",
"(",
"fpath",
",",
"binder_conf",
",",
"gallery_conf",
")",
":",
"# Build the URL",
"fpath_prefix",
"=",
"binder_conf",
".",
"get",
"(",
"'filepath_prefix'",
")",
"link_base",
"=",
"binder_conf",
".",
"get",
"(",
"'notebooks_dir'",
")",
... | Generate a Binder URL according to the configuration in conf.py.
Parameters
----------
fpath: str
The path to the `.py` file for which a Binder badge will be generated.
binder_conf: dict or None
The Binder configuration dictionary. See `gen_binder_rst` for details.
Returns
-------
binder_url : str
A URL that can be used to direct the user to the live Binder
environment. | [
"Generate",
"a",
"Binder",
"URL",
"according",
"to",
"the",
"configuration",
"in",
"conf",
".",
"py",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L34-L78 |
230,119 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | gen_binder_rst | def gen_binder_rst(fpath, binder_conf, gallery_conf):
"""Generate the RST + link for the Binder badge.
Parameters
----------
fpath: str
The path to the `.py` file for which a Binder badge will be generated.
binder_conf: dict or None
If a dictionary it must have the following keys:
'binderhub_url': The URL of the BinderHub instance that's running a Binder
service.
'org': The GitHub organization to which the documentation will be
pushed.
'repo': The GitHub repository to which the documentation will be
pushed.
'branch': The Git branch on which the documentation exists (e.g.,
gh-pages).
'dependencies': A list of paths to dependency files that match the
Binderspec.
Returns
-------
rst : str
The reStructuredText for the Binder badge that links to this file.
"""
binder_conf = check_binder_conf(binder_conf)
binder_url = gen_binder_url(fpath, binder_conf, gallery_conf)
rst = (
"\n"
" .. container:: binder-badge\n\n"
" .. image:: https://mybinder.org/badge_logo.svg\n"
" :target: {}\n"
" :width: 150 px\n").format(binder_url)
return rst | python | def gen_binder_rst(fpath, binder_conf, gallery_conf):
binder_conf = check_binder_conf(binder_conf)
binder_url = gen_binder_url(fpath, binder_conf, gallery_conf)
rst = (
"\n"
" .. container:: binder-badge\n\n"
" .. image:: https://mybinder.org/badge_logo.svg\n"
" :target: {}\n"
" :width: 150 px\n").format(binder_url)
return rst | [
"def",
"gen_binder_rst",
"(",
"fpath",
",",
"binder_conf",
",",
"gallery_conf",
")",
":",
"binder_conf",
"=",
"check_binder_conf",
"(",
"binder_conf",
")",
"binder_url",
"=",
"gen_binder_url",
"(",
"fpath",
",",
"binder_conf",
",",
"gallery_conf",
")",
"rst",
"=... | Generate the RST + link for the Binder badge.
Parameters
----------
fpath: str
The path to the `.py` file for which a Binder badge will be generated.
binder_conf: dict or None
If a dictionary it must have the following keys:
'binderhub_url': The URL of the BinderHub instance that's running a Binder
service.
'org': The GitHub organization to which the documentation will be
pushed.
'repo': The GitHub repository to which the documentation will be
pushed.
'branch': The Git branch on which the documentation exists (e.g.,
gh-pages).
'dependencies': A list of paths to dependency files that match the
Binderspec.
Returns
-------
rst : str
The reStructuredText for the Binder badge that links to this file. | [
"Generate",
"the",
"RST",
"+",
"link",
"for",
"the",
"Binder",
"badge",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L81-L116 |
230,120 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | copy_binder_files | def copy_binder_files(app, exception):
"""Copy all Binder requirements and notebooks files."""
if exception is not None:
return
if app.builder.name not in ['html', 'readthedocs']:
return
gallery_conf = app.config.sphinx_gallery_conf
binder_conf = check_binder_conf(gallery_conf.get('binder'))
if not len(binder_conf) > 0:
return
logger.info('copying binder requirements...', color='white')
_copy_binder_reqs(app, binder_conf)
_copy_binder_notebooks(app) | python | def copy_binder_files(app, exception):
if exception is not None:
return
if app.builder.name not in ['html', 'readthedocs']:
return
gallery_conf = app.config.sphinx_gallery_conf
binder_conf = check_binder_conf(gallery_conf.get('binder'))
if not len(binder_conf) > 0:
return
logger.info('copying binder requirements...', color='white')
_copy_binder_reqs(app, binder_conf)
_copy_binder_notebooks(app) | [
"def",
"copy_binder_files",
"(",
"app",
",",
"exception",
")",
":",
"if",
"exception",
"is",
"not",
"None",
":",
"return",
"if",
"app",
".",
"builder",
".",
"name",
"not",
"in",
"[",
"'html'",
",",
"'readthedocs'",
"]",
":",
"return",
"gallery_conf",
"="... | Copy all Binder requirements and notebooks files. | [
"Copy",
"all",
"Binder",
"requirements",
"and",
"notebooks",
"files",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L119-L135 |
230,121 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | _copy_binder_reqs | def _copy_binder_reqs(app, binder_conf):
"""Copy Binder requirements files to a "binder" folder in the docs."""
path_reqs = binder_conf.get('dependencies')
for path in path_reqs:
if not os.path.exists(os.path.join(app.srcdir, path)):
raise ValueError(("Couldn't find the Binder requirements file: {}, "
"did you specify the path correctly?".format(path)))
binder_folder = os.path.join(app.outdir, 'binder')
if not os.path.isdir(binder_folder):
os.makedirs(binder_folder)
# Copy over the requirements to the output directory
for path in path_reqs:
shutil.copy(os.path.join(app.srcdir, path), binder_folder) | python | def _copy_binder_reqs(app, binder_conf):
path_reqs = binder_conf.get('dependencies')
for path in path_reqs:
if not os.path.exists(os.path.join(app.srcdir, path)):
raise ValueError(("Couldn't find the Binder requirements file: {}, "
"did you specify the path correctly?".format(path)))
binder_folder = os.path.join(app.outdir, 'binder')
if not os.path.isdir(binder_folder):
os.makedirs(binder_folder)
# Copy over the requirements to the output directory
for path in path_reqs:
shutil.copy(os.path.join(app.srcdir, path), binder_folder) | [
"def",
"_copy_binder_reqs",
"(",
"app",
",",
"binder_conf",
")",
":",
"path_reqs",
"=",
"binder_conf",
".",
"get",
"(",
"'dependencies'",
")",
"for",
"path",
"in",
"path_reqs",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
... | Copy Binder requirements files to a "binder" folder in the docs. | [
"Copy",
"Binder",
"requirements",
"files",
"to",
"a",
"binder",
"folder",
"in",
"the",
"docs",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L138-L152 |
230,122 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | _remove_ipynb_files | def _remove_ipynb_files(path, contents):
"""Given a list of files in `contents`, remove all files named `ipynb` or
directories named `images` and return the result.
Used with the `shutil` "ignore" keyword to filter out non-ipynb files."""
contents_return = []
for entry in contents:
if entry.endswith('.ipynb'):
# Don't include ipynb files
pass
elif (entry != "images") and os.path.isdir(os.path.join(path, entry)):
# Don't include folders not called "images"
pass
else:
# Keep everything else
contents_return.append(entry)
return contents_return | python | def _remove_ipynb_files(path, contents):
contents_return = []
for entry in contents:
if entry.endswith('.ipynb'):
# Don't include ipynb files
pass
elif (entry != "images") and os.path.isdir(os.path.join(path, entry)):
# Don't include folders not called "images"
pass
else:
# Keep everything else
contents_return.append(entry)
return contents_return | [
"def",
"_remove_ipynb_files",
"(",
"path",
",",
"contents",
")",
":",
"contents_return",
"=",
"[",
"]",
"for",
"entry",
"in",
"contents",
":",
"if",
"entry",
".",
"endswith",
"(",
"'.ipynb'",
")",
":",
"# Don't include ipynb files",
"pass",
"elif",
"(",
"ent... | Given a list of files in `contents`, remove all files named `ipynb` or
directories named `images` and return the result.
Used with the `shutil` "ignore" keyword to filter out non-ipynb files. | [
"Given",
"a",
"list",
"of",
"files",
"in",
"contents",
"remove",
"all",
"files",
"named",
"ipynb",
"or",
"directories",
"named",
"images",
"and",
"return",
"the",
"result",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L155-L171 |
230,123 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | _copy_binder_notebooks | def _copy_binder_notebooks(app):
"""Copy Jupyter notebooks to the binder notebooks directory.
Copy each output gallery directory structure but only including the
Jupyter notebook files."""
gallery_conf = app.config.sphinx_gallery_conf
gallery_dirs = gallery_conf.get('gallery_dirs')
binder_conf = gallery_conf.get('binder')
notebooks_dir = os.path.join(app.outdir, binder_conf.get('notebooks_dir'))
shutil.rmtree(notebooks_dir, ignore_errors=True)
os.makedirs(notebooks_dir)
if not isinstance(gallery_dirs, (list, tuple)):
gallery_dirs = [gallery_dirs]
iterator = sphinx_compatibility.status_iterator(
gallery_dirs, 'copying binder notebooks...', length=len(gallery_dirs))
for i_folder in iterator:
shutil.copytree(os.path.join(app.srcdir, i_folder),
os.path.join(notebooks_dir, i_folder),
ignore=_remove_ipynb_files) | python | def _copy_binder_notebooks(app):
gallery_conf = app.config.sphinx_gallery_conf
gallery_dirs = gallery_conf.get('gallery_dirs')
binder_conf = gallery_conf.get('binder')
notebooks_dir = os.path.join(app.outdir, binder_conf.get('notebooks_dir'))
shutil.rmtree(notebooks_dir, ignore_errors=True)
os.makedirs(notebooks_dir)
if not isinstance(gallery_dirs, (list, tuple)):
gallery_dirs = [gallery_dirs]
iterator = sphinx_compatibility.status_iterator(
gallery_dirs, 'copying binder notebooks...', length=len(gallery_dirs))
for i_folder in iterator:
shutil.copytree(os.path.join(app.srcdir, i_folder),
os.path.join(notebooks_dir, i_folder),
ignore=_remove_ipynb_files) | [
"def",
"_copy_binder_notebooks",
"(",
"app",
")",
":",
"gallery_conf",
"=",
"app",
".",
"config",
".",
"sphinx_gallery_conf",
"gallery_dirs",
"=",
"gallery_conf",
".",
"get",
"(",
"'gallery_dirs'",
")",
"binder_conf",
"=",
"gallery_conf",
".",
"get",
"(",
"'bind... | Copy Jupyter notebooks to the binder notebooks directory.
Copy each output gallery directory structure but only including the
Jupyter notebook files. | [
"Copy",
"Jupyter",
"notebooks",
"to",
"the",
"binder",
"notebooks",
"directory",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L174-L196 |
230,124 | sphinx-gallery/sphinx-gallery | sphinx_gallery/binder.py | check_binder_conf | def check_binder_conf(binder_conf):
"""Check to make sure that the Binder configuration is correct."""
# Grab the configuration and return None if it's not configured
binder_conf = {} if binder_conf is None else binder_conf
if not isinstance(binder_conf, dict):
raise ValueError('`binder_conf` must be a dictionary or None.')
if len(binder_conf) == 0:
return binder_conf
if binder_conf.get('url') and not binder_conf.get('binderhub_url'):
logger.warning(
'Found old BinderHub URL keyword ("url"). Please update your '
'configuration to use the new keyword ("binderhub_url"). "url" will be '
'deprecated in sphinx-gallery v0.4')
binder_conf['binderhub_url'] = binderhub_conf.get('url')
# Ensure all fields are populated
req_values = ['binderhub_url', 'org', 'repo', 'branch', 'dependencies']
optional_values = ['filepath_prefix', 'notebooks_dir', 'use_jupyter_lab']
missing_values = []
for val in req_values:
if binder_conf.get(val) is None:
missing_values.append(val)
if len(missing_values) > 0:
raise ValueError('binder_conf is missing values for: {}'.format(
missing_values))
for key in binder_conf.keys():
if key not in (req_values + optional_values):
raise ValueError("Unknown Binder config key: {}".format(key))
# Ensure we have http in the URL
if not any(binder_conf['binderhub_url'].startswith(ii)
for ii in ['http://', 'https://']):
raise ValueError('did not supply a valid url, '
'gave binderhub_url: {}'.format(binder_conf['binderhub_url']))
# Ensure we have at least one dependency file
# Need at least one of these three files
required_reqs_files = ['requirements.txt', 'environment.yml', 'Dockerfile']
path_reqs = binder_conf['dependencies']
if isinstance(path_reqs, basestring):
path_reqs = [path_reqs]
binder_conf['dependencies'] = path_reqs
elif not isinstance(path_reqs, (list, tuple)):
raise ValueError("`dependencies` value should be a list of strings. "
"Got type {}.".format(type(path_reqs)))
binder_conf['notebooks_dir'] = binder_conf.get('notebooks_dir',
'notebooks')
path_reqs_filenames = [os.path.basename(ii) for ii in path_reqs]
if not any(ii in path_reqs_filenames for ii in required_reqs_files):
raise ValueError(
'Did not find one of `requirements.txt` or `environment.yml` '
'in the "dependencies" section of the binder configuration '
'for sphinx-gallery. A path to at least one of these files '
'must exist in your Binder dependencies.')
return binder_conf | python | def check_binder_conf(binder_conf):
# Grab the configuration and return None if it's not configured
binder_conf = {} if binder_conf is None else binder_conf
if not isinstance(binder_conf, dict):
raise ValueError('`binder_conf` must be a dictionary or None.')
if len(binder_conf) == 0:
return binder_conf
if binder_conf.get('url') and not binder_conf.get('binderhub_url'):
logger.warning(
'Found old BinderHub URL keyword ("url"). Please update your '
'configuration to use the new keyword ("binderhub_url"). "url" will be '
'deprecated in sphinx-gallery v0.4')
binder_conf['binderhub_url'] = binderhub_conf.get('url')
# Ensure all fields are populated
req_values = ['binderhub_url', 'org', 'repo', 'branch', 'dependencies']
optional_values = ['filepath_prefix', 'notebooks_dir', 'use_jupyter_lab']
missing_values = []
for val in req_values:
if binder_conf.get(val) is None:
missing_values.append(val)
if len(missing_values) > 0:
raise ValueError('binder_conf is missing values for: {}'.format(
missing_values))
for key in binder_conf.keys():
if key not in (req_values + optional_values):
raise ValueError("Unknown Binder config key: {}".format(key))
# Ensure we have http in the URL
if not any(binder_conf['binderhub_url'].startswith(ii)
for ii in ['http://', 'https://']):
raise ValueError('did not supply a valid url, '
'gave binderhub_url: {}'.format(binder_conf['binderhub_url']))
# Ensure we have at least one dependency file
# Need at least one of these three files
required_reqs_files = ['requirements.txt', 'environment.yml', 'Dockerfile']
path_reqs = binder_conf['dependencies']
if isinstance(path_reqs, basestring):
path_reqs = [path_reqs]
binder_conf['dependencies'] = path_reqs
elif not isinstance(path_reqs, (list, tuple)):
raise ValueError("`dependencies` value should be a list of strings. "
"Got type {}.".format(type(path_reqs)))
binder_conf['notebooks_dir'] = binder_conf.get('notebooks_dir',
'notebooks')
path_reqs_filenames = [os.path.basename(ii) for ii in path_reqs]
if not any(ii in path_reqs_filenames for ii in required_reqs_files):
raise ValueError(
'Did not find one of `requirements.txt` or `environment.yml` '
'in the "dependencies" section of the binder configuration '
'for sphinx-gallery. A path to at least one of these files '
'must exist in your Binder dependencies.')
return binder_conf | [
"def",
"check_binder_conf",
"(",
"binder_conf",
")",
":",
"# Grab the configuration and return None if it's not configured",
"binder_conf",
"=",
"{",
"}",
"if",
"binder_conf",
"is",
"None",
"else",
"binder_conf",
"if",
"not",
"isinstance",
"(",
"binder_conf",
",",
"dict... | Check to make sure that the Binder configuration is correct. | [
"Check",
"to",
"make",
"sure",
"that",
"the",
"Binder",
"configuration",
"is",
"correct",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/binder.py#L199-L257 |
230,125 | sphinx-gallery/sphinx-gallery | sphinx_gallery/py_source_parser.py | parse_source_file | def parse_source_file(filename):
"""Parse source file into AST node
Parameters
----------
filename : str
File path
Returns
-------
node : AST node
content : utf-8 encoded string
"""
# can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't
# work with unicode strings in Python2.7 "SyntaxError: encoding
# declaration in Unicode string" In python 2.7 the string can't be
# encoded and have information about its encoding. That is particularly
# problematic since source files include in their header information
# about the file encoding.
# Minimal example to fail: ast.parse(u'# -*- coding: utf-8 -*-')
with open(filename, 'rb') as fid:
content = fid.read()
# change from Windows format to UNIX for uniformity
content = content.replace(b'\r\n', b'\n')
try:
node = ast.parse(content)
return node, content.decode('utf-8')
except SyntaxError:
return None, content.decode('utf-8') | python | def parse_source_file(filename):
# can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't
# work with unicode strings in Python2.7 "SyntaxError: encoding
# declaration in Unicode string" In python 2.7 the string can't be
# encoded and have information about its encoding. That is particularly
# problematic since source files include in their header information
# about the file encoding.
# Minimal example to fail: ast.parse(u'# -*- coding: utf-8 -*-')
with open(filename, 'rb') as fid:
content = fid.read()
# change from Windows format to UNIX for uniformity
content = content.replace(b'\r\n', b'\n')
try:
node = ast.parse(content)
return node, content.decode('utf-8')
except SyntaxError:
return None, content.decode('utf-8') | [
"def",
"parse_source_file",
"(",
"filename",
")",
":",
"# can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't",
"# work with unicode strings in Python2.7 \"SyntaxError: encoding",
"# declaration in Unicode string\" In python 2.7 the string can't be",
"# encoded and have information ... | Parse source file into AST node
Parameters
----------
filename : str
File path
Returns
-------
node : AST node
content : utf-8 encoded string | [
"Parse",
"source",
"file",
"into",
"AST",
"node"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/py_source_parser.py#L30-L61 |
230,126 | sphinx-gallery/sphinx-gallery | sphinx_gallery/py_source_parser.py | get_docstring_and_rest | def get_docstring_and_rest(filename):
"""Separate ``filename`` content between docstring and the rest
Strongly inspired from ast.get_docstring.
Returns
-------
docstring : str
docstring of ``filename``
rest : str
``filename`` content without the docstring
"""
node, content = parse_source_file(filename)
if node is None:
return SYNTAX_ERROR_DOCSTRING, content, 1
if not isinstance(node, ast.Module):
raise TypeError("This function only supports modules. "
"You provided {0}".format(node.__class__.__name__))
if not (node.body and isinstance(node.body[0], ast.Expr) and
isinstance(node.body[0].value, ast.Str)):
raise ValueError(('Could not find docstring in file "{0}". '
'A docstring is required by sphinx-gallery '
'unless the file is ignored by "ignore_pattern"')
.format(filename))
if LooseVersion(sys.version) >= LooseVersion('3.7'):
docstring = ast.get_docstring(node)
assert docstring is not None # should be guaranteed above
# This is just for backward compat
if len(node.body[0].value.s) and node.body[0].value.s[0] == '\n':
# just for strict backward compat here
docstring = '\n' + docstring
ts = tokenize.tokenize(BytesIO(content.encode()).readline)
# find the first string according to the tokenizer and get its end row
for tk in ts:
if tk.exact_type == 3:
lineno, _ = tk.end
break
else:
lineno = 0
else:
# this block can be removed when python 3.6 support is dropped
docstring_node = node.body[0]
docstring = docstring_node.value.s
# python2.7: Code was read in bytes needs decoding to utf-8
# unless future unicode_literals is imported in source which
# make ast output unicode strings
if hasattr(docstring, 'decode') and not isinstance(docstring, unicode):
docstring = docstring.decode('utf-8')
lineno = docstring_node.lineno # The last line of the string.
# This get the content of the file after the docstring last line
# Note: 'maxsplit' argument is not a keyword argument in python2
rest = '\n'.join(content.split('\n')[lineno:])
lineno += 1
return docstring, rest, lineno | python | def get_docstring_and_rest(filename):
node, content = parse_source_file(filename)
if node is None:
return SYNTAX_ERROR_DOCSTRING, content, 1
if not isinstance(node, ast.Module):
raise TypeError("This function only supports modules. "
"You provided {0}".format(node.__class__.__name__))
if not (node.body and isinstance(node.body[0], ast.Expr) and
isinstance(node.body[0].value, ast.Str)):
raise ValueError(('Could not find docstring in file "{0}". '
'A docstring is required by sphinx-gallery '
'unless the file is ignored by "ignore_pattern"')
.format(filename))
if LooseVersion(sys.version) >= LooseVersion('3.7'):
docstring = ast.get_docstring(node)
assert docstring is not None # should be guaranteed above
# This is just for backward compat
if len(node.body[0].value.s) and node.body[0].value.s[0] == '\n':
# just for strict backward compat here
docstring = '\n' + docstring
ts = tokenize.tokenize(BytesIO(content.encode()).readline)
# find the first string according to the tokenizer and get its end row
for tk in ts:
if tk.exact_type == 3:
lineno, _ = tk.end
break
else:
lineno = 0
else:
# this block can be removed when python 3.6 support is dropped
docstring_node = node.body[0]
docstring = docstring_node.value.s
# python2.7: Code was read in bytes needs decoding to utf-8
# unless future unicode_literals is imported in source which
# make ast output unicode strings
if hasattr(docstring, 'decode') and not isinstance(docstring, unicode):
docstring = docstring.decode('utf-8')
lineno = docstring_node.lineno # The last line of the string.
# This get the content of the file after the docstring last line
# Note: 'maxsplit' argument is not a keyword argument in python2
rest = '\n'.join(content.split('\n')[lineno:])
lineno += 1
return docstring, rest, lineno | [
"def",
"get_docstring_and_rest",
"(",
"filename",
")",
":",
"node",
",",
"content",
"=",
"parse_source_file",
"(",
"filename",
")",
"if",
"node",
"is",
"None",
":",
"return",
"SYNTAX_ERROR_DOCSTRING",
",",
"content",
",",
"1",
"if",
"not",
"isinstance",
"(",
... | Separate ``filename`` content between docstring and the rest
Strongly inspired from ast.get_docstring.
Returns
-------
docstring : str
docstring of ``filename``
rest : str
``filename`` content without the docstring | [
"Separate",
"filename",
"content",
"between",
"docstring",
"and",
"the",
"rest"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/py_source_parser.py#L64-L121 |
230,127 | sphinx-gallery/sphinx-gallery | sphinx_gallery/py_source_parser.py | extract_file_config | def extract_file_config(content):
"""
Pull out the file-specific config specified in the docstring.
"""
prop_pat = re.compile(
r"^\s*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)\s*$",
re.MULTILINE)
file_conf = {}
for match in re.finditer(prop_pat, content):
name = match.group(1)
value = match.group(2)
try:
value = ast.literal_eval(value)
except (SyntaxError, ValueError):
logger.warning(
'Sphinx-gallery option %s was passed invalid value %s',
name, value)
else:
file_conf[name] = value
return file_conf | python | def extract_file_config(content):
prop_pat = re.compile(
r"^\s*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)\s*$",
re.MULTILINE)
file_conf = {}
for match in re.finditer(prop_pat, content):
name = match.group(1)
value = match.group(2)
try:
value = ast.literal_eval(value)
except (SyntaxError, ValueError):
logger.warning(
'Sphinx-gallery option %s was passed invalid value %s',
name, value)
else:
file_conf[name] = value
return file_conf | [
"def",
"extract_file_config",
"(",
"content",
")",
":",
"prop_pat",
"=",
"re",
".",
"compile",
"(",
"r\"^\\s*#\\s*sphinx_gallery_([A-Za-z0-9_]+)\\s*=\\s*(.+)\\s*$\"",
",",
"re",
".",
"MULTILINE",
")",
"file_conf",
"=",
"{",
"}",
"for",
"match",
"in",
"re",
".",
... | Pull out the file-specific config specified in the docstring. | [
"Pull",
"out",
"the",
"file",
"-",
"specific",
"config",
"specified",
"in",
"the",
"docstring",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/py_source_parser.py#L124-L144 |
230,128 | sphinx-gallery/sphinx-gallery | sphinx_gallery/py_source_parser.py | split_code_and_text_blocks | def split_code_and_text_blocks(source_file):
"""Return list with source file separated into code and text blocks.
Returns
-------
file_conf : dict
File-specific settings given in source file comments as:
``# sphinx_gallery_<name> = <value>``
blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
the corresponding content string of block and the leading line number
"""
docstring, rest_of_content, lineno = get_docstring_and_rest(source_file)
blocks = [('text', docstring, 1)]
file_conf = extract_file_config(rest_of_content)
pattern = re.compile(
r'(?P<header_line>^#{20,}.*)\s(?P<text_content>(?:^#.*\s)*)',
flags=re.M)
sub_pat = re.compile('^#', flags=re.M)
pos_so_far = 0
for match in re.finditer(pattern, rest_of_content):
code_block_content = rest_of_content[pos_so_far:match.start()]
if code_block_content.strip():
blocks.append(('code', code_block_content, lineno))
lineno += code_block_content.count('\n')
lineno += 1 # Ignored header line of hashes.
text_content = match.group('text_content')
text_block_content = dedent(re.sub(sub_pat, '', text_content)).lstrip()
if text_block_content.strip():
blocks.append(('text', text_block_content, lineno))
lineno += text_content.count('\n')
pos_so_far = match.end()
remaining_content = rest_of_content[pos_so_far:]
if remaining_content.strip():
blocks.append(('code', remaining_content, lineno))
return file_conf, blocks | python | def split_code_and_text_blocks(source_file):
docstring, rest_of_content, lineno = get_docstring_and_rest(source_file)
blocks = [('text', docstring, 1)]
file_conf = extract_file_config(rest_of_content)
pattern = re.compile(
r'(?P<header_line>^#{20,}.*)\s(?P<text_content>(?:^#.*\s)*)',
flags=re.M)
sub_pat = re.compile('^#', flags=re.M)
pos_so_far = 0
for match in re.finditer(pattern, rest_of_content):
code_block_content = rest_of_content[pos_so_far:match.start()]
if code_block_content.strip():
blocks.append(('code', code_block_content, lineno))
lineno += code_block_content.count('\n')
lineno += 1 # Ignored header line of hashes.
text_content = match.group('text_content')
text_block_content = dedent(re.sub(sub_pat, '', text_content)).lstrip()
if text_block_content.strip():
blocks.append(('text', text_block_content, lineno))
lineno += text_content.count('\n')
pos_so_far = match.end()
remaining_content = rest_of_content[pos_so_far:]
if remaining_content.strip():
blocks.append(('code', remaining_content, lineno))
return file_conf, blocks | [
"def",
"split_code_and_text_blocks",
"(",
"source_file",
")",
":",
"docstring",
",",
"rest_of_content",
",",
"lineno",
"=",
"get_docstring_and_rest",
"(",
"source_file",
")",
"blocks",
"=",
"[",
"(",
"'text'",
",",
"docstring",
",",
"1",
")",
"]",
"file_conf",
... | Return list with source file separated into code and text blocks.
Returns
-------
file_conf : dict
File-specific settings given in source file comments as:
``# sphinx_gallery_<name> = <value>``
blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
the corresponding content string of block and the leading line number | [
"Return",
"list",
"with",
"source",
"file",
"separated",
"into",
"code",
"and",
"text",
"blocks",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/py_source_parser.py#L147-L190 |
230,129 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | parse_config | def parse_config(app):
"""Process the Sphinx Gallery configuration"""
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
src_dir = app.builder.srcdir
abort_on_example_error = app.builder.config.abort_on_example_error
lang = app.builder.config.highlight_language
gallery_conf = _complete_gallery_conf(
app.config.sphinx_gallery_conf, src_dir, plot_gallery,
abort_on_example_error, lang, app.builder.name)
# this assures I can call the config in other places
app.config.sphinx_gallery_conf = gallery_conf
app.config.html_static_path.append(glr_path_static())
return gallery_conf | python | def parse_config(app):
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
src_dir = app.builder.srcdir
abort_on_example_error = app.builder.config.abort_on_example_error
lang = app.builder.config.highlight_language
gallery_conf = _complete_gallery_conf(
app.config.sphinx_gallery_conf, src_dir, plot_gallery,
abort_on_example_error, lang, app.builder.name)
# this assures I can call the config in other places
app.config.sphinx_gallery_conf = gallery_conf
app.config.html_static_path.append(glr_path_static())
return gallery_conf | [
"def",
"parse_config",
"(",
"app",
")",
":",
"try",
":",
"plot_gallery",
"=",
"eval",
"(",
"app",
".",
"builder",
".",
"config",
".",
"plot_gallery",
")",
"except",
"TypeError",
":",
"plot_gallery",
"=",
"bool",
"(",
"app",
".",
"builder",
".",
"config",... | Process the Sphinx Gallery configuration | [
"Process",
"the",
"Sphinx",
"Gallery",
"configuration"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L81-L97 |
230,130 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | get_subsections | def get_subsections(srcdir, examples_dir, sortkey):
"""Return the list of subsections of a gallery
Parameters
----------
srcdir : str
absolute path to directory containing conf.py
examples_dir : str
path to the examples directory relative to conf.py
sortkey : callable
The sort key to use.
Returns
-------
out : list
sorted list of gallery subsection folder names
"""
subfolders = [subfolder for subfolder in os.listdir(examples_dir)
if os.path.exists(os.path.join(
examples_dir, subfolder, 'README.txt'))]
base_examples_dir_path = os.path.relpath(examples_dir, srcdir)
subfolders_with_path = [os.path.join(base_examples_dir_path, item)
for item in subfolders]
sorted_subfolders = sorted(subfolders_with_path, key=sortkey)
return [subfolders[i] for i in [subfolders_with_path.index(item)
for item in sorted_subfolders]] | python | def get_subsections(srcdir, examples_dir, sortkey):
subfolders = [subfolder for subfolder in os.listdir(examples_dir)
if os.path.exists(os.path.join(
examples_dir, subfolder, 'README.txt'))]
base_examples_dir_path = os.path.relpath(examples_dir, srcdir)
subfolders_with_path = [os.path.join(base_examples_dir_path, item)
for item in subfolders]
sorted_subfolders = sorted(subfolders_with_path, key=sortkey)
return [subfolders[i] for i in [subfolders_with_path.index(item)
for item in sorted_subfolders]] | [
"def",
"get_subsections",
"(",
"srcdir",
",",
"examples_dir",
",",
"sortkey",
")",
":",
"subfolders",
"=",
"[",
"subfolder",
"for",
"subfolder",
"in",
"os",
".",
"listdir",
"(",
"examples_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",... | Return the list of subsections of a gallery
Parameters
----------
srcdir : str
absolute path to directory containing conf.py
examples_dir : str
path to the examples directory relative to conf.py
sortkey : callable
The sort key to use.
Returns
-------
out : list
sorted list of gallery subsection folder names | [
"Return",
"the",
"list",
"of",
"subsections",
"of",
"a",
"gallery"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L186-L213 |
230,131 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | _prepare_sphx_glr_dirs | def _prepare_sphx_glr_dirs(gallery_conf, srcdir):
"""Creates necessary folders for sphinx_gallery files """
examples_dirs = gallery_conf['examples_dirs']
gallery_dirs = gallery_conf['gallery_dirs']
if not isinstance(examples_dirs, list):
examples_dirs = [examples_dirs]
if not isinstance(gallery_dirs, list):
gallery_dirs = [gallery_dirs]
if bool(gallery_conf['backreferences_dir']):
backreferences_dir = os.path.join(
srcdir, gallery_conf['backreferences_dir'])
if not os.path.exists(backreferences_dir):
os.makedirs(backreferences_dir)
return list(zip(examples_dirs, gallery_dirs)) | python | def _prepare_sphx_glr_dirs(gallery_conf, srcdir):
examples_dirs = gallery_conf['examples_dirs']
gallery_dirs = gallery_conf['gallery_dirs']
if not isinstance(examples_dirs, list):
examples_dirs = [examples_dirs]
if not isinstance(gallery_dirs, list):
gallery_dirs = [gallery_dirs]
if bool(gallery_conf['backreferences_dir']):
backreferences_dir = os.path.join(
srcdir, gallery_conf['backreferences_dir'])
if not os.path.exists(backreferences_dir):
os.makedirs(backreferences_dir)
return list(zip(examples_dirs, gallery_dirs)) | [
"def",
"_prepare_sphx_glr_dirs",
"(",
"gallery_conf",
",",
"srcdir",
")",
":",
"examples_dirs",
"=",
"gallery_conf",
"[",
"'examples_dirs'",
"]",
"gallery_dirs",
"=",
"gallery_conf",
"[",
"'gallery_dirs'",
"]",
"if",
"not",
"isinstance",
"(",
"examples_dirs",
",",
... | Creates necessary folders for sphinx_gallery files | [
"Creates",
"necessary",
"folders",
"for",
"sphinx_gallery",
"files"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L216-L233 |
230,132 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | generate_gallery_rst | def generate_gallery_rst(app):
"""Generate the Main examples gallery reStructuredText
Start the sphinx-gallery configuration and recursively scan the examples
directories in order to populate the examples gallery
"""
logger.info('generating gallery...', color='white')
gallery_conf = parse_config(app)
seen_backrefs = set()
computation_times = []
workdirs = _prepare_sphx_glr_dirs(gallery_conf,
app.builder.srcdir)
# Check for duplicate filenames to make sure linking works as expected
examples_dirs = [ex_dir for ex_dir, _ in workdirs]
files = collect_gallery_files(examples_dirs)
check_duplicate_filenames(files)
for examples_dir, gallery_dir in workdirs:
examples_dir = os.path.join(app.builder.srcdir, examples_dir)
gallery_dir = os.path.join(app.builder.srcdir, gallery_dir)
if not os.path.exists(os.path.join(examples_dir, 'README.txt')):
raise FileNotFoundError("Main example directory {0} does not "
"have a README.txt file. Please write "
"one to introduce your gallery."
.format(examples_dir))
# Here we don't use an os.walk, but we recurse only twice: flat is
# better than nested.
this_fhindex, this_computation_times = generate_dir_rst(
examples_dir, gallery_dir, gallery_conf, seen_backrefs)
computation_times += this_computation_times
write_computation_times(gallery_conf, gallery_dir,
this_computation_times)
# we create an index.rst with all examples
index_rst_new = os.path.join(gallery_dir, 'index.rst.new')
with codecs.open(index_rst_new, 'w', encoding='utf-8') as fhindex:
# :orphan: to suppress "not included in TOCTREE" sphinx warnings
fhindex.write(":orphan:\n\n" + this_fhindex)
for subsection in get_subsections(
app.builder.srcdir, examples_dir,
gallery_conf['subsection_order']):
src_dir = os.path.join(examples_dir, subsection)
target_dir = os.path.join(gallery_dir, subsection)
this_fhindex, this_computation_times = \
generate_dir_rst(src_dir, target_dir, gallery_conf,
seen_backrefs)
fhindex.write(this_fhindex)
computation_times += this_computation_times
write_computation_times(gallery_conf, target_dir,
this_computation_times)
if gallery_conf['download_all_examples']:
download_fhindex = generate_zipfiles(gallery_dir)
fhindex.write(download_fhindex)
fhindex.write(SPHX_GLR_SIG)
_replace_md5(index_rst_new)
finalize_backreferences(seen_backrefs, gallery_conf)
if gallery_conf['plot_gallery']:
logger.info("computation time summary:", color='white')
for time_elapsed, fname in sorted(computation_times, reverse=True):
fname = os.path.relpath(fname,
os.path.normpath(gallery_conf['src_dir']))
if time_elapsed is not None:
if time_elapsed >= gallery_conf['min_reported_time']:
logger.info(" - %s: %.2g sec", fname, time_elapsed)
else:
logger.info(" - %s: not run", fname)
# Also create a junit.xml file, useful e.g. on CircleCI
write_junit_xml(gallery_conf, app.builder.outdir, computation_times) | python | def generate_gallery_rst(app):
logger.info('generating gallery...', color='white')
gallery_conf = parse_config(app)
seen_backrefs = set()
computation_times = []
workdirs = _prepare_sphx_glr_dirs(gallery_conf,
app.builder.srcdir)
# Check for duplicate filenames to make sure linking works as expected
examples_dirs = [ex_dir for ex_dir, _ in workdirs]
files = collect_gallery_files(examples_dirs)
check_duplicate_filenames(files)
for examples_dir, gallery_dir in workdirs:
examples_dir = os.path.join(app.builder.srcdir, examples_dir)
gallery_dir = os.path.join(app.builder.srcdir, gallery_dir)
if not os.path.exists(os.path.join(examples_dir, 'README.txt')):
raise FileNotFoundError("Main example directory {0} does not "
"have a README.txt file. Please write "
"one to introduce your gallery."
.format(examples_dir))
# Here we don't use an os.walk, but we recurse only twice: flat is
# better than nested.
this_fhindex, this_computation_times = generate_dir_rst(
examples_dir, gallery_dir, gallery_conf, seen_backrefs)
computation_times += this_computation_times
write_computation_times(gallery_conf, gallery_dir,
this_computation_times)
# we create an index.rst with all examples
index_rst_new = os.path.join(gallery_dir, 'index.rst.new')
with codecs.open(index_rst_new, 'w', encoding='utf-8') as fhindex:
# :orphan: to suppress "not included in TOCTREE" sphinx warnings
fhindex.write(":orphan:\n\n" + this_fhindex)
for subsection in get_subsections(
app.builder.srcdir, examples_dir,
gallery_conf['subsection_order']):
src_dir = os.path.join(examples_dir, subsection)
target_dir = os.path.join(gallery_dir, subsection)
this_fhindex, this_computation_times = \
generate_dir_rst(src_dir, target_dir, gallery_conf,
seen_backrefs)
fhindex.write(this_fhindex)
computation_times += this_computation_times
write_computation_times(gallery_conf, target_dir,
this_computation_times)
if gallery_conf['download_all_examples']:
download_fhindex = generate_zipfiles(gallery_dir)
fhindex.write(download_fhindex)
fhindex.write(SPHX_GLR_SIG)
_replace_md5(index_rst_new)
finalize_backreferences(seen_backrefs, gallery_conf)
if gallery_conf['plot_gallery']:
logger.info("computation time summary:", color='white')
for time_elapsed, fname in sorted(computation_times, reverse=True):
fname = os.path.relpath(fname,
os.path.normpath(gallery_conf['src_dir']))
if time_elapsed is not None:
if time_elapsed >= gallery_conf['min_reported_time']:
logger.info(" - %s: %.2g sec", fname, time_elapsed)
else:
logger.info(" - %s: not run", fname)
# Also create a junit.xml file, useful e.g. on CircleCI
write_junit_xml(gallery_conf, app.builder.outdir, computation_times) | [
"def",
"generate_gallery_rst",
"(",
"app",
")",
":",
"logger",
".",
"info",
"(",
"'generating gallery...'",
",",
"color",
"=",
"'white'",
")",
"gallery_conf",
"=",
"parse_config",
"(",
"app",
")",
"seen_backrefs",
"=",
"set",
"(",
")",
"computation_times",
"="... | Generate the Main examples gallery reStructuredText
Start the sphinx-gallery configuration and recursively scan the examples
directories in order to populate the examples gallery | [
"Generate",
"the",
"Main",
"examples",
"gallery",
"reStructuredText"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L236-L315 |
230,133 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | _sec_to_readable | def _sec_to_readable(t):
"""Convert a number of seconds to a more readable representation."""
# This will only work for < 1 day execution time
# And we reserve 2 digits for minutes because presumably
# there aren't many > 99 minute scripts, but occasionally some
# > 9 minute ones
t = datetime(1, 1, 1) + timedelta(seconds=t)
t = '{0:02d}:{1:02d}.{2:03d}'.format(
t.hour * 60 + t.minute, t.second,
int(round(t.microsecond / 1000.)))
return t | python | def _sec_to_readable(t):
# This will only work for < 1 day execution time
# And we reserve 2 digits for minutes because presumably
# there aren't many > 99 minute scripts, but occasionally some
# > 9 minute ones
t = datetime(1, 1, 1) + timedelta(seconds=t)
t = '{0:02d}:{1:02d}.{2:03d}'.format(
t.hour * 60 + t.minute, t.second,
int(round(t.microsecond / 1000.)))
return t | [
"def",
"_sec_to_readable",
"(",
"t",
")",
":",
"# This will only work for < 1 day execution time",
"# And we reserve 2 digits for minutes because presumably",
"# there aren't many > 99 minute scripts, but occasionally some",
"# > 9 minute ones",
"t",
"=",
"datetime",
"(",
"1",
",",
"... | Convert a number of seconds to a more readable representation. | [
"Convert",
"a",
"number",
"of",
"seconds",
"to",
"a",
"more",
"readable",
"representation",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L328-L338 |
230,134 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | touch_empty_backreferences | def touch_empty_backreferences(app, what, name, obj, options, lines):
"""Generate empty back-reference example files
This avoids inclusion errors/warnings if there are no gallery
examples for a class / module that is being parsed by autodoc"""
if not bool(app.config.sphinx_gallery_conf['backreferences_dir']):
return
examples_path = os.path.join(app.srcdir,
app.config.sphinx_gallery_conf[
"backreferences_dir"],
"%s.examples" % name)
if not os.path.exists(examples_path):
# touch file
open(examples_path, 'w').close() | python | def touch_empty_backreferences(app, what, name, obj, options, lines):
if not bool(app.config.sphinx_gallery_conf['backreferences_dir']):
return
examples_path = os.path.join(app.srcdir,
app.config.sphinx_gallery_conf[
"backreferences_dir"],
"%s.examples" % name)
if not os.path.exists(examples_path):
# touch file
open(examples_path, 'w').close() | [
"def",
"touch_empty_backreferences",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"if",
"not",
"bool",
"(",
"app",
".",
"config",
".",
"sphinx_gallery_conf",
"[",
"'backreferences_dir'",
"]",
")",
":",
"return",... | Generate empty back-reference example files
This avoids inclusion errors/warnings if there are no gallery
examples for a class / module that is being parsed by autodoc | [
"Generate",
"empty",
"back",
"-",
"reference",
"example",
"files"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L416-L432 |
230,135 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | _parse_failures | def _parse_failures(gallery_conf):
"""Split the failures."""
failing_examples = set(gallery_conf['failing_examples'].keys())
expected_failing_examples = set(
os.path.normpath(os.path.join(gallery_conf['src_dir'], path))
for path in gallery_conf['expected_failing_examples'])
failing_as_expected = failing_examples.intersection(
expected_failing_examples)
failing_unexpectedly = failing_examples.difference(
expected_failing_examples)
passing_unexpectedly = expected_failing_examples.difference(
failing_examples)
# filter from examples actually run
passing_unexpectedly = [
src_file for src_file in passing_unexpectedly
if re.search(gallery_conf.get('filename_pattern'), src_file)]
return failing_as_expected, failing_unexpectedly, passing_unexpectedly | python | def _parse_failures(gallery_conf):
failing_examples = set(gallery_conf['failing_examples'].keys())
expected_failing_examples = set(
os.path.normpath(os.path.join(gallery_conf['src_dir'], path))
for path in gallery_conf['expected_failing_examples'])
failing_as_expected = failing_examples.intersection(
expected_failing_examples)
failing_unexpectedly = failing_examples.difference(
expected_failing_examples)
passing_unexpectedly = expected_failing_examples.difference(
failing_examples)
# filter from examples actually run
passing_unexpectedly = [
src_file for src_file in passing_unexpectedly
if re.search(gallery_conf.get('filename_pattern'), src_file)]
return failing_as_expected, failing_unexpectedly, passing_unexpectedly | [
"def",
"_parse_failures",
"(",
"gallery_conf",
")",
":",
"failing_examples",
"=",
"set",
"(",
"gallery_conf",
"[",
"'failing_examples'",
"]",
".",
"keys",
"(",
")",
")",
"expected_failing_examples",
"=",
"set",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"... | Split the failures. | [
"Split",
"the",
"failures",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L435-L451 |
230,136 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | summarize_failing_examples | def summarize_failing_examples(app, exception):
"""Collects the list of falling examples and prints them with a traceback.
Raises ValueError if there where failing examples.
"""
if exception is not None:
return
# Under no-plot Examples are not run so nothing to summarize
if not app.config.sphinx_gallery_conf['plot_gallery']:
logger.info('Sphinx-gallery gallery_conf["plot_gallery"] was '
'False, so no examples were executed.', color='brown')
return
gallery_conf = app.config.sphinx_gallery_conf
failing_as_expected, failing_unexpectedly, passing_unexpectedly = \
_parse_failures(gallery_conf)
if failing_as_expected:
logger.info("Examples failing as expected:", color='brown')
for fail_example in failing_as_expected:
logger.info('%s failed leaving traceback:', fail_example,
color='brown')
logger.info(gallery_conf['failing_examples'][fail_example],
color='brown')
fail_msgs = []
if failing_unexpectedly:
fail_msgs.append(red("Unexpected failing examples:"))
for fail_example in failing_unexpectedly:
fail_msgs.append(fail_example + ' failed leaving traceback:\n' +
gallery_conf['failing_examples'][fail_example] +
'\n')
if passing_unexpectedly:
fail_msgs.append(red("Examples expected to fail, but not failing:\n") +
"Please remove these examples from\n" +
"sphinx_gallery_conf['expected_failing_examples']\n" +
"in your conf.py file"
"\n".join(passing_unexpectedly))
# standard message
n_good = len(gallery_conf['passing_examples'])
n_tot = len(gallery_conf['failing_examples']) + n_good
n_stale = len(gallery_conf['stale_examples'])
logger.info('\nSphinx-gallery successfully executed %d out of %d '
'file%s subselected by:\n\n'
' gallery_conf["filename_pattern"] = %r\n'
' gallery_conf["ignore_pattern"] = %r\n'
'\nafter excluding %d file%s that had previously been run '
'(based on MD5).\n'
% (n_good, n_tot, 's' if n_tot != 1 else '',
gallery_conf['filename_pattern'],
gallery_conf['ignore_pattern'],
n_stale, 's' if n_stale != 1 else '',
),
color='brown')
if fail_msgs:
raise ValueError("Here is a summary of the problems encountered when "
"running the examples\n\n" + "\n".join(fail_msgs) +
"\n" + "-" * 79) | python | def summarize_failing_examples(app, exception):
if exception is not None:
return
# Under no-plot Examples are not run so nothing to summarize
if not app.config.sphinx_gallery_conf['plot_gallery']:
logger.info('Sphinx-gallery gallery_conf["plot_gallery"] was '
'False, so no examples were executed.', color='brown')
return
gallery_conf = app.config.sphinx_gallery_conf
failing_as_expected, failing_unexpectedly, passing_unexpectedly = \
_parse_failures(gallery_conf)
if failing_as_expected:
logger.info("Examples failing as expected:", color='brown')
for fail_example in failing_as_expected:
logger.info('%s failed leaving traceback:', fail_example,
color='brown')
logger.info(gallery_conf['failing_examples'][fail_example],
color='brown')
fail_msgs = []
if failing_unexpectedly:
fail_msgs.append(red("Unexpected failing examples:"))
for fail_example in failing_unexpectedly:
fail_msgs.append(fail_example + ' failed leaving traceback:\n' +
gallery_conf['failing_examples'][fail_example] +
'\n')
if passing_unexpectedly:
fail_msgs.append(red("Examples expected to fail, but not failing:\n") +
"Please remove these examples from\n" +
"sphinx_gallery_conf['expected_failing_examples']\n" +
"in your conf.py file"
"\n".join(passing_unexpectedly))
# standard message
n_good = len(gallery_conf['passing_examples'])
n_tot = len(gallery_conf['failing_examples']) + n_good
n_stale = len(gallery_conf['stale_examples'])
logger.info('\nSphinx-gallery successfully executed %d out of %d '
'file%s subselected by:\n\n'
' gallery_conf["filename_pattern"] = %r\n'
' gallery_conf["ignore_pattern"] = %r\n'
'\nafter excluding %d file%s that had previously been run '
'(based on MD5).\n'
% (n_good, n_tot, 's' if n_tot != 1 else '',
gallery_conf['filename_pattern'],
gallery_conf['ignore_pattern'],
n_stale, 's' if n_stale != 1 else '',
),
color='brown')
if fail_msgs:
raise ValueError("Here is a summary of the problems encountered when "
"running the examples\n\n" + "\n".join(fail_msgs) +
"\n" + "-" * 79) | [
"def",
"summarize_failing_examples",
"(",
"app",
",",
"exception",
")",
":",
"if",
"exception",
"is",
"not",
"None",
":",
"return",
"# Under no-plot Examples are not run so nothing to summarize",
"if",
"not",
"app",
".",
"config",
".",
"sphinx_gallery_conf",
"[",
"'pl... | Collects the list of falling examples and prints them with a traceback.
Raises ValueError if there where failing examples. | [
"Collects",
"the",
"list",
"of",
"falling",
"examples",
"and",
"prints",
"them",
"with",
"a",
"traceback",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L454-L515 |
230,137 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | collect_gallery_files | def collect_gallery_files(examples_dirs):
"""Collect python files from the gallery example directories."""
files = []
for example_dir in examples_dirs:
for root, dirnames, filenames in os.walk(example_dir):
for filename in filenames:
if filename.endswith('.py'):
files.append(os.path.join(root, filename))
return files | python | def collect_gallery_files(examples_dirs):
files = []
for example_dir in examples_dirs:
for root, dirnames, filenames in os.walk(example_dir):
for filename in filenames:
if filename.endswith('.py'):
files.append(os.path.join(root, filename))
return files | [
"def",
"collect_gallery_files",
"(",
"examples_dirs",
")",
":",
"files",
"=",
"[",
"]",
"for",
"example_dir",
"in",
"examples_dirs",
":",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"example_dir",
")",
":",
"for",
"filen... | Collect python files from the gallery example directories. | [
"Collect",
"python",
"files",
"from",
"the",
"gallery",
"example",
"directories",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L518-L526 |
230,138 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | check_duplicate_filenames | def check_duplicate_filenames(files):
"""Check for duplicate filenames across gallery directories."""
# Check whether we'll have duplicates
used_names = set()
dup_names = list()
for this_file in files:
this_fname = os.path.basename(this_file)
if this_fname in used_names:
dup_names.append(this_file)
else:
used_names.add(this_fname)
if len(dup_names) > 0:
logger.warning(
'Duplicate file name(s) found. Having duplicate file names will '
'break some links. List of files: {}'.format(sorted(dup_names),)) | python | def check_duplicate_filenames(files):
# Check whether we'll have duplicates
used_names = set()
dup_names = list()
for this_file in files:
this_fname = os.path.basename(this_file)
if this_fname in used_names:
dup_names.append(this_file)
else:
used_names.add(this_fname)
if len(dup_names) > 0:
logger.warning(
'Duplicate file name(s) found. Having duplicate file names will '
'break some links. List of files: {}'.format(sorted(dup_names),)) | [
"def",
"check_duplicate_filenames",
"(",
"files",
")",
":",
"# Check whether we'll have duplicates",
"used_names",
"=",
"set",
"(",
")",
"dup_names",
"=",
"list",
"(",
")",
"for",
"this_file",
"in",
"files",
":",
"this_fname",
"=",
"os",
".",
"path",
".",
"bas... | Check for duplicate filenames across gallery directories. | [
"Check",
"for",
"duplicate",
"filenames",
"across",
"gallery",
"directories",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L529-L545 |
230,139 | sphinx-gallery/sphinx-gallery | sphinx_gallery/gen_gallery.py | setup | def setup(app):
"""Setup sphinx-gallery sphinx extension"""
sphinx_compatibility._app = app
app.add_config_value('sphinx_gallery_conf', DEFAULT_GALLERY_CONF, 'html')
for key in ['plot_gallery', 'abort_on_example_error']:
app.add_config_value(key, get_default_config_value(key), 'html')
try:
app.add_css_file('gallery.css')
except AttributeError: # Sphinx < 1.8
app.add_stylesheet('gallery.css')
# Sphinx < 1.6 calls it `_extensions`, >= 1.6 is `extensions`.
extensions_attr = '_extensions' if hasattr(
app, '_extensions') else 'extensions'
if 'sphinx.ext.autodoc' in getattr(app, extensions_attr):
app.connect('autodoc-process-docstring', touch_empty_backreferences)
app.connect('builder-inited', generate_gallery_rst)
app.connect('build-finished', copy_binder_files)
app.connect('build-finished', summarize_failing_examples)
app.connect('build-finished', embed_code_links)
metadata = {'parallel_read_safe': True,
'parallel_write_safe': False,
'version': _sg_version}
return metadata | python | def setup(app):
sphinx_compatibility._app = app
app.add_config_value('sphinx_gallery_conf', DEFAULT_GALLERY_CONF, 'html')
for key in ['plot_gallery', 'abort_on_example_error']:
app.add_config_value(key, get_default_config_value(key), 'html')
try:
app.add_css_file('gallery.css')
except AttributeError: # Sphinx < 1.8
app.add_stylesheet('gallery.css')
# Sphinx < 1.6 calls it `_extensions`, >= 1.6 is `extensions`.
extensions_attr = '_extensions' if hasattr(
app, '_extensions') else 'extensions'
if 'sphinx.ext.autodoc' in getattr(app, extensions_attr):
app.connect('autodoc-process-docstring', touch_empty_backreferences)
app.connect('builder-inited', generate_gallery_rst)
app.connect('build-finished', copy_binder_files)
app.connect('build-finished', summarize_failing_examples)
app.connect('build-finished', embed_code_links)
metadata = {'parallel_read_safe': True,
'parallel_write_safe': False,
'version': _sg_version}
return metadata | [
"def",
"setup",
"(",
"app",
")",
":",
"sphinx_compatibility",
".",
"_app",
"=",
"app",
"app",
".",
"add_config_value",
"(",
"'sphinx_gallery_conf'",
",",
"DEFAULT_GALLERY_CONF",
",",
"'html'",
")",
"for",
"key",
"in",
"[",
"'plot_gallery'",
",",
"'abort_on_examp... | Setup sphinx-gallery sphinx extension | [
"Setup",
"sphinx",
"-",
"gallery",
"sphinx",
"extension"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/gen_gallery.py#L554-L580 |
230,140 | sphinx-gallery/sphinx-gallery | sphinx_gallery/utils.py | replace_py_ipynb | def replace_py_ipynb(fname):
"""Replace .py extension in filename by .ipynb"""
fname_prefix, extension = os.path.splitext(fname)
allowed_extension = '.py'
if extension != allowed_extension:
raise ValueError(
"Unrecognized file extension, expected %s, got %s"
% (allowed_extension, extension))
new_extension = '.ipynb'
return '{}{}'.format(fname_prefix, new_extension) | python | def replace_py_ipynb(fname):
fname_prefix, extension = os.path.splitext(fname)
allowed_extension = '.py'
if extension != allowed_extension:
raise ValueError(
"Unrecognized file extension, expected %s, got %s"
% (allowed_extension, extension))
new_extension = '.ipynb'
return '{}{}'.format(fname_prefix, new_extension) | [
"def",
"replace_py_ipynb",
"(",
"fname",
")",
":",
"fname_prefix",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"allowed_extension",
"=",
"'.py'",
"if",
"extension",
"!=",
"allowed_extension",
":",
"raise",
"ValueError",
"(",
... | Replace .py extension in filename by .ipynb | [
"Replace",
".",
"py",
"extension",
"in",
"filename",
"by",
".",
"ipynb"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/utils.py#L84-L93 |
230,141 | sphinx-gallery/sphinx-gallery | sphinx_gallery/utils.py | get_md5sum | def get_md5sum(src_file):
"""Returns md5sum of file"""
with open(src_file, 'rb') as src_data:
src_content = src_data.read()
return hashlib.md5(src_content).hexdigest() | python | def get_md5sum(src_file):
with open(src_file, 'rb') as src_data:
src_content = src_data.read()
return hashlib.md5(src_content).hexdigest() | [
"def",
"get_md5sum",
"(",
"src_file",
")",
":",
"with",
"open",
"(",
"src_file",
",",
"'rb'",
")",
"as",
"src_data",
":",
"src_content",
"=",
"src_data",
".",
"read",
"(",
")",
"return",
"hashlib",
".",
"md5",
"(",
"src_content",
")",
".",
"hexdigest",
... | Returns md5sum of file | [
"Returns",
"md5sum",
"of",
"file"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/utils.py#L96-L100 |
230,142 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixResponse.parse | def parse(self, response):
"""Parse zabbix response."""
info = response.get('info')
res = self._regex.search(info)
self._processed += int(res.group(1))
self._failed += int(res.group(2))
self._total += int(res.group(3))
self._time += Decimal(res.group(4))
self._chunk += 1 | python | def parse(self, response):
info = response.get('info')
res = self._regex.search(info)
self._processed += int(res.group(1))
self._failed += int(res.group(2))
self._total += int(res.group(3))
self._time += Decimal(res.group(4))
self._chunk += 1 | [
"def",
"parse",
"(",
"self",
",",
"response",
")",
":",
"info",
"=",
"response",
".",
"get",
"(",
"'info'",
")",
"res",
"=",
"self",
".",
"_regex",
".",
"search",
"(",
"info",
")",
"self",
".",
"_processed",
"+=",
"int",
"(",
"res",
".",
"group",
... | Parse zabbix response. | [
"Parse",
"zabbix",
"response",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L65-L74 |
230,143 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._load_from_config | def _load_from_config(self, config_file):
"""Load zabbix server IP address and port from zabbix agent config
file.
If ServerActive variable is not found in the file, it will
use the default: 127.0.0.1:10051
:type config_file: str
:param use_config: Path to zabbix_agentd.conf file to load settings
from. If value is `True` then default config path will used:
/etc/zabbix/zabbix_agentd.conf
"""
if config_file and isinstance(config_file, bool):
config_file = '/etc/zabbix/zabbix_agentd.conf'
logger.debug("Used config: %s", config_file)
# This is workaround for config wile without sections
with open(config_file, 'r') as f:
config_file_data = "[root]\n" + f.read()
params = {}
try:
# python2
args = inspect.getargspec(
configparser.RawConfigParser.__init__).args
except ValueError:
# python3
args = inspect.getfullargspec(
configparser.RawConfigParser.__init__).kwonlyargs
if 'strict' in args:
params['strict'] = True
config_file_fp = StringIO(config_file_data)
config = configparser.RawConfigParser(**params)
config.readfp(config_file_fp)
# Prefer ServerActive, then try Server and fallback to defaults
if config.has_option('root', 'ServerActive'):
zabbix_serveractives = config.get('root', 'ServerActive')
elif config.has_option('root', 'Server'):
zabbix_serveractives = config.get('root', 'Server')
else:
zabbix_serveractives = '127.0.0.1:10051'
result = []
for serverport in zabbix_serveractives.split(','):
if ':' not in serverport:
serverport = "%s:%s" % (serverport.strip(), 10051)
server, port = serverport.split(':')
serverport = (server, int(port))
result.append(serverport)
logger.debug("Loaded params: %s", result)
return result | python | def _load_from_config(self, config_file):
if config_file and isinstance(config_file, bool):
config_file = '/etc/zabbix/zabbix_agentd.conf'
logger.debug("Used config: %s", config_file)
# This is workaround for config wile without sections
with open(config_file, 'r') as f:
config_file_data = "[root]\n" + f.read()
params = {}
try:
# python2
args = inspect.getargspec(
configparser.RawConfigParser.__init__).args
except ValueError:
# python3
args = inspect.getfullargspec(
configparser.RawConfigParser.__init__).kwonlyargs
if 'strict' in args:
params['strict'] = True
config_file_fp = StringIO(config_file_data)
config = configparser.RawConfigParser(**params)
config.readfp(config_file_fp)
# Prefer ServerActive, then try Server and fallback to defaults
if config.has_option('root', 'ServerActive'):
zabbix_serveractives = config.get('root', 'ServerActive')
elif config.has_option('root', 'Server'):
zabbix_serveractives = config.get('root', 'Server')
else:
zabbix_serveractives = '127.0.0.1:10051'
result = []
for serverport in zabbix_serveractives.split(','):
if ':' not in serverport:
serverport = "%s:%s" % (serverport.strip(), 10051)
server, port = serverport.split(':')
serverport = (server, int(port))
result.append(serverport)
logger.debug("Loaded params: %s", result)
return result | [
"def",
"_load_from_config",
"(",
"self",
",",
"config_file",
")",
":",
"if",
"config_file",
"and",
"isinstance",
"(",
"config_file",
",",
"bool",
")",
":",
"config_file",
"=",
"'/etc/zabbix/zabbix_agentd.conf'",
"logger",
".",
"debug",
"(",
"\"Used config: %s\"",
... | Load zabbix server IP address and port from zabbix agent config
file.
If ServerActive variable is not found in the file, it will
use the default: 127.0.0.1:10051
:type config_file: str
:param use_config: Path to zabbix_agentd.conf file to load settings
from. If value is `True` then default config path will used:
/etc/zabbix/zabbix_agentd.conf | [
"Load",
"zabbix",
"server",
"IP",
"address",
"and",
"port",
"from",
"zabbix",
"agent",
"config",
"file",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L204-L260 |
230,144 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._receive | def _receive(self, sock, count):
"""Reads socket to receive data from zabbix server.
:type socket: :class:`socket._socketobject`
:param socket: Socket to read.
:type count: int
:param count: Number of bytes to read from socket.
"""
buf = b''
while len(buf) < count:
chunk = sock.recv(count - len(buf))
if not chunk:
break
buf += chunk
return buf | python | def _receive(self, sock, count):
buf = b''
while len(buf) < count:
chunk = sock.recv(count - len(buf))
if not chunk:
break
buf += chunk
return buf | [
"def",
"_receive",
"(",
"self",
",",
"sock",
",",
"count",
")",
":",
"buf",
"=",
"b''",
"while",
"len",
"(",
"buf",
")",
"<",
"count",
":",
"chunk",
"=",
"sock",
".",
"recv",
"(",
"count",
"-",
"len",
"(",
"buf",
")",
")",
"if",
"not",
"chunk",... | Reads socket to receive data from zabbix server.
:type socket: :class:`socket._socketobject`
:param socket: Socket to read.
:type count: int
:param count: Number of bytes to read from socket. | [
"Reads",
"socket",
"to",
"receive",
"data",
"from",
"zabbix",
"server",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L262-L280 |
230,145 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._create_messages | def _create_messages(self, metrics):
"""Create a list of zabbix messages from a list of ZabbixMetrics.
:type metrics_array: list
:param metrics_array: List of :class:`zabbix.sender.ZabbixMetric`.
:rtype: list
:return: List of zabbix messages.
"""
messages = []
# Fill the list of messages
for m in metrics:
messages.append(str(m))
logger.debug('Messages: %s', messages)
return messages | python | def _create_messages(self, metrics):
messages = []
# Fill the list of messages
for m in metrics:
messages.append(str(m))
logger.debug('Messages: %s', messages)
return messages | [
"def",
"_create_messages",
"(",
"self",
",",
"metrics",
")",
":",
"messages",
"=",
"[",
"]",
"# Fill the list of messages",
"for",
"m",
"in",
"metrics",
":",
"messages",
".",
"append",
"(",
"str",
"(",
"m",
")",
")",
"logger",
".",
"debug",
"(",
"'Messag... | Create a list of zabbix messages from a list of ZabbixMetrics.
:type metrics_array: list
:param metrics_array: List of :class:`zabbix.sender.ZabbixMetric`.
:rtype: list
:return: List of zabbix messages. | [
"Create",
"a",
"list",
"of",
"zabbix",
"messages",
"from",
"a",
"list",
"of",
"ZabbixMetrics",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L282-L300 |
230,146 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._create_request | def _create_request(self, messages):
"""Create a formatted request to zabbix from a list of messages.
:type messages: list
:param messages: List of zabbix messages
:rtype: list
:return: Formatted zabbix request
"""
msg = ','.join(messages)
request = '{{"request":"sender data","data":[{msg}]}}'.format(msg=msg)
request = request.encode("utf-8")
logger.debug('Request: %s', request)
return request | python | def _create_request(self, messages):
msg = ','.join(messages)
request = '{{"request":"sender data","data":[{msg}]}}'.format(msg=msg)
request = request.encode("utf-8")
logger.debug('Request: %s', request)
return request | [
"def",
"_create_request",
"(",
"self",
",",
"messages",
")",
":",
"msg",
"=",
"','",
".",
"join",
"(",
"messages",
")",
"request",
"=",
"'{{\"request\":\"sender data\",\"data\":[{msg}]}}'",
".",
"format",
"(",
"msg",
"=",
"msg",
")",
"request",
"=",
"request",... | Create a formatted request to zabbix from a list of messages.
:type messages: list
:param messages: List of zabbix messages
:rtype: list
:return: Formatted zabbix request | [
"Create",
"a",
"formatted",
"request",
"to",
"zabbix",
"from",
"a",
"list",
"of",
"messages",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L302-L317 |
230,147 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._create_packet | def _create_packet(self, request):
"""Create a formatted packet from a request.
:type request: str
:param request: Formatted zabbix request
:rtype: str
:return: Data packet for zabbix
"""
data_len = struct.pack('<Q', len(request))
packet = b'ZBXD\x01' + data_len + request
def ord23(x):
if not isinstance(x, int):
return ord(x)
else:
return x
logger.debug('Packet [str]: %s', packet)
logger.debug('Packet [hex]: %s',
':'.join(hex(ord23(x))[2:] for x in packet))
return packet | python | def _create_packet(self, request):
data_len = struct.pack('<Q', len(request))
packet = b'ZBXD\x01' + data_len + request
def ord23(x):
if not isinstance(x, int):
return ord(x)
else:
return x
logger.debug('Packet [str]: %s', packet)
logger.debug('Packet [hex]: %s',
':'.join(hex(ord23(x))[2:] for x in packet))
return packet | [
"def",
"_create_packet",
"(",
"self",
",",
"request",
")",
":",
"data_len",
"=",
"struct",
".",
"pack",
"(",
"'<Q'",
",",
"len",
"(",
"request",
")",
")",
"packet",
"=",
"b'ZBXD\\x01'",
"+",
"data_len",
"+",
"request",
"def",
"ord23",
"(",
"x",
")",
... | Create a formatted packet from a request.
:type request: str
:param request: Formatted zabbix request
:rtype: str
:return: Data packet for zabbix | [
"Create",
"a",
"formatted",
"packet",
"from",
"a",
"request",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L319-L341 |
230,148 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._get_response | def _get_response(self, connection):
"""Get response from zabbix server, reads from self.socket.
:type connection: :class:`socket._socketobject`
:param connection: Socket to read.
:rtype: dict
:return: Response from zabbix server or False in case of error.
"""
response_header = self._receive(connection, 13)
logger.debug('Response header: %s', response_header)
if (not response_header.startswith(b'ZBXD\x01') or
len(response_header) != 13):
logger.debug('Zabbix return not valid response.')
result = False
else:
response_len = struct.unpack('<Q', response_header[5:])[0]
response_body = connection.recv(response_len)
result = json.loads(response_body.decode("utf-8"))
logger.debug('Data received: %s', result)
try:
connection.close()
except Exception as err:
pass
return result | python | def _get_response(self, connection):
response_header = self._receive(connection, 13)
logger.debug('Response header: %s', response_header)
if (not response_header.startswith(b'ZBXD\x01') or
len(response_header) != 13):
logger.debug('Zabbix return not valid response.')
result = False
else:
response_len = struct.unpack('<Q', response_header[5:])[0]
response_body = connection.recv(response_len)
result = json.loads(response_body.decode("utf-8"))
logger.debug('Data received: %s', result)
try:
connection.close()
except Exception as err:
pass
return result | [
"def",
"_get_response",
"(",
"self",
",",
"connection",
")",
":",
"response_header",
"=",
"self",
".",
"_receive",
"(",
"connection",
",",
"13",
")",
"logger",
".",
"debug",
"(",
"'Response header: %s'",
",",
"response_header",
")",
"if",
"(",
"not",
"respon... | Get response from zabbix server, reads from self.socket.
:type connection: :class:`socket._socketobject`
:param connection: Socket to read.
:rtype: dict
:return: Response from zabbix server or False in case of error. | [
"Get",
"response",
"from",
"zabbix",
"server",
"reads",
"from",
"self",
".",
"socket",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L343-L371 |
230,149 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender._chunk_send | def _chunk_send(self, metrics):
"""Send the one chunk metrics to zabbix server.
:type metrics: list
:param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send
to Zabbix
:rtype: str
:return: Response from Zabbix Server
"""
messages = self._create_messages(metrics)
request = self._create_request(messages)
packet = self._create_packet(request)
for host_addr in self.zabbix_uri:
logger.debug('Sending data to %s', host_addr)
# create socket object
connection_ = socket.socket()
if self.socket_wrapper:
connection = self.socket_wrapper(connection_)
else:
connection = connection_
connection.settimeout(self.timeout)
try:
# server and port must be tuple
connection.connect(host_addr)
connection.sendall(packet)
except socket.timeout:
logger.error('Sending failed: Connection to %s timed out after'
'%d seconds', host_addr, self.timeout)
connection.close()
raise socket.timeout
except Exception as err:
# In case of error we should close connection, otherwise
# we will close it after data will be received.
logger.warn('Sending failed: %s', getattr(err, 'msg', str(err)))
connection.close()
raise Exception(err)
response = self._get_response(connection)
logger.debug('%s response: %s', host_addr, response)
if response and response.get('response') != 'success':
logger.debug('Response error: %s}', response)
raise Exception(response)
return response | python | def _chunk_send(self, metrics):
messages = self._create_messages(metrics)
request = self._create_request(messages)
packet = self._create_packet(request)
for host_addr in self.zabbix_uri:
logger.debug('Sending data to %s', host_addr)
# create socket object
connection_ = socket.socket()
if self.socket_wrapper:
connection = self.socket_wrapper(connection_)
else:
connection = connection_
connection.settimeout(self.timeout)
try:
# server and port must be tuple
connection.connect(host_addr)
connection.sendall(packet)
except socket.timeout:
logger.error('Sending failed: Connection to %s timed out after'
'%d seconds', host_addr, self.timeout)
connection.close()
raise socket.timeout
except Exception as err:
# In case of error we should close connection, otherwise
# we will close it after data will be received.
logger.warn('Sending failed: %s', getattr(err, 'msg', str(err)))
connection.close()
raise Exception(err)
response = self._get_response(connection)
logger.debug('%s response: %s', host_addr, response)
if response and response.get('response') != 'success':
logger.debug('Response error: %s}', response)
raise Exception(response)
return response | [
"def",
"_chunk_send",
"(",
"self",
",",
"metrics",
")",
":",
"messages",
"=",
"self",
".",
"_create_messages",
"(",
"metrics",
")",
"request",
"=",
"self",
".",
"_create_request",
"(",
"messages",
")",
"packet",
"=",
"self",
".",
"_create_packet",
"(",
"re... | Send the one chunk metrics to zabbix server.
:type metrics: list
:param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send
to Zabbix
:rtype: str
:return: Response from Zabbix Server | [
"Send",
"the",
"one",
"chunk",
"metrics",
"to",
"zabbix",
"server",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L373-L422 |
230,150 | adubkov/py-zabbix | pyzabbix/sender.py | ZabbixSender.send | def send(self, metrics):
"""Send the metrics to zabbix server.
:type metrics: list
:param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send
to Zabbix
:rtype: :class:`pyzabbix.sender.ZabbixResponse`
:return: Parsed response from Zabbix Server
"""
result = ZabbixResponse()
for m in range(0, len(metrics), self.chunk_size):
result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
return result | python | def send(self, metrics):
result = ZabbixResponse()
for m in range(0, len(metrics), self.chunk_size):
result.parse(self._chunk_send(metrics[m:m + self.chunk_size]))
return result | [
"def",
"send",
"(",
"self",
",",
"metrics",
")",
":",
"result",
"=",
"ZabbixResponse",
"(",
")",
"for",
"m",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"metrics",
")",
",",
"self",
".",
"chunk_size",
")",
":",
"result",
".",
"parse",
"(",
"self",
... | Send the metrics to zabbix server.
:type metrics: list
:param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send
to Zabbix
:rtype: :class:`pyzabbix.sender.ZabbixResponse`
:return: Parsed response from Zabbix Server | [
"Send",
"the",
"metrics",
"to",
"zabbix",
"server",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/sender.py#L424-L437 |
230,151 | adubkov/py-zabbix | pyzabbix/api.py | ZabbixAPI._login | def _login(self, user='', password=''):
"""Do login to zabbix server.
:type user: str
:param user: Zabbix user
:type password: str
:param password: Zabbix user password
"""
logger.debug("ZabbixAPI.login({0},{1})".format(user, password))
self.auth = None
if self.use_authenticate:
self.auth = self.user.authenticate(user=user, password=password)
else:
self.auth = self.user.login(user=user, password=password) | python | def _login(self, user='', password=''):
logger.debug("ZabbixAPI.login({0},{1})".format(user, password))
self.auth = None
if self.use_authenticate:
self.auth = self.user.authenticate(user=user, password=password)
else:
self.auth = self.user.login(user=user, password=password) | [
"def",
"_login",
"(",
"self",
",",
"user",
"=",
"''",
",",
"password",
"=",
"''",
")",
":",
"logger",
".",
"debug",
"(",
"\"ZabbixAPI.login({0},{1})\"",
".",
"format",
"(",
"user",
",",
"password",
")",
")",
"self",
".",
"auth",
"=",
"None",
"if",
"s... | Do login to zabbix server.
:type user: str
:param user: Zabbix user
:type password: str
:param password: Zabbix user password | [
"Do",
"login",
"to",
"zabbix",
"server",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/api.py#L184-L201 |
230,152 | adubkov/py-zabbix | pyzabbix/api.py | ZabbixAPI._logout | def _logout(self):
"""Do logout from zabbix server."""
if self.auth:
logger.debug("ZabbixAPI.logout()")
if self.user.logout():
self.auth = None | python | def _logout(self):
if self.auth:
logger.debug("ZabbixAPI.logout()")
if self.user.logout():
self.auth = None | [
"def",
"_logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"auth",
":",
"logger",
".",
"debug",
"(",
"\"ZabbixAPI.logout()\"",
")",
"if",
"self",
".",
"user",
".",
"logout",
"(",
")",
":",
"self",
".",
"auth",
"=",
"None"
] | Do logout from zabbix server. | [
"Do",
"logout",
"from",
"zabbix",
"server",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/api.py#L203-L210 |
230,153 | adubkov/py-zabbix | pyzabbix/api.py | ZabbixAPI.do_request | def do_request(self, method, params=None):
"""Make request to Zabbix API.
:type method: str
:param method: ZabbixAPI method, like: `apiinfo.version`.
:type params: str
:param params: ZabbixAPI method arguments.
>>> from pyzabbix import ZabbixAPI
>>> z = ZabbixAPI()
>>> apiinfo = z.do_request('apiinfo.version')
"""
request_json = {
'jsonrpc': '2.0',
'method': method,
'params': params or {},
'id': '1',
}
# apiinfo.version and user.login doesn't require auth token
if self.auth and (method not in ('apiinfo.version', 'user.login')):
request_json['auth'] = self.auth
logger.debug(
'urllib2.Request({0}, {1})'.format(
self.url,
json.dumps(request_json)))
data = json.dumps(request_json)
if not isinstance(data, bytes):
data = data.encode("utf-8")
req = urllib2.Request(self.url, data)
req.get_method = lambda: 'POST'
req.add_header('Content-Type', 'application/json-rpc')
try:
res = urlopen(req)
res_str = res.read().decode('utf-8')
res_json = json.loads(res_str)
except ValueError as e:
raise ZabbixAPIException("Unable to parse json: %s" % e.message)
res_str = json.dumps(res_json, indent=4, separators=(',', ': '))
logger.debug("Response Body: %s", res_str)
if 'error' in res_json:
err = res_json['error'].copy()
err.update({'json': str(request_json)})
raise ZabbixAPIException(err)
return res_json | python | def do_request(self, method, params=None):
request_json = {
'jsonrpc': '2.0',
'method': method,
'params': params or {},
'id': '1',
}
# apiinfo.version and user.login doesn't require auth token
if self.auth and (method not in ('apiinfo.version', 'user.login')):
request_json['auth'] = self.auth
logger.debug(
'urllib2.Request({0}, {1})'.format(
self.url,
json.dumps(request_json)))
data = json.dumps(request_json)
if not isinstance(data, bytes):
data = data.encode("utf-8")
req = urllib2.Request(self.url, data)
req.get_method = lambda: 'POST'
req.add_header('Content-Type', 'application/json-rpc')
try:
res = urlopen(req)
res_str = res.read().decode('utf-8')
res_json = json.loads(res_str)
except ValueError as e:
raise ZabbixAPIException("Unable to parse json: %s" % e.message)
res_str = json.dumps(res_json, indent=4, separators=(',', ': '))
logger.debug("Response Body: %s", res_str)
if 'error' in res_json:
err = res_json['error'].copy()
err.update({'json': str(request_json)})
raise ZabbixAPIException(err)
return res_json | [
"def",
"do_request",
"(",
"self",
",",
"method",
",",
"params",
"=",
"None",
")",
":",
"request_json",
"=",
"{",
"'jsonrpc'",
":",
"'2.0'",
",",
"'method'",
":",
"method",
",",
"'params'",
":",
"params",
"or",
"{",
"}",
",",
"'id'",
":",
"'1'",
",",
... | Make request to Zabbix API.
:type method: str
:param method: ZabbixAPI method, like: `apiinfo.version`.
:type params: str
:param params: ZabbixAPI method arguments.
>>> from pyzabbix import ZabbixAPI
>>> z = ZabbixAPI()
>>> apiinfo = z.do_request('apiinfo.version') | [
"Make",
"request",
"to",
"Zabbix",
"API",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/api.py#L227-L280 |
230,154 | adubkov/py-zabbix | pyzabbix/api.py | ZabbixAPI.get_id | def get_id(self, item_type, item=None, with_id=False, hostid=None, **args):
"""Return id or ids of zabbix objects.
:type item_type: str
:param item_type: Type of zabbix object. (eg host, item etc.)
:type item: str
:param item: Name of zabbix object. If it is `None`, return list of
all objects in the scope.
:type with_id: bool
:param with_id: Returned values will be in zabbix json `id` format.
Examlpe: `{'itemid: 128}`
:type name: bool
:param name: Return name instead of id.
:type hostid: int
:param hostid: Filter objects by specific hostid.
:type templateids: int
:param tempateids: Filter objects which only belong to specific
templates by template id.
:type app_name: str
:param app_name: Filter object which only belong to specific
application.
:rtype: int or list
:return: Return single `id`, `name` or list of values.
"""
result = None
name = args.get('name', False)
type_ = '{item_type}.get'.format(item_type=item_type)
item_filter_name = {
'mediatype': 'description',
'trigger': 'description',
'triggerprototype': 'description',
'user': 'alias',
'usermacro': 'macro',
}
item_id_name = {
'discoveryrule': 'item',
'graphprototype': 'graph',
'hostgroup': 'group',
'itemprototype': 'item',
'map': 'selement',
'triggerprototype': 'trigger',
'usergroup': 'usrgrp',
'usermacro': 'hostmacro',
}
filter_ = {
'filter': {
item_filter_name.get(item_type, 'name'): item,
},
'output': 'extend'}
if hostid:
filter_['filter'].update({'hostid': hostid})
if args.get('templateids'):
if item_type == 'usermacro':
filter_['hostids'] = args['templateids']
else:
filter_['templateids'] = args['templateids']
if args.get('app_name'):
filter_['application'] = args['app_name']
logger.debug(
'do_request( "{type}", {filter} )'.format(
type=type_,
filter=filter_))
response = self.do_request(type_, filter_)['result']
if response:
item_id_str = item_id_name.get(item_type, item_type)
item_id = '{item}id'.format(item=item_id_str)
result = []
for obj in response:
# Check if object not belong current template
if args.get('templateids'):
if (not obj.get('templateid') in ("0", None) or
not len(obj.get('templateids', [])) == 0):
continue
if name:
o = obj.get(item_filter_name.get(item_type, 'name'))
result.append(o)
elif with_id:
result.append({item_id: int(obj.get(item_id))})
else:
result.append(int(obj.get(item_id)))
list_types = (list, type(None))
if not isinstance(item, list_types):
result = result[0]
return result | python | def get_id(self, item_type, item=None, with_id=False, hostid=None, **args):
result = None
name = args.get('name', False)
type_ = '{item_type}.get'.format(item_type=item_type)
item_filter_name = {
'mediatype': 'description',
'trigger': 'description',
'triggerprototype': 'description',
'user': 'alias',
'usermacro': 'macro',
}
item_id_name = {
'discoveryrule': 'item',
'graphprototype': 'graph',
'hostgroup': 'group',
'itemprototype': 'item',
'map': 'selement',
'triggerprototype': 'trigger',
'usergroup': 'usrgrp',
'usermacro': 'hostmacro',
}
filter_ = {
'filter': {
item_filter_name.get(item_type, 'name'): item,
},
'output': 'extend'}
if hostid:
filter_['filter'].update({'hostid': hostid})
if args.get('templateids'):
if item_type == 'usermacro':
filter_['hostids'] = args['templateids']
else:
filter_['templateids'] = args['templateids']
if args.get('app_name'):
filter_['application'] = args['app_name']
logger.debug(
'do_request( "{type}", {filter} )'.format(
type=type_,
filter=filter_))
response = self.do_request(type_, filter_)['result']
if response:
item_id_str = item_id_name.get(item_type, item_type)
item_id = '{item}id'.format(item=item_id_str)
result = []
for obj in response:
# Check if object not belong current template
if args.get('templateids'):
if (not obj.get('templateid') in ("0", None) or
not len(obj.get('templateids', [])) == 0):
continue
if name:
o = obj.get(item_filter_name.get(item_type, 'name'))
result.append(o)
elif with_id:
result.append({item_id: int(obj.get(item_id))})
else:
result.append(int(obj.get(item_id)))
list_types = (list, type(None))
if not isinstance(item, list_types):
result = result[0]
return result | [
"def",
"get_id",
"(",
"self",
",",
"item_type",
",",
"item",
"=",
"None",
",",
"with_id",
"=",
"False",
",",
"hostid",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"result",
"=",
"None",
"name",
"=",
"args",
".",
"get",
"(",
"'name'",
",",
"Fals... | Return id or ids of zabbix objects.
:type item_type: str
:param item_type: Type of zabbix object. (eg host, item etc.)
:type item: str
:param item: Name of zabbix object. If it is `None`, return list of
all objects in the scope.
:type with_id: bool
:param with_id: Returned values will be in zabbix json `id` format.
Examlpe: `{'itemid: 128}`
:type name: bool
:param name: Return name instead of id.
:type hostid: int
:param hostid: Filter objects by specific hostid.
:type templateids: int
:param tempateids: Filter objects which only belong to specific
templates by template id.
:type app_name: str
:param app_name: Filter object which only belong to specific
application.
:rtype: int or list
:return: Return single `id`, `name` or list of values. | [
"Return",
"id",
"or",
"ids",
"of",
"zabbix",
"objects",
"."
] | a26aadcba7c54cb122be8becc3802e2c42562c49 | https://github.com/adubkov/py-zabbix/blob/a26aadcba7c54cb122be8becc3802e2c42562c49/pyzabbix/api.py#L282-L385 |
230,155 | hit9/img2txt | ansi.py | generate_optimized_y_move_down_x_SOL | def generate_optimized_y_move_down_x_SOL(y_dist):
""" move down y_dist, set x=0 """
# Optimization to move N lines and go to SOL in one command. Note that some terminals
# may not support this so we might have to remove this optimization or make it optional
# if that winds up mattering for terminals we care about. If we had to remove we'd
# want to rework things such that we used "\x1b[{0}B" but also we would want to change
# our interface to this function so we didn't guarantee x=0 since caller might ultimate
# want it in a different place and we don't want to output two x moves. Could pass in
# desired x, or return current x from here.
string = "\x1b[{0}E".format(y_dist) # ANSI code to move down N lines and move x to SOL
# Would a sequence of 1 or more \n chars be cheaper? If so we'll output that instead
if y_dist < len(string):
string = '\n' * y_dist
return string | python | def generate_optimized_y_move_down_x_SOL(y_dist):
# Optimization to move N lines and go to SOL in one command. Note that some terminals
# may not support this so we might have to remove this optimization or make it optional
# if that winds up mattering for terminals we care about. If we had to remove we'd
# want to rework things such that we used "\x1b[{0}B" but also we would want to change
# our interface to this function so we didn't guarantee x=0 since caller might ultimate
# want it in a different place and we don't want to output two x moves. Could pass in
# desired x, or return current x from here.
string = "\x1b[{0}E".format(y_dist) # ANSI code to move down N lines and move x to SOL
# Would a sequence of 1 or more \n chars be cheaper? If so we'll output that instead
if y_dist < len(string):
string = '\n' * y_dist
return string | [
"def",
"generate_optimized_y_move_down_x_SOL",
"(",
"y_dist",
")",
":",
"# Optimization to move N lines and go to SOL in one command. Note that some terminals ",
"# may not support this so we might have to remove this optimization or make it optional ",
"# if that winds up mattering for terminals we... | move down y_dist, set x=0 | [
"move",
"down",
"y_dist",
"set",
"x",
"=",
"0"
] | b54bf0cc9ac274a7fa738e06b534ec7975ad9c18 | https://github.com/hit9/img2txt/blob/b54bf0cc9ac274a7fa738e06b534ec7975ad9c18/ansi.py#L63-L80 |
230,156 | ishepard/pydriller | pydriller/git_repository.py | GitRepository.get_head | def get_head(self) -> Commit:
"""
Get the head commit.
:return: Commit of the head commit
"""
head_commit = self.repo.head.commit
return Commit(head_commit, self.path, self.main_branch) | python | def get_head(self) -> Commit:
head_commit = self.repo.head.commit
return Commit(head_commit, self.path, self.main_branch) | [
"def",
"get_head",
"(",
"self",
")",
"->",
"Commit",
":",
"head_commit",
"=",
"self",
".",
"repo",
".",
"head",
".",
"commit",
"return",
"Commit",
"(",
"head_commit",
",",
"self",
".",
"path",
",",
"self",
".",
"main_branch",
")"
] | Get the head commit.
:return: Commit of the head commit | [
"Get",
"the",
"head",
"commit",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L81-L88 |
230,157 | ishepard/pydriller | pydriller/git_repository.py | GitRepository.get_list_commits | def get_list_commits(self, branch: str = None,
reverse_order: bool = True) \
-> Generator[Commit, None, None]:
"""
Return a generator of commits of all the commits in the repo.
:return: Generator[Commit], the generator of all the commits in the
repo
"""
for commit in self.repo.iter_commits(branch, reverse=reverse_order):
yield self.get_commit_from_gitpython(commit) | python | def get_list_commits(self, branch: str = None,
reverse_order: bool = True) \
-> Generator[Commit, None, None]:
for commit in self.repo.iter_commits(branch, reverse=reverse_order):
yield self.get_commit_from_gitpython(commit) | [
"def",
"get_list_commits",
"(",
"self",
",",
"branch",
":",
"str",
"=",
"None",
",",
"reverse_order",
":",
"bool",
"=",
"True",
")",
"->",
"Generator",
"[",
"Commit",
",",
"None",
",",
"None",
"]",
":",
"for",
"commit",
"in",
"self",
".",
"repo",
"."... | Return a generator of commits of all the commits in the repo.
:return: Generator[Commit], the generator of all the commits in the
repo | [
"Return",
"a",
"generator",
"of",
"commits",
"of",
"all",
"the",
"commits",
"in",
"the",
"repo",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L90-L100 |
230,158 | ishepard/pydriller | pydriller/git_repository.py | GitRepository.get_commit | def get_commit(self, commit_id: str) -> Commit:
"""
Get the specified commit.
:param str commit_id: hash of the commit to analyze
:return: Commit
"""
return Commit(self.repo.commit(commit_id), self.path, self.main_branch) | python | def get_commit(self, commit_id: str) -> Commit:
return Commit(self.repo.commit(commit_id), self.path, self.main_branch) | [
"def",
"get_commit",
"(",
"self",
",",
"commit_id",
":",
"str",
")",
"->",
"Commit",
":",
"return",
"Commit",
"(",
"self",
".",
"repo",
".",
"commit",
"(",
"commit_id",
")",
",",
"self",
".",
"path",
",",
"self",
".",
"main_branch",
")"
] | Get the specified commit.
:param str commit_id: hash of the commit to analyze
:return: Commit | [
"Get",
"the",
"specified",
"commit",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L102-L109 |
230,159 | ishepard/pydriller | pydriller/git_repository.py | GitRepository.get_commit_from_gitpython | def get_commit_from_gitpython(self, commit: GitCommit) -> Commit:
"""
Build a PyDriller commit object from a GitPython commit object.
This is internal of PyDriller, I don't think users generally will need
it.
:param GitCommit commit: GitPython commit
:return: Commit commit: PyDriller commit
"""
return Commit(commit, self.path, self.main_branch) | python | def get_commit_from_gitpython(self, commit: GitCommit) -> Commit:
return Commit(commit, self.path, self.main_branch) | [
"def",
"get_commit_from_gitpython",
"(",
"self",
",",
"commit",
":",
"GitCommit",
")",
"->",
"Commit",
":",
"return",
"Commit",
"(",
"commit",
",",
"self",
".",
"path",
",",
"self",
".",
"main_branch",
")"
] | Build a PyDriller commit object from a GitPython commit object.
This is internal of PyDriller, I don't think users generally will need
it.
:param GitCommit commit: GitPython commit
:return: Commit commit: PyDriller commit | [
"Build",
"a",
"PyDriller",
"commit",
"object",
"from",
"a",
"GitPython",
"commit",
"object",
".",
"This",
"is",
"internal",
"of",
"PyDriller",
"I",
"don",
"t",
"think",
"users",
"generally",
"will",
"need",
"it",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L111-L120 |
230,160 | ishepard/pydriller | pydriller/git_repository.py | GitRepository.get_commit_from_tag | def get_commit_from_tag(self, tag: str) -> Commit:
"""
Obtain the tagged commit.
:param str tag: the tag
:return: Commit commit: the commit the tag referred to
"""
try:
selected_tag = self.repo.tags[tag]
return self.get_commit(selected_tag.commit.hexsha)
except (IndexError, AttributeError):
logger.debug('Tag %s not found', tag)
raise | python | def get_commit_from_tag(self, tag: str) -> Commit:
try:
selected_tag = self.repo.tags[tag]
return self.get_commit(selected_tag.commit.hexsha)
except (IndexError, AttributeError):
logger.debug('Tag %s not found', tag)
raise | [
"def",
"get_commit_from_tag",
"(",
"self",
",",
"tag",
":",
"str",
")",
"->",
"Commit",
":",
"try",
":",
"selected_tag",
"=",
"self",
".",
"repo",
".",
"tags",
"[",
"tag",
"]",
"return",
"self",
".",
"get_commit",
"(",
"selected_tag",
".",
"commit",
".... | Obtain the tagged commit.
:param str tag: the tag
:return: Commit commit: the commit the tag referred to | [
"Obtain",
"the",
"tagged",
"commit",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/git_repository.py#L177-L189 |
230,161 | ishepard/pydriller | pydriller/domain/commit.py | Modification.added | def added(self) -> int:
"""
Return the total number of added lines in the file.
:return: int lines_added
"""
added = 0
for line in self.diff.replace('\r', '').split("\n"):
if line.startswith('+') and not line.startswith('+++'):
added += 1
return added | python | def added(self) -> int:
added = 0
for line in self.diff.replace('\r', '').split("\n"):
if line.startswith('+') and not line.startswith('+++'):
added += 1
return added | [
"def",
"added",
"(",
"self",
")",
"->",
"int",
":",
"added",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"diff",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'+'",
... | Return the total number of added lines in the file.
:return: int lines_added | [
"Return",
"the",
"total",
"number",
"of",
"added",
"lines",
"in",
"the",
"file",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L105-L115 |
230,162 | ishepard/pydriller | pydriller/domain/commit.py | Modification.removed | def removed(self):
"""
Return the total number of deleted lines in the file.
:return: int lines_deleted
"""
removed = 0
for line in self.diff.replace('\r', '').split("\n"):
if line.startswith('-') and not line.startswith('---'):
removed += 1
return removed | python | def removed(self):
removed = 0
for line in self.diff.replace('\r', '').split("\n"):
if line.startswith('-') and not line.startswith('---'):
removed += 1
return removed | [
"def",
"removed",
"(",
"self",
")",
":",
"removed",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"diff",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'-'",
")",
"and",... | Return the total number of deleted lines in the file.
:return: int lines_deleted | [
"Return",
"the",
"total",
"number",
"of",
"deleted",
"lines",
"in",
"the",
"file",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L118-L128 |
230,163 | ishepard/pydriller | pydriller/domain/commit.py | Commit.author | def author(self) -> Developer:
"""
Return the author of the commit as a Developer object.
:return: author
"""
return Developer(self._c_object.author.name,
self._c_object.author.email) | python | def author(self) -> Developer:
return Developer(self._c_object.author.name,
self._c_object.author.email) | [
"def",
"author",
"(",
"self",
")",
"->",
"Developer",
":",
"return",
"Developer",
"(",
"self",
".",
"_c_object",
".",
"author",
".",
"name",
",",
"self",
".",
"_c_object",
".",
"author",
".",
"email",
")"
] | Return the author of the commit as a Developer object.
:return: author | [
"Return",
"the",
"author",
"of",
"the",
"commit",
"as",
"a",
"Developer",
"object",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L273-L280 |
230,164 | ishepard/pydriller | pydriller/domain/commit.py | Commit.committer | def committer(self) -> Developer:
"""
Return the committer of the commit as a Developer object.
:return: committer
"""
return Developer(self._c_object.committer.name,
self._c_object.committer.email) | python | def committer(self) -> Developer:
return Developer(self._c_object.committer.name,
self._c_object.committer.email) | [
"def",
"committer",
"(",
"self",
")",
"->",
"Developer",
":",
"return",
"Developer",
"(",
"self",
".",
"_c_object",
".",
"committer",
".",
"name",
",",
"self",
".",
"_c_object",
".",
"committer",
".",
"email",
")"
] | Return the committer of the commit as a Developer object.
:return: committer | [
"Return",
"the",
"committer",
"of",
"the",
"commit",
"as",
"a",
"Developer",
"object",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L283-L290 |
230,165 | ishepard/pydriller | pydriller/domain/commit.py | Commit.parents | def parents(self) -> List[str]:
"""
Return the list of parents SHAs.
:return: List[str] parents
"""
parents = []
for p in self._c_object.parents:
parents.append(p.hexsha)
return parents | python | def parents(self) -> List[str]:
parents = []
for p in self._c_object.parents:
parents.append(p.hexsha)
return parents | [
"def",
"parents",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"parents",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"_c_object",
".",
"parents",
":",
"parents",
".",
"append",
"(",
"p",
".",
"hexsha",
")",
"return",
"parents"
] | Return the list of parents SHAs.
:return: List[str] parents | [
"Return",
"the",
"list",
"of",
"parents",
"SHAs",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L347-L356 |
230,166 | ishepard/pydriller | pydriller/domain/commit.py | Commit.modifications | def modifications(self) -> List[Modification]:
"""
Return a list of modified files.
:return: List[Modification] modifications
"""
if self._modifications is None:
self._modifications = self._get_modifications()
return self._modifications | python | def modifications(self) -> List[Modification]:
if self._modifications is None:
self._modifications = self._get_modifications()
return self._modifications | [
"def",
"modifications",
"(",
"self",
")",
"->",
"List",
"[",
"Modification",
"]",
":",
"if",
"self",
".",
"_modifications",
"is",
"None",
":",
"self",
".",
"_modifications",
"=",
"self",
".",
"_get_modifications",
"(",
")",
"return",
"self",
".",
"_modific... | Return a list of modified files.
:return: List[Modification] modifications | [
"Return",
"a",
"list",
"of",
"modified",
"files",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L368-L377 |
230,167 | ishepard/pydriller | pydriller/domain/commit.py | Commit.branches | def branches(self) -> Set[str]:
"""
Return the set of branches that contain the commit.
:return: set(str) branches
"""
if self._branches is None:
self._branches = self._get_branches()
return self._branches | python | def branches(self) -> Set[str]:
if self._branches is None:
self._branches = self._get_branches()
return self._branches | [
"def",
"branches",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"if",
"self",
".",
"_branches",
"is",
"None",
":",
"self",
".",
"_branches",
"=",
"self",
".",
"_get_branches",
"(",
")",
"return",
"self",
".",
"_branches"
] | Return the set of branches that contain the commit.
:return: set(str) branches | [
"Return",
"the",
"set",
"of",
"branches",
"that",
"contain",
"the",
"commit",
"."
] | 71facb32afa085d5ddf0081beba34d00d57b8080 | https://github.com/ishepard/pydriller/blob/71facb32afa085d5ddf0081beba34d00d57b8080/pydriller/domain/commit.py#L430-L439 |
230,168 | nginxinc/crossplane | crossplane/lexer.py | _lex_file_object | def _lex_file_object(file_obj):
"""
Generates token tuples from an nginx config file object
Yields 3-tuples like (token, lineno, quoted)
"""
token = '' # the token buffer
token_line = 0 # the line the token starts on
next_token_is_directive = True
it = itertools.chain.from_iterable(file_obj)
it = _iterescape(it) # treat escaped characters differently
it = _iterlinecount(it) # count the number of newline characters
for char, line in it:
# handle whitespace
if char.isspace():
# if token complete yield it and reset token buffer
if token:
yield (token, token_line, False)
if next_token_is_directive and token in EXTERNAL_LEXERS:
for custom_lexer_token in EXTERNAL_LEXERS[token](it, token):
yield custom_lexer_token
next_token_is_directive = True
else:
next_token_is_directive = False
token = ''
# disregard until char isn't a whitespace character
while char.isspace():
char, line = next(it)
# if starting comment
if not token and char == '#':
while not char.endswith('\n'):
token = token + char
char, _ = next(it)
yield (token, line, False)
token = ''
continue
if not token:
token_line = line
# handle parameter expansion syntax (ex: "${var[@]}")
if token and token[-1] == '$' and char == '{':
next_token_is_directive = False
while token[-1] != '}' and not char.isspace():
token += char
char, line = next(it)
# if a quote is found, add the whole string to the token buffer
if char in ('"', "'"):
# if a quote is inside a token, treat it like any other char
if token:
token += char
continue
quote = char
char, line = next(it)
while char != quote:
token += quote if char == '\\' + quote else char
char, line = next(it)
yield (token, token_line, True) # True because this is in quotes
# handle quoted external directives
if next_token_is_directive and token in EXTERNAL_LEXERS:
for custom_lexer_token in EXTERNAL_LEXERS[token](it, token):
yield custom_lexer_token
next_token_is_directive = True
else:
next_token_is_directive = False
token = ''
continue
# handle special characters that are treated like full tokens
if char in ('{', '}', ';'):
# if token complete yield it and reset token buffer
if token:
yield (token, token_line, False)
token = ''
# this character is a full token so yield it now
yield (char, line, False)
next_token_is_directive = True
continue
# append char to the token buffer
token += char | python | def _lex_file_object(file_obj):
token = '' # the token buffer
token_line = 0 # the line the token starts on
next_token_is_directive = True
it = itertools.chain.from_iterable(file_obj)
it = _iterescape(it) # treat escaped characters differently
it = _iterlinecount(it) # count the number of newline characters
for char, line in it:
# handle whitespace
if char.isspace():
# if token complete yield it and reset token buffer
if token:
yield (token, token_line, False)
if next_token_is_directive and token in EXTERNAL_LEXERS:
for custom_lexer_token in EXTERNAL_LEXERS[token](it, token):
yield custom_lexer_token
next_token_is_directive = True
else:
next_token_is_directive = False
token = ''
# disregard until char isn't a whitespace character
while char.isspace():
char, line = next(it)
# if starting comment
if not token and char == '#':
while not char.endswith('\n'):
token = token + char
char, _ = next(it)
yield (token, line, False)
token = ''
continue
if not token:
token_line = line
# handle parameter expansion syntax (ex: "${var[@]}")
if token and token[-1] == '$' and char == '{':
next_token_is_directive = False
while token[-1] != '}' and not char.isspace():
token += char
char, line = next(it)
# if a quote is found, add the whole string to the token buffer
if char in ('"', "'"):
# if a quote is inside a token, treat it like any other char
if token:
token += char
continue
quote = char
char, line = next(it)
while char != quote:
token += quote if char == '\\' + quote else char
char, line = next(it)
yield (token, token_line, True) # True because this is in quotes
# handle quoted external directives
if next_token_is_directive and token in EXTERNAL_LEXERS:
for custom_lexer_token in EXTERNAL_LEXERS[token](it, token):
yield custom_lexer_token
next_token_is_directive = True
else:
next_token_is_directive = False
token = ''
continue
# handle special characters that are treated like full tokens
if char in ('{', '}', ';'):
# if token complete yield it and reset token buffer
if token:
yield (token, token_line, False)
token = ''
# this character is a full token so yield it now
yield (char, line, False)
next_token_is_directive = True
continue
# append char to the token buffer
token += char | [
"def",
"_lex_file_object",
"(",
"file_obj",
")",
":",
"token",
"=",
"''",
"# the token buffer",
"token_line",
"=",
"0",
"# the line the token starts on",
"next_token_is_directive",
"=",
"True",
"it",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"file_o... | Generates token tuples from an nginx config file object
Yields 3-tuples like (token, lineno, quoted) | [
"Generates",
"token",
"tuples",
"from",
"an",
"nginx",
"config",
"file",
"object"
] | 59186f5785c72062656f5e160f08002b3e2c9888 | https://github.com/nginxinc/crossplane/blob/59186f5785c72062656f5e160f08002b3e2c9888/crossplane/lexer.py#L30-L120 |
230,169 | nginxinc/crossplane | crossplane/lexer.py | _balance_braces | def _balance_braces(tokens, filename=None):
"""Raises syntax errors if braces aren't balanced"""
depth = 0
for token, line, quoted in tokens:
if token == '}' and not quoted:
depth -= 1
elif token == '{' and not quoted:
depth += 1
# raise error if we ever have more right braces than left
if depth < 0:
reason = 'unexpected "}"'
raise NgxParserSyntaxError(reason, filename, line)
else:
yield (token, line, quoted)
# raise error if we have less right braces than left at EOF
if depth > 0:
reason = 'unexpected end of file, expecting "}"'
raise NgxParserSyntaxError(reason, filename, line) | python | def _balance_braces(tokens, filename=None):
depth = 0
for token, line, quoted in tokens:
if token == '}' and not quoted:
depth -= 1
elif token == '{' and not quoted:
depth += 1
# raise error if we ever have more right braces than left
if depth < 0:
reason = 'unexpected "}"'
raise NgxParserSyntaxError(reason, filename, line)
else:
yield (token, line, quoted)
# raise error if we have less right braces than left at EOF
if depth > 0:
reason = 'unexpected end of file, expecting "}"'
raise NgxParserSyntaxError(reason, filename, line) | [
"def",
"_balance_braces",
"(",
"tokens",
",",
"filename",
"=",
"None",
")",
":",
"depth",
"=",
"0",
"for",
"token",
",",
"line",
",",
"quoted",
"in",
"tokens",
":",
"if",
"token",
"==",
"'}'",
"and",
"not",
"quoted",
":",
"depth",
"-=",
"1",
"elif",
... | Raises syntax errors if braces aren't balanced | [
"Raises",
"syntax",
"errors",
"if",
"braces",
"aren",
"t",
"balanced"
] | 59186f5785c72062656f5e160f08002b3e2c9888 | https://github.com/nginxinc/crossplane/blob/59186f5785c72062656f5e160f08002b3e2c9888/crossplane/lexer.py#L123-L143 |
230,170 | nginxinc/crossplane | crossplane/lexer.py | lex | def lex(filename):
"""Generates tokens from an nginx config file"""
with io.open(filename, mode='r', encoding='utf-8') as f:
it = _lex_file_object(f)
it = _balance_braces(it, filename)
for token, line, quoted in it:
yield (token, line, quoted) | python | def lex(filename):
with io.open(filename, mode='r', encoding='utf-8') as f:
it = _lex_file_object(f)
it = _balance_braces(it, filename)
for token, line, quoted in it:
yield (token, line, quoted) | [
"def",
"lex",
"(",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"it",
"=",
"_lex_file_object",
"(",
"f",
")",
"it",
"=",
"_balance_braces",
"(",
"it... | Generates tokens from an nginx config file | [
"Generates",
"tokens",
"from",
"an",
"nginx",
"config",
"file"
] | 59186f5785c72062656f5e160f08002b3e2c9888 | https://github.com/nginxinc/crossplane/blob/59186f5785c72062656f5e160f08002b3e2c9888/crossplane/lexer.py#L146-L152 |
230,171 | nginxinc/crossplane | crossplane/parser.py | _prepare_if_args | def _prepare_if_args(stmt):
"""Removes parentheses from an "if" directive's arguments"""
args = stmt['args']
if args and args[0].startswith('(') and args[-1].endswith(')'):
args[0] = args[0][1:].lstrip()
args[-1] = args[-1][:-1].rstrip()
start = int(not args[0])
end = len(args) - int(not args[-1])
args[:] = args[start:end] | python | def _prepare_if_args(stmt):
args = stmt['args']
if args and args[0].startswith('(') and args[-1].endswith(')'):
args[0] = args[0][1:].lstrip()
args[-1] = args[-1][:-1].rstrip()
start = int(not args[0])
end = len(args) - int(not args[-1])
args[:] = args[start:end] | [
"def",
"_prepare_if_args",
"(",
"stmt",
")",
":",
"args",
"=",
"stmt",
"[",
"'args'",
"]",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"'('",
")",
"and",
"args",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"')'",
")",
":",
... | Removes parentheses from an "if" directive's arguments | [
"Removes",
"parentheses",
"from",
"an",
"if",
"directive",
"s",
"arguments"
] | 59186f5785c72062656f5e160f08002b3e2c9888 | https://github.com/nginxinc/crossplane/blob/59186f5785c72062656f5e160f08002b3e2c9888/crossplane/parser.py#L14-L22 |
230,172 | nginxinc/crossplane | crossplane/parser.py | _combine_parsed_configs | def _combine_parsed_configs(old_payload):
"""
Combines config files into one by using include directives.
:param old_payload: payload that's normally returned by parse()
:return: the new combined payload
"""
old_configs = old_payload['config']
def _perform_includes(block):
for stmt in block:
if 'block' in stmt:
stmt['block'] = list(_perform_includes(stmt['block']))
if 'includes' in stmt:
for index in stmt['includes']:
config = old_configs[index]['parsed']
for stmt in _perform_includes(config):
yield stmt
else:
yield stmt # do not yield include stmt itself
combined_config = {
'file': old_configs[0]['file'],
'status': 'ok',
'errors': [],
'parsed': []
}
for config in old_configs:
combined_config['errors'] += config.get('errors', [])
if config.get('status', 'ok') == 'failed':
combined_config['status'] = 'failed'
first_config = old_configs[0]['parsed']
combined_config['parsed'] += _perform_includes(first_config)
combined_payload = {
'status': old_payload.get('status', 'ok'),
'errors': old_payload.get('errors', []),
'config': [combined_config]
}
return combined_payload | python | def _combine_parsed_configs(old_payload):
old_configs = old_payload['config']
def _perform_includes(block):
for stmt in block:
if 'block' in stmt:
stmt['block'] = list(_perform_includes(stmt['block']))
if 'includes' in stmt:
for index in stmt['includes']:
config = old_configs[index]['parsed']
for stmt in _perform_includes(config):
yield stmt
else:
yield stmt # do not yield include stmt itself
combined_config = {
'file': old_configs[0]['file'],
'status': 'ok',
'errors': [],
'parsed': []
}
for config in old_configs:
combined_config['errors'] += config.get('errors', [])
if config.get('status', 'ok') == 'failed':
combined_config['status'] = 'failed'
first_config = old_configs[0]['parsed']
combined_config['parsed'] += _perform_includes(first_config)
combined_payload = {
'status': old_payload.get('status', 'ok'),
'errors': old_payload.get('errors', []),
'config': [combined_config]
}
return combined_payload | [
"def",
"_combine_parsed_configs",
"(",
"old_payload",
")",
":",
"old_configs",
"=",
"old_payload",
"[",
"'config'",
"]",
"def",
"_perform_includes",
"(",
"block",
")",
":",
"for",
"stmt",
"in",
"block",
":",
"if",
"'block'",
"in",
"stmt",
":",
"stmt",
"[",
... | Combines config files into one by using include directives.
:param old_payload: payload that's normally returned by parse()
:return: the new combined payload | [
"Combines",
"config",
"files",
"into",
"one",
"by",
"using",
"include",
"directives",
"."
] | 59186f5785c72062656f5e160f08002b3e2c9888 | https://github.com/nginxinc/crossplane/blob/59186f5785c72062656f5e160f08002b3e2c9888/crossplane/parser.py#L239-L280 |
230,173 | python-cmd2/cmd2 | tasks.py | rmrf | def rmrf(items, verbose=True):
"Silently remove a list of directories or files"
if isinstance(items, str):
items = [items]
for item in items:
if verbose:
print("Removing {}".format(item))
shutil.rmtree(item, ignore_errors=True)
# rmtree doesn't remove bare files
try:
os.remove(item)
except FileNotFoundError:
pass | python | def rmrf(items, verbose=True):
"Silently remove a list of directories or files"
if isinstance(items, str):
items = [items]
for item in items:
if verbose:
print("Removing {}".format(item))
shutil.rmtree(item, ignore_errors=True)
# rmtree doesn't remove bare files
try:
os.remove(item)
except FileNotFoundError:
pass | [
"def",
"rmrf",
"(",
"items",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"items",
",",
"str",
")",
":",
"items",
"=",
"[",
"items",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Removing {}\"",
"... | Silently remove a list of directories or files | [
"Silently",
"remove",
"a",
"list",
"of",
"directories",
"or",
"files"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/tasks.py#L19-L32 |
230,174 | python-cmd2/cmd2 | tasks.py | docs | def docs(context, builder='html'):
"Build documentation using sphinx"
cmdline = 'python -msphinx -M {} {} {} {}'.format(builder, DOCS_SRCDIR, DOCS_BUILDDIR, SPHINX_OPTS)
context.run(cmdline) | python | def docs(context, builder='html'):
"Build documentation using sphinx"
cmdline = 'python -msphinx -M {} {} {} {}'.format(builder, DOCS_SRCDIR, DOCS_BUILDDIR, SPHINX_OPTS)
context.run(cmdline) | [
"def",
"docs",
"(",
"context",
",",
"builder",
"=",
"'html'",
")",
":",
"cmdline",
"=",
"'python -msphinx -M {} {} {} {}'",
".",
"format",
"(",
"builder",
",",
"DOCS_SRCDIR",
",",
"DOCS_BUILDDIR",
",",
"SPHINX_OPTS",
")",
"context",
".",
"run",
"(",
"cmdline",... | Build documentation using sphinx | [
"Build",
"documentation",
"using",
"sphinx"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/tasks.py#L98-L101 |
230,175 | python-cmd2/cmd2 | tasks.py | eggs_clean | def eggs_clean(context):
"Remove egg directories"
#pylint: disable=unused-argument
dirs = set()
dirs.add('.eggs')
for name in os.listdir(os.curdir):
if name.endswith('.egg-info'):
dirs.add(name)
if name.endswith('.egg'):
dirs.add(name)
rmrf(dirs) | python | def eggs_clean(context):
"Remove egg directories"
#pylint: disable=unused-argument
dirs = set()
dirs.add('.eggs')
for name in os.listdir(os.curdir):
if name.endswith('.egg-info'):
dirs.add(name)
if name.endswith('.egg'):
dirs.add(name)
rmrf(dirs) | [
"def",
"eggs_clean",
"(",
"context",
")",
":",
"#pylint: disable=unused-argument",
"dirs",
"=",
"set",
"(",
")",
"dirs",
".",
"add",
"(",
"'.eggs'",
")",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"curdir",
")",
":",
"if",
"name",
".",
... | Remove egg directories | [
"Remove",
"egg",
"directories"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/tasks.py#L144-L154 |
230,176 | python-cmd2/cmd2 | tasks.py | tag | def tag(context, name, message=''):
"Add a Git tag and push it to origin"
# If a tag was provided on the command-line, then add a Git tag and push it to origin
if name:
context.run('git tag -a {} -m {!r}'.format(name, message))
context.run('git push origin {}'.format(name)) | python | def tag(context, name, message=''):
"Add a Git tag and push it to origin"
# If a tag was provided on the command-line, then add a Git tag and push it to origin
if name:
context.run('git tag -a {} -m {!r}'.format(name, message))
context.run('git push origin {}'.format(name)) | [
"def",
"tag",
"(",
"context",
",",
"name",
",",
"message",
"=",
"''",
")",
":",
"# If a tag was provided on the command-line, then add a Git tag and push it to origin",
"if",
"name",
":",
"context",
".",
"run",
"(",
"'git tag -a {} -m {!r}'",
".",
"format",
"(",
"name... | Add a Git tag and push it to origin | [
"Add",
"a",
"Git",
"tag",
"and",
"push",
"it",
"to",
"origin"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/tasks.py#L180-L185 |
230,177 | python-cmd2/cmd2 | tasks.py | validatetag | def validatetag(context):
"Check to make sure that a tag exists for the current HEAD and it looks like a valid version number"
# Validate that a Git tag exists for the current commit HEAD
result = context.run("git describe --exact-match --tags $(git log -n1 --pretty='%h')")
tag = result.stdout.rstrip()
# Validate that the Git tag appears to be a valid version number
ver_regex = re.compile('(\d+)\.(\d+)\.(\d+)')
match = ver_regex.fullmatch(tag)
if match is None:
print('Tag {!r} does not appear to be a valid version number'.format(tag))
sys.exit(-1)
else:
print('Tag {!r} appears to be a valid version number'.format(tag)) | python | def validatetag(context):
"Check to make sure that a tag exists for the current HEAD and it looks like a valid version number"
# Validate that a Git tag exists for the current commit HEAD
result = context.run("git describe --exact-match --tags $(git log -n1 --pretty='%h')")
tag = result.stdout.rstrip()
# Validate that the Git tag appears to be a valid version number
ver_regex = re.compile('(\d+)\.(\d+)\.(\d+)')
match = ver_regex.fullmatch(tag)
if match is None:
print('Tag {!r} does not appear to be a valid version number'.format(tag))
sys.exit(-1)
else:
print('Tag {!r} appears to be a valid version number'.format(tag)) | [
"def",
"validatetag",
"(",
"context",
")",
":",
"# Validate that a Git tag exists for the current commit HEAD",
"result",
"=",
"context",
".",
"run",
"(",
"\"git describe --exact-match --tags $(git log -n1 --pretty='%h')\"",
")",
"tag",
"=",
"result",
".",
"stdout",
".",
"r... | Check to make sure that a tag exists for the current HEAD and it looks like a valid version number | [
"Check",
"to",
"make",
"sure",
"that",
"a",
"tag",
"exists",
"for",
"the",
"current",
"HEAD",
"and",
"it",
"looks",
"like",
"a",
"valid",
"version",
"number"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/tasks.py#L189-L202 |
230,178 | python-cmd2/cmd2 | examples/async_printing.py | AlerterApp._preloop_hook | def _preloop_hook(self) -> None:
""" Start the alerter thread """
# This runs after cmdloop() acquires self.terminal_lock, which will be locked until the prompt appears.
# Therefore this is the best place to start the alerter thread since there is no risk of it alerting
# before the prompt is displayed. You can also start it via a command if its not something that should
# be running during the entire application. See do_start_alerts().
self._stop_thread = False
self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)
self._alerter_thread.start() | python | def _preloop_hook(self) -> None:
# This runs after cmdloop() acquires self.terminal_lock, which will be locked until the prompt appears.
# Therefore this is the best place to start the alerter thread since there is no risk of it alerting
# before the prompt is displayed. You can also start it via a command if its not something that should
# be running during the entire application. See do_start_alerts().
self._stop_thread = False
self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)
self._alerter_thread.start() | [
"def",
"_preloop_hook",
"(",
"self",
")",
"->",
"None",
":",
"# This runs after cmdloop() acquires self.terminal_lock, which will be locked until the prompt appears.",
"# Therefore this is the best place to start the alerter thread since there is no risk of it alerting",
"# before the prompt is ... | Start the alerter thread | [
"Start",
"the",
"alerter",
"thread"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/async_printing.py#L49-L58 |
230,179 | python-cmd2/cmd2 | examples/async_printing.py | AlerterApp.do_start_alerts | def do_start_alerts(self, _):
""" Starts the alerter thread """
if self._alerter_thread.is_alive():
print("The alert thread is already started")
else:
self._stop_thread = False
self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)
self._alerter_thread.start() | python | def do_start_alerts(self, _):
if self._alerter_thread.is_alive():
print("The alert thread is already started")
else:
self._stop_thread = False
self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread_func)
self._alerter_thread.start() | [
"def",
"do_start_alerts",
"(",
"self",
",",
"_",
")",
":",
"if",
"self",
".",
"_alerter_thread",
".",
"is_alive",
"(",
")",
":",
"print",
"(",
"\"The alert thread is already started\"",
")",
"else",
":",
"self",
".",
"_stop_thread",
"=",
"False",
"self",
"."... | Starts the alerter thread | [
"Starts",
"the",
"alerter",
"thread"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/async_printing.py#L70-L77 |
230,180 | python-cmd2/cmd2 | examples/async_printing.py | AlerterApp._alerter_thread_func | def _alerter_thread_func(self) -> None:
""" Prints alerts and updates the prompt any time the prompt is showing """
self._alert_count = 0
self._next_alert_time = 0
while not self._stop_thread:
# Always acquire terminal_lock before printing alerts or updating the prompt
# To keep the app responsive, do not block on this call
if self.terminal_lock.acquire(blocking=False):
# Get any alerts that need to be printed
alert_str = self._generate_alert_str()
# Generate a new prompt
new_prompt = self._generate_colored_prompt()
# Check if we have alerts to print
if alert_str:
# new_prompt is an optional parameter to async_alert()
self.async_alert(alert_str, new_prompt)
new_title = "Alerts Printed: {}".format(self._alert_count)
self.set_window_title(new_title)
# No alerts needed to be printed, check if the prompt changed
elif new_prompt != self.prompt:
self.async_update_prompt(new_prompt)
# Don't forget to release the lock
self.terminal_lock.release()
time.sleep(0.5) | python | def _alerter_thread_func(self) -> None:
self._alert_count = 0
self._next_alert_time = 0
while not self._stop_thread:
# Always acquire terminal_lock before printing alerts or updating the prompt
# To keep the app responsive, do not block on this call
if self.terminal_lock.acquire(blocking=False):
# Get any alerts that need to be printed
alert_str = self._generate_alert_str()
# Generate a new prompt
new_prompt = self._generate_colored_prompt()
# Check if we have alerts to print
if alert_str:
# new_prompt is an optional parameter to async_alert()
self.async_alert(alert_str, new_prompt)
new_title = "Alerts Printed: {}".format(self._alert_count)
self.set_window_title(new_title)
# No alerts needed to be printed, check if the prompt changed
elif new_prompt != self.prompt:
self.async_update_prompt(new_prompt)
# Don't forget to release the lock
self.terminal_lock.release()
time.sleep(0.5) | [
"def",
"_alerter_thread_func",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_alert_count",
"=",
"0",
"self",
".",
"_next_alert_time",
"=",
"0",
"while",
"not",
"self",
".",
"_stop_thread",
":",
"# Always acquire terminal_lock before printing alerts or updating t... | Prints alerts and updates the prompt any time the prompt is showing | [
"Prints",
"alerts",
"and",
"updates",
"the",
"prompt",
"any",
"time",
"the",
"prompt",
"is",
"showing"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/async_printing.py#L165-L196 |
230,181 | python-cmd2/cmd2 | cmd2/utils.py | quote_string_if_needed | def quote_string_if_needed(arg: str) -> str:
""" Quotes a string if it contains spaces and isn't already quoted """
if is_quoted(arg) or ' ' not in arg:
return arg
if '"' in arg:
quote = "'"
else:
quote = '"'
return quote + arg + quote | python | def quote_string_if_needed(arg: str) -> str:
if is_quoted(arg) or ' ' not in arg:
return arg
if '"' in arg:
quote = "'"
else:
quote = '"'
return quote + arg + quote | [
"def",
"quote_string_if_needed",
"(",
"arg",
":",
"str",
")",
"->",
"str",
":",
"if",
"is_quoted",
"(",
"arg",
")",
"or",
"' '",
"not",
"in",
"arg",
":",
"return",
"arg",
"if",
"'\"'",
"in",
"arg",
":",
"quote",
"=",
"\"'\"",
"else",
":",
"quote",
... | Quotes a string if it contains spaces and isn't already quoted | [
"Quotes",
"a",
"string",
"if",
"it",
"contains",
"spaces",
"and",
"isn",
"t",
"already",
"quoted"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L46-L56 |
230,182 | python-cmd2/cmd2 | cmd2/utils.py | namedtuple_with_defaults | def namedtuple_with_defaults(typename: str, field_names: Union[str, List[str]],
default_values: collections.Iterable = ()):
"""
Convenience function for defining a namedtuple with default values
From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments
Examples:
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
>>> Node()
Node(val=None, left=None, right=7)
>>> Node(4)
Node(val=4, left=None, right=7)
"""
T = collections.namedtuple(typename, field_names)
# noinspection PyProtectedMember,PyUnresolvedReferences
T.__new__.__defaults__ = (None,) * len(T._fields)
if isinstance(default_values, collections.Mapping):
prototype = T(**default_values)
else:
prototype = T(*default_values)
T.__new__.__defaults__ = tuple(prototype)
return T | python | def namedtuple_with_defaults(typename: str, field_names: Union[str, List[str]],
default_values: collections.Iterable = ()):
T = collections.namedtuple(typename, field_names)
# noinspection PyProtectedMember,PyUnresolvedReferences
T.__new__.__defaults__ = (None,) * len(T._fields)
if isinstance(default_values, collections.Mapping):
prototype = T(**default_values)
else:
prototype = T(*default_values)
T.__new__.__defaults__ = tuple(prototype)
return T | [
"def",
"namedtuple_with_defaults",
"(",
"typename",
":",
"str",
",",
"field_names",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"default_values",
":",
"collections",
".",
"Iterable",
"=",
"(",
")",
")",
":",
"T",
"=",
"collections",... | Convenience function for defining a namedtuple with default values
From: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments
Examples:
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
>>> Node()
Node(val=None, left=None, right=7)
>>> Node(4)
Node(val=4, left=None, right=7) | [
"Convenience",
"function",
"for",
"defining",
"a",
"namedtuple",
"with",
"default",
"values"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L72-L100 |
230,183 | python-cmd2/cmd2 | cmd2/utils.py | cast | def cast(current: Any, new: str) -> Any:
"""Tries to force a new value into the same type as the current when trying to set the value for a parameter.
:param current: current value for the parameter, type varies
:param new: new value
:return: new value with same type as current, or the current value if there was an error casting
"""
typ = type(current)
orig_new = new
if typ == bool:
try:
return bool(int(new))
except (ValueError, TypeError):
pass
try:
new = new.lower()
if (new == 'on') or (new[0] in ('y', 't')):
return True
if (new == 'off') or (new[0] in ('n', 'f')):
return False
except AttributeError:
pass
else:
try:
return typ(new)
except (ValueError, TypeError):
pass
print("Problem setting parameter (now {}) to {}; incorrect type?".format(current, orig_new))
return current | python | def cast(current: Any, new: str) -> Any:
typ = type(current)
orig_new = new
if typ == bool:
try:
return bool(int(new))
except (ValueError, TypeError):
pass
try:
new = new.lower()
if (new == 'on') or (new[0] in ('y', 't')):
return True
if (new == 'off') or (new[0] in ('n', 'f')):
return False
except AttributeError:
pass
else:
try:
return typ(new)
except (ValueError, TypeError):
pass
print("Problem setting parameter (now {}) to {}; incorrect type?".format(current, orig_new))
return current | [
"def",
"cast",
"(",
"current",
":",
"Any",
",",
"new",
":",
"str",
")",
"->",
"Any",
":",
"typ",
"=",
"type",
"(",
"current",
")",
"orig_new",
"=",
"new",
"if",
"typ",
"==",
"bool",
":",
"try",
":",
"return",
"bool",
"(",
"int",
"(",
"new",
")"... | Tries to force a new value into the same type as the current when trying to set the value for a parameter.
:param current: current value for the parameter, type varies
:param new: new value
:return: new value with same type as current, or the current value if there was an error casting | [
"Tries",
"to",
"force",
"a",
"new",
"value",
"into",
"the",
"same",
"type",
"as",
"the",
"current",
"when",
"trying",
"to",
"set",
"the",
"value",
"for",
"a",
"parameter",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L103-L132 |
230,184 | python-cmd2/cmd2 | cmd2/utils.py | which | def which(editor: str) -> Optional[str]:
"""Find the full path of a given editor.
Return the full path of the given editor, or None if the editor can
not be found.
:param editor: filename of the editor to check, ie 'notepad.exe' or 'vi'
:return: a full path or None
"""
try:
editor_path = subprocess.check_output(['which', editor], stderr=subprocess.STDOUT).strip()
editor_path = editor_path.decode()
except subprocess.CalledProcessError:
editor_path = None
return editor_path | python | def which(editor: str) -> Optional[str]:
try:
editor_path = subprocess.check_output(['which', editor], stderr=subprocess.STDOUT).strip()
editor_path = editor_path.decode()
except subprocess.CalledProcessError:
editor_path = None
return editor_path | [
"def",
"which",
"(",
"editor",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"try",
":",
"editor_path",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'which'",
",",
"editor",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
... | Find the full path of a given editor.
Return the full path of the given editor, or None if the editor can
not be found.
:param editor: filename of the editor to check, ie 'notepad.exe' or 'vi'
:return: a full path or None | [
"Find",
"the",
"full",
"path",
"of",
"a",
"given",
"editor",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L135-L149 |
230,185 | python-cmd2/cmd2 | cmd2/utils.py | is_text_file | def is_text_file(file_path: str) -> bool:
"""Returns if a file contains only ASCII or UTF-8 encoded text.
:param file_path: path to the file being checked
:return: True if the file is a text file, False if it is binary.
"""
import codecs
expanded_path = os.path.abspath(os.path.expanduser(file_path.strip()))
valid_text_file = False
# Check if the file is ASCII
try:
with codecs.open(expanded_path, encoding='ascii', errors='strict') as f:
# Make sure the file has at least one line of text
# noinspection PyUnusedLocal
if sum(1 for line in f) > 0:
valid_text_file = True
except OSError: # pragma: no cover
pass
except UnicodeDecodeError:
# The file is not ASCII. Check if it is UTF-8.
try:
with codecs.open(expanded_path, encoding='utf-8', errors='strict') as f:
# Make sure the file has at least one line of text
# noinspection PyUnusedLocal
if sum(1 for line in f) > 0:
valid_text_file = True
except OSError: # pragma: no cover
pass
except UnicodeDecodeError:
# Not UTF-8
pass
return valid_text_file | python | def is_text_file(file_path: str) -> bool:
import codecs
expanded_path = os.path.abspath(os.path.expanduser(file_path.strip()))
valid_text_file = False
# Check if the file is ASCII
try:
with codecs.open(expanded_path, encoding='ascii', errors='strict') as f:
# Make sure the file has at least one line of text
# noinspection PyUnusedLocal
if sum(1 for line in f) > 0:
valid_text_file = True
except OSError: # pragma: no cover
pass
except UnicodeDecodeError:
# The file is not ASCII. Check if it is UTF-8.
try:
with codecs.open(expanded_path, encoding='utf-8', errors='strict') as f:
# Make sure the file has at least one line of text
# noinspection PyUnusedLocal
if sum(1 for line in f) > 0:
valid_text_file = True
except OSError: # pragma: no cover
pass
except UnicodeDecodeError:
# Not UTF-8
pass
return valid_text_file | [
"def",
"is_text_file",
"(",
"file_path",
":",
"str",
")",
"->",
"bool",
":",
"import",
"codecs",
"expanded_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"file_path",
".",
"strip",
"(",
")",
")",
")",
"... | Returns if a file contains only ASCII or UTF-8 encoded text.
:param file_path: path to the file being checked
:return: True if the file is a text file, False if it is binary. | [
"Returns",
"if",
"a",
"file",
"contains",
"only",
"ASCII",
"or",
"UTF",
"-",
"8",
"encoded",
"text",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L152-L186 |
230,186 | python-cmd2/cmd2 | cmd2/utils.py | remove_duplicates | def remove_duplicates(list_to_prune: List) -> List:
"""Removes duplicates from a list while preserving order of the items.
:param list_to_prune: the list being pruned of duplicates
:return: The pruned list
"""
temp_dict = collections.OrderedDict()
for item in list_to_prune:
temp_dict[item] = None
return list(temp_dict.keys()) | python | def remove_duplicates(list_to_prune: List) -> List:
temp_dict = collections.OrderedDict()
for item in list_to_prune:
temp_dict[item] = None
return list(temp_dict.keys()) | [
"def",
"remove_duplicates",
"(",
"list_to_prune",
":",
"List",
")",
"->",
"List",
":",
"temp_dict",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"item",
"in",
"list_to_prune",
":",
"temp_dict",
"[",
"item",
"]",
"=",
"None",
"return",
"list",
"... | Removes duplicates from a list while preserving order of the items.
:param list_to_prune: the list being pruned of duplicates
:return: The pruned list | [
"Removes",
"duplicates",
"from",
"a",
"list",
"while",
"preserving",
"order",
"of",
"the",
"items",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L189-L199 |
230,187 | python-cmd2/cmd2 | cmd2/utils.py | alphabetical_sort | def alphabetical_sort(list_to_sort: Iterable[str]) -> List[str]:
"""Sorts a list of strings alphabetically.
For example: ['a1', 'A11', 'A2', 'a22', 'a3']
To sort a list in place, don't call this method, which makes a copy. Instead, do this:
my_list.sort(key=norm_fold)
:param list_to_sort: the list being sorted
:return: the sorted list
"""
return sorted(list_to_sort, key=norm_fold) | python | def alphabetical_sort(list_to_sort: Iterable[str]) -> List[str]:
return sorted(list_to_sort, key=norm_fold) | [
"def",
"alphabetical_sort",
"(",
"list_to_sort",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"sorted",
"(",
"list_to_sort",
",",
"key",
"=",
"norm_fold",
")"
] | Sorts a list of strings alphabetically.
For example: ['a1', 'A11', 'A2', 'a22', 'a3']
To sort a list in place, don't call this method, which makes a copy. Instead, do this:
my_list.sort(key=norm_fold)
:param list_to_sort: the list being sorted
:return: the sorted list | [
"Sorts",
"a",
"list",
"of",
"strings",
"alphabetically",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L211-L223 |
230,188 | python-cmd2/cmd2 | cmd2/utils.py | natural_sort | def natural_sort(list_to_sort: Iterable[str]) -> List[str]:
"""
Sorts a list of strings case insensitively as well as numerically.
For example: ['a1', 'A2', 'a3', 'A11', 'a22']
To sort a list in place, don't call this method, which makes a copy. Instead, do this:
my_list.sort(key=natural_keys)
:param list_to_sort: the list being sorted
:return: the list sorted naturally
"""
return sorted(list_to_sort, key=natural_keys) | python | def natural_sort(list_to_sort: Iterable[str]) -> List[str]:
return sorted(list_to_sort, key=natural_keys) | [
"def",
"natural_sort",
"(",
"list_to_sort",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"sorted",
"(",
"list_to_sort",
",",
"key",
"=",
"natural_keys",
")"
] | Sorts a list of strings case insensitively as well as numerically.
For example: ['a1', 'A2', 'a3', 'A11', 'a22']
To sort a list in place, don't call this method, which makes a copy. Instead, do this:
my_list.sort(key=natural_keys)
:param list_to_sort: the list being sorted
:return: the list sorted naturally | [
"Sorts",
"a",
"list",
"of",
"strings",
"case",
"insensitively",
"as",
"well",
"as",
"numerically",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L249-L262 |
230,189 | python-cmd2/cmd2 | cmd2/utils.py | find_editor | def find_editor() -> str:
"""Find a reasonable editor to use by default for the system that the cmd2 application is running on."""
editor = os.environ.get('EDITOR')
if not editor:
if sys.platform[:3] == 'win':
editor = 'notepad'
else:
# Favor command-line editors first so we don't leave the terminal to edit
for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']:
if which(editor):
break
return editor | python | def find_editor() -> str:
editor = os.environ.get('EDITOR')
if not editor:
if sys.platform[:3] == 'win':
editor = 'notepad'
else:
# Favor command-line editors first so we don't leave the terminal to edit
for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']:
if which(editor):
break
return editor | [
"def",
"find_editor",
"(",
")",
"->",
"str",
":",
"editor",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'EDITOR'",
")",
"if",
"not",
"editor",
":",
"if",
"sys",
".",
"platform",
"[",
":",
"3",
"]",
"==",
"'win'",
":",
"editor",
"=",
"'notepad'",
... | Find a reasonable editor to use by default for the system that the cmd2 application is running on. | [
"Find",
"a",
"reasonable",
"editor",
"to",
"use",
"by",
"default",
"for",
"the",
"system",
"that",
"the",
"cmd2",
"application",
"is",
"running",
"on",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L277-L288 |
230,190 | python-cmd2/cmd2 | cmd2/utils.py | StdSim.write | def write(self, s: str) -> None:
"""Add str to internal bytes buffer and if echo is True, echo contents to inner stream"""
if not isinstance(s, str):
raise TypeError('write() argument must be str, not {}'.format(type(s)))
if not self.pause_storage:
self.buffer.byte_buf += s.encode(encoding=self.encoding, errors=self.errors)
if self.echo:
self.inner_stream.write(s) | python | def write(self, s: str) -> None:
if not isinstance(s, str):
raise TypeError('write() argument must be str, not {}'.format(type(s)))
if not self.pause_storage:
self.buffer.byte_buf += s.encode(encoding=self.encoding, errors=self.errors)
if self.echo:
self.inner_stream.write(s) | [
"def",
"write",
"(",
"self",
",",
"s",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'write() argument must be str, not {}'",
".",
"format",
"(",
"type",
"(",
"s",
")",
")",
... | Add str to internal bytes buffer and if echo is True, echo contents to inner stream | [
"Add",
"str",
"to",
"internal",
"bytes",
"buffer",
"and",
"if",
"echo",
"is",
"True",
"echo",
"contents",
"to",
"inner",
"stream"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L312-L320 |
230,191 | python-cmd2/cmd2 | cmd2/utils.py | StdSim.getvalue | def getvalue(self) -> str:
"""Get the internal contents as a str"""
return self.buffer.byte_buf.decode(encoding=self.encoding, errors=self.errors) | python | def getvalue(self) -> str:
return self.buffer.byte_buf.decode(encoding=self.encoding, errors=self.errors) | [
"def",
"getvalue",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"buffer",
".",
"byte_buf",
".",
"decode",
"(",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"self",
".",
"errors",
")"
] | Get the internal contents as a str | [
"Get",
"the",
"internal",
"contents",
"as",
"a",
"str"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L322-L324 |
230,192 | python-cmd2/cmd2 | cmd2/utils.py | ByteBuf.write | def write(self, b: bytes) -> None:
"""Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream."""
if not isinstance(b, bytes):
raise TypeError('a bytes-like object is required, not {}'.format(type(b)))
if not self.std_sim_instance.pause_storage:
self.byte_buf += b
if self.std_sim_instance.echo:
self.std_sim_instance.inner_stream.buffer.write(b)
# Since StdSim wraps TextIO streams, we will flush the stream if line buffering is on
# and the bytes being written contain a new line character. This is helpful when StdSim
# is being used to capture output of a shell command because it causes the output to print
# to the screen more often than if we waited for the stream to flush its buffer.
if self.std_sim_instance.line_buffering:
if any(newline in b for newline in ByteBuf.NEWLINES):
self.std_sim_instance.flush() | python | def write(self, b: bytes) -> None:
if not isinstance(b, bytes):
raise TypeError('a bytes-like object is required, not {}'.format(type(b)))
if not self.std_sim_instance.pause_storage:
self.byte_buf += b
if self.std_sim_instance.echo:
self.std_sim_instance.inner_stream.buffer.write(b)
# Since StdSim wraps TextIO streams, we will flush the stream if line buffering is on
# and the bytes being written contain a new line character. This is helpful when StdSim
# is being used to capture output of a shell command because it causes the output to print
# to the screen more often than if we waited for the stream to flush its buffer.
if self.std_sim_instance.line_buffering:
if any(newline in b for newline in ByteBuf.NEWLINES):
self.std_sim_instance.flush() | [
"def",
"write",
"(",
"self",
",",
"b",
":",
"bytes",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"b",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'a bytes-like object is required, not {}'",
".",
"format",
"(",
"type",
"(",
"b",
")",
... | Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream. | [
"Add",
"bytes",
"to",
"internal",
"bytes",
"buffer",
"and",
"if",
"echo",
"is",
"True",
"echo",
"contents",
"to",
"inner",
"stream",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L382-L397 |
230,193 | python-cmd2/cmd2 | examples/hooks.py | CmdLineApp.add_whitespace_hook | def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""A hook to split alphabetic command names immediately followed by a number.
l24 -> l 24
list24 -> list 24
list 24 -> list 24
"""
command = data.statement.command
# regular expression with looks for:
# ^ - the beginning of the string
# ([^\s\d]+) - one or more non-whitespace non-digit characters, set as capture group 1
# (\d+) - one or more digit characters, set as capture group 2
command_pattern = re.compile(r'^([^\s\d]+)(\d+)')
match = command_pattern.search(command)
if match:
data.statement = self.statement_parser.parse("{} {} {}".format(
match.group(1),
match.group(2),
'' if data.statement.args is None else data.statement.args
))
return data | python | def add_whitespace_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
command = data.statement.command
# regular expression with looks for:
# ^ - the beginning of the string
# ([^\s\d]+) - one or more non-whitespace non-digit characters, set as capture group 1
# (\d+) - one or more digit characters, set as capture group 2
command_pattern = re.compile(r'^([^\s\d]+)(\d+)')
match = command_pattern.search(command)
if match:
data.statement = self.statement_parser.parse("{} {} {}".format(
match.group(1),
match.group(2),
'' if data.statement.args is None else data.statement.args
))
return data | [
"def",
"add_whitespace_hook",
"(",
"self",
",",
"data",
":",
"cmd2",
".",
"plugin",
".",
"PostparsingData",
")",
"->",
"cmd2",
".",
"plugin",
".",
"PostparsingData",
":",
"command",
"=",
"data",
".",
"statement",
".",
"command",
"# regular expression with looks ... | A hook to split alphabetic command names immediately followed by a number.
l24 -> l 24
list24 -> list 24
list 24 -> list 24 | [
"A",
"hook",
"to",
"split",
"alphabetic",
"command",
"names",
"immediately",
"followed",
"by",
"a",
"number",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/hooks.py#L53-L74 |
230,194 | python-cmd2/cmd2 | examples/hooks.py | CmdLineApp.downcase_hook | def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""A hook to make uppercase commands lowercase."""
command = data.statement.command.lower()
data.statement = self.statement_parser.parse("{} {}".format(
command,
'' if data.statement.args is None else data.statement.args
))
return data | python | def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
command = data.statement.command.lower()
data.statement = self.statement_parser.parse("{} {}".format(
command,
'' if data.statement.args is None else data.statement.args
))
return data | [
"def",
"downcase_hook",
"(",
"self",
",",
"data",
":",
"cmd2",
".",
"plugin",
".",
"PostparsingData",
")",
"->",
"cmd2",
".",
"plugin",
".",
"PostparsingData",
":",
"command",
"=",
"data",
".",
"statement",
".",
"command",
".",
"lower",
"(",
")",
"data",... | A hook to make uppercase commands lowercase. | [
"A",
"hook",
"to",
"make",
"uppercase",
"commands",
"lowercase",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/hooks.py#L76-L83 |
230,195 | python-cmd2/cmd2 | examples/hooks.py | CmdLineApp.abbrev_hook | def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""Accept unique abbreviated commands"""
func = self.cmd_func(data.statement.command)
if func is None:
# check if the entered command might be an abbreviation
possible_cmds = [cmd for cmd in self.get_all_commands() if cmd.startswith(data.statement.command)]
if len(possible_cmds) == 1:
raw = data.statement.raw.replace(data.statement.command, possible_cmds[0], 1)
data.statement = self.statement_parser.parse(raw)
return data | python | def abbrev_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
func = self.cmd_func(data.statement.command)
if func is None:
# check if the entered command might be an abbreviation
possible_cmds = [cmd for cmd in self.get_all_commands() if cmd.startswith(data.statement.command)]
if len(possible_cmds) == 1:
raw = data.statement.raw.replace(data.statement.command, possible_cmds[0], 1)
data.statement = self.statement_parser.parse(raw)
return data | [
"def",
"abbrev_hook",
"(",
"self",
",",
"data",
":",
"cmd2",
".",
"plugin",
".",
"PostparsingData",
")",
"->",
"cmd2",
".",
"plugin",
".",
"PostparsingData",
":",
"func",
"=",
"self",
".",
"cmd_func",
"(",
"data",
".",
"statement",
".",
"command",
")",
... | Accept unique abbreviated commands | [
"Accept",
"unique",
"abbreviated",
"commands"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/hooks.py#L85-L94 |
230,196 | python-cmd2/cmd2 | examples/hooks.py | CmdLineApp.do_list | def do_list(self, arglist: List[str]) -> None:
"""Generate a list of 10 numbers."""
if arglist:
first = arglist[0]
try:
first = int(first)
except ValueError:
first = 1
else:
first = 1
last = first + 10
for x in range(first, last):
self.poutput(str(x)) | python | def do_list(self, arglist: List[str]) -> None:
if arglist:
first = arglist[0]
try:
first = int(first)
except ValueError:
first = 1
else:
first = 1
last = first + 10
for x in range(first, last):
self.poutput(str(x)) | [
"def",
"do_list",
"(",
"self",
",",
"arglist",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"if",
"arglist",
":",
"first",
"=",
"arglist",
"[",
"0",
"]",
"try",
":",
"first",
"=",
"int",
"(",
"first",
")",
"except",
"ValueError",
":",
"f... | Generate a list of 10 numbers. | [
"Generate",
"a",
"list",
"of",
"10",
"numbers",
"."
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/hooks.py#L97-L110 |
230,197 | python-cmd2/cmd2 | examples/subcommands.py | SubcommandsExample.do_base | def do_base(self, args):
"""Base command help"""
func = getattr(args, 'func', None)
if func is not None:
# Call whatever sub-command function was selected
func(self, args)
else:
# No sub-command was provided, so call help
self.do_help('base') | python | def do_base(self, args):
func = getattr(args, 'func', None)
if func is not None:
# Call whatever sub-command function was selected
func(self, args)
else:
# No sub-command was provided, so call help
self.do_help('base') | [
"def",
"do_base",
"(",
"self",
",",
"args",
")",
":",
"func",
"=",
"getattr",
"(",
"args",
",",
"'func'",
",",
"None",
")",
"if",
"func",
"is",
"not",
"None",
":",
"# Call whatever sub-command function was selected",
"func",
"(",
"self",
",",
"args",
")",
... | Base command help | [
"Base",
"command",
"help"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/subcommands.py#L94-L102 |
230,198 | python-cmd2/cmd2 | examples/subcommands.py | SubcommandsExample.do_alternate | def do_alternate(self, args):
"""Alternate command help"""
func = getattr(args, 'func', None)
if func is not None:
# Call whatever sub-command function was selected
func(self, args)
else:
# No sub-command was provided, so call help
self.do_help('alternate') | python | def do_alternate(self, args):
func = getattr(args, 'func', None)
if func is not None:
# Call whatever sub-command function was selected
func(self, args)
else:
# No sub-command was provided, so call help
self.do_help('alternate') | [
"def",
"do_alternate",
"(",
"self",
",",
"args",
")",
":",
"func",
"=",
"getattr",
"(",
"args",
",",
"'func'",
",",
"None",
")",
"if",
"func",
"is",
"not",
"None",
":",
"# Call whatever sub-command function was selected",
"func",
"(",
"self",
",",
"args",
... | Alternate command help | [
"Alternate",
"command",
"help"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/subcommands.py#L105-L113 |
230,199 | python-cmd2/cmd2 | examples/cmd_as_argument.py | main | def main(argv=None):
"""Run when invoked from the operating system shell"""
parser = argparse.ArgumentParser(
description='Commands as arguments'
)
command_help = 'optional command to run, if no command given, enter an interactive shell'
parser.add_argument('command', nargs='?',
help=command_help)
arg_help = 'optional arguments for command'
parser.add_argument('command_args', nargs=argparse.REMAINDER,
help=arg_help)
args = parser.parse_args(argv)
c = CmdLineApp()
if args.command:
# we have a command, run it and then exit
c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args)))
else:
# we have no command, drop into interactive mode
c.cmdloop() | python | def main(argv=None):
parser = argparse.ArgumentParser(
description='Commands as arguments'
)
command_help = 'optional command to run, if no command given, enter an interactive shell'
parser.add_argument('command', nargs='?',
help=command_help)
arg_help = 'optional arguments for command'
parser.add_argument('command_args', nargs=argparse.REMAINDER,
help=arg_help)
args = parser.parse_args(argv)
c = CmdLineApp()
if args.command:
# we have a command, run it and then exit
c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args)))
else:
# we have no command, drop into interactive mode
c.cmdloop() | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Commands as arguments'",
")",
"command_help",
"=",
"'optional command to run, if no command given, enter an interactive shell'",
"parser",
".",
... | Run when invoked from the operating system shell | [
"Run",
"when",
"invoked",
"from",
"the",
"operating",
"system",
"shell"
] | b22c0bd891ed08c8b09df56df9d91f48166a5e2a | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/cmd_as_argument.py#L87-L109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.