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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
defunkt/pystache | pystache/renderer.py | Renderer.render_path | def render_path(self, template_path, *context, **kwargs):
"""
Render the template at the given path using the given context.
Read the render() docstring for more information.
"""
loader = self._make_loader()
template = loader.read(template_path)
return self._render_string(template, *context, **kwargs) | python | def render_path(self, template_path, *context, **kwargs):
"""
Render the template at the given path using the given context.
Read the render() docstring for more information.
"""
loader = self._make_loader()
template = loader.read(template_path)
return self._render_string(template, *context, **kwargs) | [
"def",
"render_path",
"(",
"self",
",",
"template_path",
",",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"loader",
"=",
"self",
".",
"_make_loader",
"(",
")",
"template",
"=",
"loader",
".",
"read",
"(",
"template_path",
")",
"return",
"self",
... | Render the template at the given path using the given context.
Read the render() docstring for more information. | [
"Render",
"the",
"template",
"at",
"the",
"given",
"path",
"using",
"the",
"given",
"context",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L380-L390 | train | 207,100 |
defunkt/pystache | pystache/renderer.py | Renderer._render_string | def _render_string(self, template, *context, **kwargs):
"""
Render the given template string using the given context.
"""
# RenderEngine.render() requires that the template string be unicode.
template = self._to_unicode_hard(template)
render_func = lambda engine, stack: engine.render(template, stack)
return self._render_final(render_func, *context, **kwargs) | python | def _render_string(self, template, *context, **kwargs):
"""
Render the given template string using the given context.
"""
# RenderEngine.render() requires that the template string be unicode.
template = self._to_unicode_hard(template)
render_func = lambda engine, stack: engine.render(template, stack)
return self._render_final(render_func, *context, **kwargs) | [
"def",
"_render_string",
"(",
"self",
",",
"template",
",",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"# RenderEngine.render() requires that the template string be unicode.",
"template",
"=",
"self",
".",
"_to_unicode_hard",
"(",
"template",
")",
"render_func... | Render the given template string using the given context. | [
"Render",
"the",
"given",
"template",
"string",
"using",
"the",
"given",
"context",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L392-L402 | train | 207,101 |
defunkt/pystache | pystache/renderer.py | Renderer.render | def render(self, template, *context, **kwargs):
"""
Render the given template string, view template, or parsed template.
Returns a unicode string.
Prior to rendering, this method will convert a template that is a
byte string (type str in Python 2) to unicode using the string_encoding
and decode_errors attributes. See the constructor docstring for
more information.
Arguments:
template: a template string that is unicode or a byte string,
a ParsedTemplate instance, or another object instance. In the
final case, the function first looks for the template associated
to the object by calling this class's get_associated_template()
method. The rendering process also uses the passed object as
the first element of the context stack when rendering.
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments are skipped. Items in the *context list are added to
the context stack in order so that later items in the argument
list take precedence over earlier items.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list.
"""
if is_string(template):
return self._render_string(template, *context, **kwargs)
if isinstance(template, ParsedTemplate):
render_func = lambda engine, stack: template.render(engine, stack)
return self._render_final(render_func, *context, **kwargs)
# Otherwise, we assume the template is an object.
return self._render_object(template, *context, **kwargs) | python | def render(self, template, *context, **kwargs):
"""
Render the given template string, view template, or parsed template.
Returns a unicode string.
Prior to rendering, this method will convert a template that is a
byte string (type str in Python 2) to unicode using the string_encoding
and decode_errors attributes. See the constructor docstring for
more information.
Arguments:
template: a template string that is unicode or a byte string,
a ParsedTemplate instance, or another object instance. In the
final case, the function first looks for the template associated
to the object by calling this class's get_associated_template()
method. The rendering process also uses the passed object as
the first element of the context stack when rendering.
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments are skipped. Items in the *context list are added to
the context stack in order so that later items in the argument
list take precedence over earlier items.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list.
"""
if is_string(template):
return self._render_string(template, *context, **kwargs)
if isinstance(template, ParsedTemplate):
render_func = lambda engine, stack: template.render(engine, stack)
return self._render_final(render_func, *context, **kwargs)
# Otherwise, we assume the template is an object.
return self._render_object(template, *context, **kwargs) | [
"def",
"render",
"(",
"self",
",",
"template",
",",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"is_string",
"(",
"template",
")",
":",
"return",
"self",
".",
"_render_string",
"(",
"template",
",",
"*",
"context",
",",
"*",
"*",
"kwargs... | Render the given template string, view template, or parsed template.
Returns a unicode string.
Prior to rendering, this method will convert a template that is a
byte string (type str in Python 2) to unicode using the string_encoding
and decode_errors attributes. See the constructor docstring for
more information.
Arguments:
template: a template string that is unicode or a byte string,
a ParsedTemplate instance, or another object instance. In the
final case, the function first looks for the template associated
to the object by calling this class's get_associated_template()
method. The rendering process also uses the passed object as
the first element of the context stack when rendering.
*context: zero or more dictionaries, ContextStack instances, or objects
with which to populate the initial context stack. None
arguments are skipped. Items in the *context list are added to
the context stack in order so that later items in the argument
list take precedence over earlier items.
**kwargs: additional key-value data to add to the context stack.
As these arguments appear after all items in the *context list,
in the case of key conflicts these values take precedence over
all items in the *context list. | [
"Render",
"the",
"given",
"template",
"string",
"view",
"template",
"or",
"parsed",
"template",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L421-L460 | train | 207,102 |
defunkt/pystache | setup.py | read | def read(path):
"""
Read and return the contents of a text file as a unicode string.
"""
# This function implementation was chosen to be compatible across Python 2/3.
f = open(path, 'rb')
# We avoid use of the with keyword for Python 2.4 support.
try:
b = f.read()
finally:
f.close()
return b.decode(FILE_ENCODING) | python | def read(path):
"""
Read and return the contents of a text file as a unicode string.
"""
# This function implementation was chosen to be compatible across Python 2/3.
f = open(path, 'rb')
# We avoid use of the with keyword for Python 2.4 support.
try:
b = f.read()
finally:
f.close()
return b.decode(FILE_ENCODING) | [
"def",
"read",
"(",
"path",
")",
":",
"# This function implementation was chosen to be compatible across Python 2/3.",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"# We avoid use of the with keyword for Python 2.4 support.",
"try",
":",
"b",
"=",
"f",
".",
"read",
... | Read and return the contents of a text file as a unicode string. | [
"Read",
"and",
"return",
"the",
"contents",
"of",
"a",
"text",
"file",
"as",
"a",
"unicode",
"string",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/setup.py#L152-L165 | train | 207,103 |
defunkt/pystache | setup.py | strip_html_comments | def strip_html_comments(text):
"""Strip HTML comments from a unicode string."""
lines = text.splitlines(True) # preserve line endings.
# Remove HTML comments (which we only allow to take a special form).
new_lines = filter(lambda line: not line.startswith("<!--"), lines)
return "".join(new_lines) | python | def strip_html_comments(text):
"""Strip HTML comments from a unicode string."""
lines = text.splitlines(True) # preserve line endings.
# Remove HTML comments (which we only allow to take a special form).
new_lines = filter(lambda line: not line.startswith("<!--"), lines)
return "".join(new_lines) | [
"def",
"strip_html_comments",
"(",
"text",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
"True",
")",
"# preserve line endings.",
"# Remove HTML comments (which we only allow to take a special form).",
"new_lines",
"=",
"filter",
"(",
"lambda",
"line",
":",
"n... | Strip HTML comments from a unicode string. | [
"Strip",
"HTML",
"comments",
"from",
"a",
"unicode",
"string",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/setup.py#L198-L205 | train | 207,104 |
defunkt/pystache | setup.py | convert_md_to_rst | def convert_md_to_rst(md_path, rst_temp_path):
"""
Convert the contents of a file from Markdown to reStructuredText.
Returns the converted text as a Unicode string.
Arguments:
md_path: a path to a UTF-8 encoded Markdown file to convert.
rst_temp_path: a temporary path to which to write the converted contents.
"""
# Pandoc uses the UTF-8 character encoding for both input and output.
command = "pandoc --write=rst --output=%s %s" % (rst_temp_path, md_path)
print("converting with pandoc: %s to %s\n-->%s" % (md_path, rst_temp_path,
command))
if os.path.exists(rst_temp_path):
os.remove(rst_temp_path)
os.system(command)
if not os.path.exists(rst_temp_path):
s = ("Error running: %s\n"
" Did you install pandoc per the %s docstring?" % (command,
__file__))
sys.exit(s)
return read(rst_temp_path) | python | def convert_md_to_rst(md_path, rst_temp_path):
"""
Convert the contents of a file from Markdown to reStructuredText.
Returns the converted text as a Unicode string.
Arguments:
md_path: a path to a UTF-8 encoded Markdown file to convert.
rst_temp_path: a temporary path to which to write the converted contents.
"""
# Pandoc uses the UTF-8 character encoding for both input and output.
command = "pandoc --write=rst --output=%s %s" % (rst_temp_path, md_path)
print("converting with pandoc: %s to %s\n-->%s" % (md_path, rst_temp_path,
command))
if os.path.exists(rst_temp_path):
os.remove(rst_temp_path)
os.system(command)
if not os.path.exists(rst_temp_path):
s = ("Error running: %s\n"
" Did you install pandoc per the %s docstring?" % (command,
__file__))
sys.exit(s)
return read(rst_temp_path) | [
"def",
"convert_md_to_rst",
"(",
"md_path",
",",
"rst_temp_path",
")",
":",
"# Pandoc uses the UTF-8 character encoding for both input and output.",
"command",
"=",
"\"pandoc --write=rst --output=%s %s\"",
"%",
"(",
"rst_temp_path",
",",
"md_path",
")",
"print",
"(",
"\"conve... | Convert the contents of a file from Markdown to reStructuredText.
Returns the converted text as a Unicode string.
Arguments:
md_path: a path to a UTF-8 encoded Markdown file to convert.
rst_temp_path: a temporary path to which to write the converted contents. | [
"Convert",
"the",
"contents",
"of",
"a",
"file",
"from",
"Markdown",
"to",
"reStructuredText",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/setup.py#L210-L239 | train | 207,105 |
defunkt/pystache | pystache/locator.py | Locator.get_object_directory | def get_object_directory(self, obj):
"""
Return the directory containing an object's defining class.
Returns None if there is no such directory, for example if the
class was defined in an interactive Python session, or in a
doctest that appears in a text file (rather than a Python file).
"""
if not hasattr(obj, '__module__'):
return None
module = sys.modules[obj.__module__]
if not hasattr(module, '__file__'):
# TODO: add a unit test for this case.
return None
path = module.__file__
return os.path.dirname(path) | python | def get_object_directory(self, obj):
"""
Return the directory containing an object's defining class.
Returns None if there is no such directory, for example if the
class was defined in an interactive Python session, or in a
doctest that appears in a text file (rather than a Python file).
"""
if not hasattr(obj, '__module__'):
return None
module = sys.modules[obj.__module__]
if not hasattr(module, '__file__'):
# TODO: add a unit test for this case.
return None
path = module.__file__
return os.path.dirname(path) | [
"def",
"get_object_directory",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'__module__'",
")",
":",
"return",
"None",
"module",
"=",
"sys",
".",
"modules",
"[",
"obj",
".",
"__module__",
"]",
"if",
"not",
"hasattr",
"("... | Return the directory containing an object's defining class.
Returns None if there is no such directory, for example if the
class was defined in an interactive Python session, or in a
doctest that appears in a text file (rather than a Python file). | [
"Return",
"the",
"directory",
"containing",
"an",
"object",
"s",
"defining",
"class",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L34-L54 | train | 207,106 |
defunkt/pystache | pystache/locator.py | Locator.make_template_name | def make_template_name(self, obj):
"""
Return the canonical template name for an object instance.
This method converts Python-style class names (PEP 8's recommended
CamelCase, aka CapWords) to lower_case_with_underscords. Here
is an example with code:
>>> class HelloWorld(object):
... pass
>>> hi = HelloWorld()
>>>
>>> locator = Locator()
>>> locator.make_template_name(hi)
'hello_world'
"""
template_name = obj.__class__.__name__
def repl(match):
return '_' + match.group(0).lower()
return re.sub('[A-Z]', repl, template_name)[1:] | python | def make_template_name(self, obj):
"""
Return the canonical template name for an object instance.
This method converts Python-style class names (PEP 8's recommended
CamelCase, aka CapWords) to lower_case_with_underscords. Here
is an example with code:
>>> class HelloWorld(object):
... pass
>>> hi = HelloWorld()
>>>
>>> locator = Locator()
>>> locator.make_template_name(hi)
'hello_world'
"""
template_name = obj.__class__.__name__
def repl(match):
return '_' + match.group(0).lower()
return re.sub('[A-Z]', repl, template_name)[1:] | [
"def",
"make_template_name",
"(",
"self",
",",
"obj",
")",
":",
"template_name",
"=",
"obj",
".",
"__class__",
".",
"__name__",
"def",
"repl",
"(",
"match",
")",
":",
"return",
"'_'",
"+",
"match",
".",
"group",
"(",
"0",
")",
".",
"lower",
"(",
")",... | Return the canonical template name for an object instance.
This method converts Python-style class names (PEP 8's recommended
CamelCase, aka CapWords) to lower_case_with_underscords. Here
is an example with code:
>>> class HelloWorld(object):
... pass
>>> hi = HelloWorld()
>>>
>>> locator = Locator()
>>> locator.make_template_name(hi)
'hello_world' | [
"Return",
"the",
"canonical",
"template",
"name",
"for",
"an",
"object",
"instance",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L56-L78 | train | 207,107 |
defunkt/pystache | pystache/locator.py | Locator.make_file_name | def make_file_name(self, template_name, template_extension=None):
"""
Generate and return the file name for the given template name.
Arguments:
template_extension: defaults to the instance's extension.
"""
file_name = template_name
if template_extension is None:
template_extension = self.template_extension
if template_extension is not False:
file_name += os.path.extsep + template_extension
return file_name | python | def make_file_name(self, template_name, template_extension=None):
"""
Generate and return the file name for the given template name.
Arguments:
template_extension: defaults to the instance's extension.
"""
file_name = template_name
if template_extension is None:
template_extension = self.template_extension
if template_extension is not False:
file_name += os.path.extsep + template_extension
return file_name | [
"def",
"make_file_name",
"(",
"self",
",",
"template_name",
",",
"template_extension",
"=",
"None",
")",
":",
"file_name",
"=",
"template_name",
"if",
"template_extension",
"is",
"None",
":",
"template_extension",
"=",
"self",
".",
"template_extension",
"if",
"tem... | Generate and return the file name for the given template name.
Arguments:
template_extension: defaults to the instance's extension. | [
"Generate",
"and",
"return",
"the",
"file",
"name",
"for",
"the",
"given",
"template",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L80-L97 | train | 207,108 |
defunkt/pystache | pystache/locator.py | Locator._find_path | def _find_path(self, search_dirs, file_name):
"""
Search for the given file, and return the path.
Returns None if the file is not found.
"""
for dir_path in search_dirs:
file_path = os.path.join(dir_path, file_name)
if os.path.exists(file_path):
return file_path
return None | python | def _find_path(self, search_dirs, file_name):
"""
Search for the given file, and return the path.
Returns None if the file is not found.
"""
for dir_path in search_dirs:
file_path = os.path.join(dir_path, file_name)
if os.path.exists(file_path):
return file_path
return None | [
"def",
"_find_path",
"(",
"self",
",",
"search_dirs",
",",
"file_name",
")",
":",
"for",
"dir_path",
"in",
"search_dirs",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"file_name",
")",
"if",
"os",
".",
"path",
".",
"exis... | Search for the given file, and return the path.
Returns None if the file is not found. | [
"Search",
"for",
"the",
"given",
"file",
"and",
"return",
"the",
"path",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L99-L111 | train | 207,109 |
defunkt/pystache | pystache/locator.py | Locator._find_path_required | def _find_path_required(self, search_dirs, file_name):
"""
Return the path to a template with the given file name.
"""
path = self._find_path(search_dirs, file_name)
if path is None:
raise TemplateNotFoundError('File %s not found in dirs: %s' %
(repr(file_name), repr(search_dirs)))
return path | python | def _find_path_required(self, search_dirs, file_name):
"""
Return the path to a template with the given file name.
"""
path = self._find_path(search_dirs, file_name)
if path is None:
raise TemplateNotFoundError('File %s not found in dirs: %s' %
(repr(file_name), repr(search_dirs)))
return path | [
"def",
"_find_path_required",
"(",
"self",
",",
"search_dirs",
",",
"file_name",
")",
":",
"path",
"=",
"self",
".",
"_find_path",
"(",
"search_dirs",
",",
"file_name",
")",
"if",
"path",
"is",
"None",
":",
"raise",
"TemplateNotFoundError",
"(",
"'File %s not ... | Return the path to a template with the given file name. | [
"Return",
"the",
"path",
"to",
"a",
"template",
"with",
"the",
"given",
"file",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L113-L124 | train | 207,110 |
defunkt/pystache | pystache/locator.py | Locator.find_name | def find_name(self, template_name, search_dirs):
"""
Return the path to a template with the given name.
Arguments:
template_name: the name of the template.
search_dirs: the list of directories in which to search.
"""
file_name = self.make_file_name(template_name)
return self._find_path_required(search_dirs, file_name) | python | def find_name(self, template_name, search_dirs):
"""
Return the path to a template with the given name.
Arguments:
template_name: the name of the template.
search_dirs: the list of directories in which to search.
"""
file_name = self.make_file_name(template_name)
return self._find_path_required(search_dirs, file_name) | [
"def",
"find_name",
"(",
"self",
",",
"template_name",
",",
"search_dirs",
")",
":",
"file_name",
"=",
"self",
".",
"make_file_name",
"(",
"template_name",
")",
"return",
"self",
".",
"_find_path_required",
"(",
"search_dirs",
",",
"file_name",
")"
] | Return the path to a template with the given name.
Arguments:
template_name: the name of the template.
search_dirs: the list of directories in which to search. | [
"Return",
"the",
"path",
"to",
"a",
"template",
"with",
"the",
"given",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L139-L152 | train | 207,111 |
defunkt/pystache | pystache/locator.py | Locator.find_object | def find_object(self, obj, search_dirs, file_name=None):
"""
Return the path to a template associated with the given object.
"""
if file_name is None:
# TODO: should we define a make_file_name() method?
template_name = self.make_template_name(obj)
file_name = self.make_file_name(template_name)
dir_path = self.get_object_directory(obj)
if dir_path is not None:
search_dirs = [dir_path] + search_dirs
path = self._find_path_required(search_dirs, file_name)
return path | python | def find_object(self, obj, search_dirs, file_name=None):
"""
Return the path to a template associated with the given object.
"""
if file_name is None:
# TODO: should we define a make_file_name() method?
template_name = self.make_template_name(obj)
file_name = self.make_file_name(template_name)
dir_path = self.get_object_directory(obj)
if dir_path is not None:
search_dirs = [dir_path] + search_dirs
path = self._find_path_required(search_dirs, file_name)
return path | [
"def",
"find_object",
"(",
"self",
",",
"obj",
",",
"search_dirs",
",",
"file_name",
"=",
"None",
")",
":",
"if",
"file_name",
"is",
"None",
":",
"# TODO: should we define a make_file_name() method?",
"template_name",
"=",
"self",
".",
"make_template_name",
"(",
"... | Return the path to a template associated with the given object. | [
"Return",
"the",
"path",
"to",
"a",
"template",
"associated",
"with",
"the",
"given",
"object",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L154-L171 | train | 207,112 |
defunkt/pystache | pystache/loader.py | Loader.unicode | def unicode(self, s, encoding=None):
"""
Convert a string to unicode using the given encoding, and return it.
This function uses the underlying to_unicode attribute.
Arguments:
s: a basestring instance to convert to unicode. Unlike Python's
built-in unicode() function, it is okay to pass unicode strings
to this function. (Passing a unicode string to Python's unicode()
with the encoding argument throws the error, "TypeError: decoding
Unicode is not supported.")
encoding: the encoding to pass to the to_unicode attribute.
Defaults to None.
"""
if isinstance(s, unicode):
return unicode(s)
return self.to_unicode(s, encoding) | python | def unicode(self, s, encoding=None):
"""
Convert a string to unicode using the given encoding, and return it.
This function uses the underlying to_unicode attribute.
Arguments:
s: a basestring instance to convert to unicode. Unlike Python's
built-in unicode() function, it is okay to pass unicode strings
to this function. (Passing a unicode string to Python's unicode()
with the encoding argument throws the error, "TypeError: decoding
Unicode is not supported.")
encoding: the encoding to pass to the to_unicode attribute.
Defaults to None.
"""
if isinstance(s, unicode):
return unicode(s)
return self.to_unicode(s, encoding) | [
"def",
"unicode",
"(",
"self",
",",
"s",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"unicode",
"(",
"s",
")",
"return",
"self",
".",
"to_unicode",
"(",
"s",
",",
"encoding",
")"
] | Convert a string to unicode using the given encoding, and return it.
This function uses the underlying to_unicode attribute.
Arguments:
s: a basestring instance to convert to unicode. Unlike Python's
built-in unicode() function, it is okay to pass unicode strings
to this function. (Passing a unicode string to Python's unicode()
with the encoding argument throws the error, "TypeError: decoding
Unicode is not supported.")
encoding: the encoding to pass to the to_unicode attribute.
Defaults to None. | [
"Convert",
"a",
"string",
"to",
"unicode",
"using",
"the",
"given",
"encoding",
"and",
"return",
"it",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L89-L110 | train | 207,113 |
defunkt/pystache | pystache/loader.py | Loader.read | def read(self, path, encoding=None):
"""
Read the template at the given path, and return it as a unicode string.
"""
b = common.read(path)
if encoding is None:
encoding = self.file_encoding
return self.unicode(b, encoding) | python | def read(self, path, encoding=None):
"""
Read the template at the given path, and return it as a unicode string.
"""
b = common.read(path)
if encoding is None:
encoding = self.file_encoding
return self.unicode(b, encoding) | [
"def",
"read",
"(",
"self",
",",
"path",
",",
"encoding",
"=",
"None",
")",
":",
"b",
"=",
"common",
".",
"read",
"(",
"path",
")",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"self",
".",
"file_encoding",
"return",
"self",
".",
"unicode",
... | Read the template at the given path, and return it as a unicode string. | [
"Read",
"the",
"template",
"at",
"the",
"given",
"path",
"and",
"return",
"it",
"as",
"a",
"unicode",
"string",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L112-L122 | train | 207,114 |
defunkt/pystache | pystache/loader.py | Loader.load_file | def load_file(self, file_name):
"""
Find and return the template with the given file name.
Arguments:
file_name: the file name of the template.
"""
locator = self._make_locator()
path = locator.find_file(file_name, self.search_dirs)
return self.read(path) | python | def load_file(self, file_name):
"""
Find and return the template with the given file name.
Arguments:
file_name: the file name of the template.
"""
locator = self._make_locator()
path = locator.find_file(file_name, self.search_dirs)
return self.read(path) | [
"def",
"load_file",
"(",
"self",
",",
"file_name",
")",
":",
"locator",
"=",
"self",
".",
"_make_locator",
"(",
")",
"path",
"=",
"locator",
".",
"find_file",
"(",
"file_name",
",",
"self",
".",
"search_dirs",
")",
"return",
"self",
".",
"read",
"(",
"... | Find and return the template with the given file name.
Arguments:
file_name: the file name of the template. | [
"Find",
"and",
"return",
"the",
"template",
"with",
"the",
"given",
"file",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L124-L137 | train | 207,115 |
defunkt/pystache | pystache/loader.py | Loader.load_name | def load_name(self, name):
"""
Find and return the template with the given template name.
Arguments:
name: the name of the template.
"""
locator = self._make_locator()
path = locator.find_name(name, self.search_dirs)
return self.read(path) | python | def load_name(self, name):
"""
Find and return the template with the given template name.
Arguments:
name: the name of the template.
"""
locator = self._make_locator()
path = locator.find_name(name, self.search_dirs)
return self.read(path) | [
"def",
"load_name",
"(",
"self",
",",
"name",
")",
":",
"locator",
"=",
"self",
".",
"_make_locator",
"(",
")",
"path",
"=",
"locator",
".",
"find_name",
"(",
"name",
",",
"self",
".",
"search_dirs",
")",
"return",
"self",
".",
"read",
"(",
"path",
"... | Find and return the template with the given template name.
Arguments:
name: the name of the template. | [
"Find",
"and",
"return",
"the",
"template",
"with",
"the",
"given",
"template",
"name",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L139-L152 | train | 207,116 |
defunkt/pystache | pystache/loader.py | Loader.load_object | def load_object(self, obj):
"""
Find and return the template associated to the given object.
Arguments:
obj: an instance of a user-defined class.
search_dirs: the list of directories in which to search.
"""
locator = self._make_locator()
path = locator.find_object(obj, self.search_dirs)
return self.read(path) | python | def load_object(self, obj):
"""
Find and return the template associated to the given object.
Arguments:
obj: an instance of a user-defined class.
search_dirs: the list of directories in which to search.
"""
locator = self._make_locator()
path = locator.find_object(obj, self.search_dirs)
return self.read(path) | [
"def",
"load_object",
"(",
"self",
",",
"obj",
")",
":",
"locator",
"=",
"self",
".",
"_make_locator",
"(",
")",
"path",
"=",
"locator",
".",
"find_object",
"(",
"obj",
",",
"self",
".",
"search_dirs",
")",
"return",
"self",
".",
"read",
"(",
"path",
... | Find and return the template associated to the given object.
Arguments:
obj: an instance of a user-defined class.
search_dirs: the list of directories in which to search. | [
"Find",
"and",
"return",
"the",
"template",
"associated",
"to",
"the",
"given",
"object",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L155-L170 | train | 207,117 |
defunkt/pystache | pystache/parser.py | parse | def parse(template, delimiters=None):
"""
Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', '') # This is a hack to get the test to pass both in Python 2 and 3.
['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])]
"""
if type(template) is not unicode:
raise Exception("Template is not unicode: %s" % type(template))
parser = _Parser(delimiters)
return parser.parse(template) | python | def parse(template, delimiters=None):
"""
Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', '') # This is a hack to get the test to pass both in Python 2 and 3.
['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])]
"""
if type(template) is not unicode:
raise Exception("Template is not unicode: %s" % type(template))
parser = _Parser(delimiters)
return parser.parse(template) | [
"def",
"parse",
"(",
"template",
",",
"delimiters",
"=",
"None",
")",
":",
"if",
"type",
"(",
"template",
")",
"is",
"not",
"unicode",
":",
"raise",
"Exception",
"(",
"\"Template is not unicode: %s\"",
"%",
"type",
"(",
"template",
")",
")",
"parser",
"=",... | Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', '') # This is a hack to get the test to pass both in Python 2 and 3.
['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])] | [
"Parse",
"a",
"unicode",
"template",
"string",
"and",
"return",
"a",
"ParsedTemplate",
"instance",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L21-L41 | train | 207,118 |
defunkt/pystache | pystache/parser.py | _Parser.parse | def parse(self, template):
"""
Parse a template string starting at some index.
This method uses the current tag delimiter.
Arguments:
template: a unicode string that is the template to parse.
index: the index at which to start parsing.
Returns:
a ParsedTemplate instance.
"""
self._compile_delimiters()
start_index = 0
content_end_index, parsed_section, section_key = None, None, None
parsed_template = ParsedTemplate()
states = []
while True:
match = self._template_re.search(template, start_index)
if match is None:
break
match_index = match.start()
end_index = match.end()
matches = match.groupdict()
# Normalize the matches dictionary.
if matches['change'] is not None:
matches.update(tag='=', tag_key=matches['delims'])
elif matches['raw'] is not None:
matches.update(tag='&', tag_key=matches['raw_name'])
tag_type = matches['tag']
tag_key = matches['tag_key']
leading_whitespace = matches['whitespace']
# Standalone (non-interpolation) tags consume the entire line,
# both leading whitespace and trailing newline.
did_tag_begin_line = match_index == 0 or template[match_index - 1] in END_OF_LINE_CHARACTERS
did_tag_end_line = end_index == len(template) or template[end_index] in END_OF_LINE_CHARACTERS
is_tag_interpolating = tag_type in ['', '&']
if did_tag_begin_line and did_tag_end_line and not is_tag_interpolating:
if end_index < len(template):
end_index += template[end_index] == '\r' and 1 or 0
if end_index < len(template):
end_index += template[end_index] == '\n' and 1 or 0
elif leading_whitespace:
match_index += len(leading_whitespace)
leading_whitespace = ''
# Avoid adding spurious empty strings to the parse tree.
if start_index != match_index:
parsed_template.add(template[start_index:match_index])
start_index = end_index
if tag_type in ('#', '^'):
# Cache current state.
state = (tag_type, end_index, section_key, parsed_template)
states.append(state)
# Initialize new state
section_key, parsed_template = tag_key, ParsedTemplate()
continue
if tag_type == '/':
if tag_key != section_key:
raise ParsingError("Section end tag mismatch: %s != %s" % (tag_key, section_key))
# Restore previous state with newly found section data.
parsed_section = parsed_template
(tag_type, section_start_index, section_key, parsed_template) = states.pop()
node = self._make_section_node(template, tag_type, tag_key, parsed_section,
section_start_index, match_index)
else:
node = self._make_interpolation_node(tag_type, tag_key, leading_whitespace)
parsed_template.add(node)
# Avoid adding spurious empty strings to the parse tree.
if start_index != len(template):
parsed_template.add(template[start_index:])
return parsed_template | python | def parse(self, template):
"""
Parse a template string starting at some index.
This method uses the current tag delimiter.
Arguments:
template: a unicode string that is the template to parse.
index: the index at which to start parsing.
Returns:
a ParsedTemplate instance.
"""
self._compile_delimiters()
start_index = 0
content_end_index, parsed_section, section_key = None, None, None
parsed_template = ParsedTemplate()
states = []
while True:
match = self._template_re.search(template, start_index)
if match is None:
break
match_index = match.start()
end_index = match.end()
matches = match.groupdict()
# Normalize the matches dictionary.
if matches['change'] is not None:
matches.update(tag='=', tag_key=matches['delims'])
elif matches['raw'] is not None:
matches.update(tag='&', tag_key=matches['raw_name'])
tag_type = matches['tag']
tag_key = matches['tag_key']
leading_whitespace = matches['whitespace']
# Standalone (non-interpolation) tags consume the entire line,
# both leading whitespace and trailing newline.
did_tag_begin_line = match_index == 0 or template[match_index - 1] in END_OF_LINE_CHARACTERS
did_tag_end_line = end_index == len(template) or template[end_index] in END_OF_LINE_CHARACTERS
is_tag_interpolating = tag_type in ['', '&']
if did_tag_begin_line and did_tag_end_line and not is_tag_interpolating:
if end_index < len(template):
end_index += template[end_index] == '\r' and 1 or 0
if end_index < len(template):
end_index += template[end_index] == '\n' and 1 or 0
elif leading_whitespace:
match_index += len(leading_whitespace)
leading_whitespace = ''
# Avoid adding spurious empty strings to the parse tree.
if start_index != match_index:
parsed_template.add(template[start_index:match_index])
start_index = end_index
if tag_type in ('#', '^'):
# Cache current state.
state = (tag_type, end_index, section_key, parsed_template)
states.append(state)
# Initialize new state
section_key, parsed_template = tag_key, ParsedTemplate()
continue
if tag_type == '/':
if tag_key != section_key:
raise ParsingError("Section end tag mismatch: %s != %s" % (tag_key, section_key))
# Restore previous state with newly found section data.
parsed_section = parsed_template
(tag_type, section_start_index, section_key, parsed_template) = states.pop()
node = self._make_section_node(template, tag_type, tag_key, parsed_section,
section_start_index, match_index)
else:
node = self._make_interpolation_node(tag_type, tag_key, leading_whitespace)
parsed_template.add(node)
# Avoid adding spurious empty strings to the parse tree.
if start_index != len(template):
parsed_template.add(template[start_index:])
return parsed_template | [
"def",
"parse",
"(",
"self",
",",
"template",
")",
":",
"self",
".",
"_compile_delimiters",
"(",
")",
"start_index",
"=",
"0",
"content_end_index",
",",
"parsed_section",
",",
"section_key",
"=",
"None",
",",
"None",
",",
"None",
"parsed_template",
"=",
"Par... | Parse a template string starting at some index.
This method uses the current tag delimiter.
Arguments:
template: a unicode string that is the template to parse.
index: the index at which to start parsing.
Returns:
a ParsedTemplate instance. | [
"Parse",
"a",
"template",
"string",
"starting",
"at",
"some",
"index",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L242-L338 | train | 207,119 |
defunkt/pystache | pystache/parser.py | _Parser._make_interpolation_node | def _make_interpolation_node(self, tag_type, tag_key, leading_whitespace):
"""
Create and return a non-section node for the parse tree.
"""
# TODO: switch to using a dictionary instead of a bunch of ifs and elifs.
if tag_type == '!':
return _CommentNode()
if tag_type == '=':
delimiters = tag_key.split()
self._change_delimiters(delimiters)
return _ChangeNode(delimiters)
if tag_type == '':
return _EscapeNode(tag_key)
if tag_type == '&':
return _LiteralNode(tag_key)
if tag_type == '>':
return _PartialNode(tag_key, leading_whitespace)
raise Exception("Invalid symbol for interpolation tag: %s" % repr(tag_type)) | python | def _make_interpolation_node(self, tag_type, tag_key, leading_whitespace):
"""
Create and return a non-section node for the parse tree.
"""
# TODO: switch to using a dictionary instead of a bunch of ifs and elifs.
if tag_type == '!':
return _CommentNode()
if tag_type == '=':
delimiters = tag_key.split()
self._change_delimiters(delimiters)
return _ChangeNode(delimiters)
if tag_type == '':
return _EscapeNode(tag_key)
if tag_type == '&':
return _LiteralNode(tag_key)
if tag_type == '>':
return _PartialNode(tag_key, leading_whitespace)
raise Exception("Invalid symbol for interpolation tag: %s" % repr(tag_type)) | [
"def",
"_make_interpolation_node",
"(",
"self",
",",
"tag_type",
",",
"tag_key",
",",
"leading_whitespace",
")",
":",
"# TODO: switch to using a dictionary instead of a bunch of ifs and elifs.",
"if",
"tag_type",
"==",
"'!'",
":",
"return",
"_CommentNode",
"(",
")",
"if",... | Create and return a non-section node for the parse tree. | [
"Create",
"and",
"return",
"a",
"non",
"-",
"section",
"node",
"for",
"the",
"parse",
"tree",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L340-L363 | train | 207,120 |
defunkt/pystache | pystache/parser.py | _Parser._make_section_node | def _make_section_node(self, template, tag_type, tag_key, parsed_section,
section_start_index, section_end_index):
"""
Create and return a section node for the parse tree.
"""
if tag_type == '#':
return _SectionNode(tag_key, parsed_section, self._delimiters,
template, section_start_index, section_end_index)
if tag_type == '^':
return _InvertedNode(tag_key, parsed_section)
raise Exception("Invalid symbol for section tag: %s" % repr(tag_type)) | python | def _make_section_node(self, template, tag_type, tag_key, parsed_section,
section_start_index, section_end_index):
"""
Create and return a section node for the parse tree.
"""
if tag_type == '#':
return _SectionNode(tag_key, parsed_section, self._delimiters,
template, section_start_index, section_end_index)
if tag_type == '^':
return _InvertedNode(tag_key, parsed_section)
raise Exception("Invalid symbol for section tag: %s" % repr(tag_type)) | [
"def",
"_make_section_node",
"(",
"self",
",",
"template",
",",
"tag_type",
",",
"tag_key",
",",
"parsed_section",
",",
"section_start_index",
",",
"section_end_index",
")",
":",
"if",
"tag_type",
"==",
"'#'",
":",
"return",
"_SectionNode",
"(",
"tag_key",
",",
... | Create and return a section node for the parse tree. | [
"Create",
"and",
"return",
"a",
"section",
"node",
"for",
"the",
"parse",
"tree",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L365-L378 | train | 207,121 |
defunkt/pystache | pystache/specloader.py | SpecLoader._find | def _find(self, spec):
"""
Find and return the path to the template associated to the instance.
"""
if spec.template_path is not None:
return spec.template_path
dir_path, file_name = self._find_relative(spec)
locator = self.loader._make_locator()
if dir_path is None:
# Then we need to search for the path.
path = locator.find_object(spec, self.loader.search_dirs, file_name=file_name)
else:
obj_dir = locator.get_object_directory(spec)
path = os.path.join(obj_dir, dir_path, file_name)
return path | python | def _find(self, spec):
"""
Find and return the path to the template associated to the instance.
"""
if spec.template_path is not None:
return spec.template_path
dir_path, file_name = self._find_relative(spec)
locator = self.loader._make_locator()
if dir_path is None:
# Then we need to search for the path.
path = locator.find_object(spec, self.loader.search_dirs, file_name=file_name)
else:
obj_dir = locator.get_object_directory(spec)
path = os.path.join(obj_dir, dir_path, file_name)
return path | [
"def",
"_find",
"(",
"self",
",",
"spec",
")",
":",
"if",
"spec",
".",
"template_path",
"is",
"not",
"None",
":",
"return",
"spec",
".",
"template_path",
"dir_path",
",",
"file_name",
"=",
"self",
".",
"_find_relative",
"(",
"spec",
")",
"locator",
"=",
... | Find and return the path to the template associated to the instance. | [
"Find",
"and",
"return",
"the",
"path",
"to",
"the",
"template",
"associated",
"to",
"the",
"instance",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/specloader.py#L53-L72 | train | 207,122 |
defunkt/pystache | pystache/specloader.py | SpecLoader.load | def load(self, spec):
"""
Find and return the template associated to a TemplateSpec instance.
Returns the template as a unicode string.
Arguments:
spec: a TemplateSpec instance.
"""
if spec.template is not None:
return self.loader.unicode(spec.template, spec.template_encoding)
path = self._find(spec)
return self.loader.read(path, spec.template_encoding) | python | def load(self, spec):
"""
Find and return the template associated to a TemplateSpec instance.
Returns the template as a unicode string.
Arguments:
spec: a TemplateSpec instance.
"""
if spec.template is not None:
return self.loader.unicode(spec.template, spec.template_encoding)
path = self._find(spec)
return self.loader.read(path, spec.template_encoding) | [
"def",
"load",
"(",
"self",
",",
"spec",
")",
":",
"if",
"spec",
".",
"template",
"is",
"not",
"None",
":",
"return",
"self",
".",
"loader",
".",
"unicode",
"(",
"spec",
".",
"template",
",",
"spec",
".",
"template_encoding",
")",
"path",
"=",
"self"... | Find and return the template associated to a TemplateSpec instance.
Returns the template as a unicode string.
Arguments:
spec: a TemplateSpec instance. | [
"Find",
"and",
"return",
"the",
"template",
"associated",
"to",
"a",
"TemplateSpec",
"instance",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/specloader.py#L74-L90 | train | 207,123 |
defunkt/pystache | pystache/renderengine.py | RenderEngine.fetch_string | def fetch_string(self, context, name):
"""
Get a value from the given context as a basestring instance.
"""
val = self.resolve_context(context, name)
if callable(val):
# Return because _render_value() is already a string.
return self._render_value(val(), context)
if not is_string(val):
return self.to_str(val)
return val | python | def fetch_string(self, context, name):
"""
Get a value from the given context as a basestring instance.
"""
val = self.resolve_context(context, name)
if callable(val):
# Return because _render_value() is already a string.
return self._render_value(val(), context)
if not is_string(val):
return self.to_str(val)
return val | [
"def",
"fetch_string",
"(",
"self",
",",
"context",
",",
"name",
")",
":",
"val",
"=",
"self",
".",
"resolve_context",
"(",
"context",
",",
"name",
")",
"if",
"callable",
"(",
"val",
")",
":",
"# Return because _render_value() is already a string.",
"return",
... | Get a value from the given context as a basestring instance. | [
"Get",
"a",
"value",
"from",
"the",
"given",
"context",
"as",
"a",
"basestring",
"instance",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderengine.py#L100-L114 | train | 207,124 |
defunkt/pystache | pystache/renderengine.py | RenderEngine.fetch_section_data | def fetch_section_data(self, context, name):
"""
Fetch the value of a section as a list.
"""
data = self.resolve_context(context, name)
# From the spec:
#
# If the data is not of a list type, it is coerced into a list
# as follows: if the data is truthy (e.g. `!!data == true`),
# use a single-element list containing the data, otherwise use
# an empty list.
#
if not data:
data = []
else:
# The least brittle way to determine whether something
# supports iteration is by trying to call iter() on it:
#
# http://docs.python.org/library/functions.html#iter
#
# It is not sufficient, for example, to check whether the item
# implements __iter__ () (the iteration protocol). There is
# also __getitem__() (the sequence protocol). In Python 2,
# strings do not implement __iter__(), but in Python 3 they do.
try:
iter(data)
except TypeError:
# Then the value does not support iteration.
data = [data]
else:
if is_string(data) or isinstance(data, dict):
# Do not treat strings and dicts (which are iterable) as lists.
data = [data]
# Otherwise, treat the value as a list.
return data | python | def fetch_section_data(self, context, name):
"""
Fetch the value of a section as a list.
"""
data = self.resolve_context(context, name)
# From the spec:
#
# If the data is not of a list type, it is coerced into a list
# as follows: if the data is truthy (e.g. `!!data == true`),
# use a single-element list containing the data, otherwise use
# an empty list.
#
if not data:
data = []
else:
# The least brittle way to determine whether something
# supports iteration is by trying to call iter() on it:
#
# http://docs.python.org/library/functions.html#iter
#
# It is not sufficient, for example, to check whether the item
# implements __iter__ () (the iteration protocol). There is
# also __getitem__() (the sequence protocol). In Python 2,
# strings do not implement __iter__(), but in Python 3 they do.
try:
iter(data)
except TypeError:
# Then the value does not support iteration.
data = [data]
else:
if is_string(data) or isinstance(data, dict):
# Do not treat strings and dicts (which are iterable) as lists.
data = [data]
# Otherwise, treat the value as a list.
return data | [
"def",
"fetch_section_data",
"(",
"self",
",",
"context",
",",
"name",
")",
":",
"data",
"=",
"self",
".",
"resolve_context",
"(",
"context",
",",
"name",
")",
"# From the spec:",
"#",
"# If the data is not of a list type, it is coerced into a list",
"# as follows: ... | Fetch the value of a section as a list. | [
"Fetch",
"the",
"value",
"of",
"a",
"section",
"as",
"a",
"list",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderengine.py#L116-L153 | train | 207,125 |
defunkt/pystache | pystache/renderengine.py | RenderEngine._render_value | def _render_value(self, val, context, delimiters=None):
"""
Render an arbitrary value.
"""
if not is_string(val):
# In case the template is an integer, for example.
val = self.to_str(val)
if type(val) is not unicode:
val = self.literal(val)
return self.render(val, context, delimiters) | python | def _render_value(self, val, context, delimiters=None):
"""
Render an arbitrary value.
"""
if not is_string(val):
# In case the template is an integer, for example.
val = self.to_str(val)
if type(val) is not unicode:
val = self.literal(val)
return self.render(val, context, delimiters) | [
"def",
"_render_value",
"(",
"self",
",",
"val",
",",
"context",
",",
"delimiters",
"=",
"None",
")",
":",
"if",
"not",
"is_string",
"(",
"val",
")",
":",
"# In case the template is an integer, for example.",
"val",
"=",
"self",
".",
"to_str",
"(",
"val",
")... | Render an arbitrary value. | [
"Render",
"an",
"arbitrary",
"value",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderengine.py#L155-L165 | train | 207,126 |
defunkt/pystache | pystache/renderengine.py | RenderEngine.render | def render(self, template, context_stack, delimiters=None):
"""
Render a unicode template string, and return as unicode.
Arguments:
template: a template string of type unicode (but not a proper
subclass of unicode).
context_stack: a ContextStack instance.
"""
parsed_template = parse(template, delimiters)
return parsed_template.render(self, context_stack) | python | def render(self, template, context_stack, delimiters=None):
"""
Render a unicode template string, and return as unicode.
Arguments:
template: a template string of type unicode (but not a proper
subclass of unicode).
context_stack: a ContextStack instance.
"""
parsed_template = parse(template, delimiters)
return parsed_template.render(self, context_stack) | [
"def",
"render",
"(",
"self",
",",
"template",
",",
"context_stack",
",",
"delimiters",
"=",
"None",
")",
":",
"parsed_template",
"=",
"parse",
"(",
"template",
",",
"delimiters",
")",
"return",
"parsed_template",
".",
"render",
"(",
"self",
",",
"context_st... | Render a unicode template string, and return as unicode.
Arguments:
template: a template string of type unicode (but not a proper
subclass of unicode).
context_stack: a ContextStack instance. | [
"Render",
"a",
"unicode",
"template",
"string",
"and",
"return",
"as",
"unicode",
"."
] | 17a5dfdcd56eb76af731d141de395a7632a905b8 | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderengine.py#L167-L181 | train | 207,127 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/dom.py | DOMWidget.evaluate | def evaluate(self, script):
"""
Evaluate script in page frame.
:param script: The script to evaluate.
"""
if WEBENGINE:
return self.dom.runJavaScript("{}".format(script))
else:
return self.dom.evaluateJavaScript("{}".format(script)) | python | def evaluate(self, script):
"""
Evaluate script in page frame.
:param script: The script to evaluate.
"""
if WEBENGINE:
return self.dom.runJavaScript("{}".format(script))
else:
return self.dom.evaluateJavaScript("{}".format(script)) | [
"def",
"evaluate",
"(",
"self",
",",
"script",
")",
":",
"if",
"WEBENGINE",
":",
"return",
"self",
".",
"dom",
".",
"runJavaScript",
"(",
"\"{}\"",
".",
"format",
"(",
"script",
")",
")",
"else",
":",
"return",
"self",
".",
"dom",
".",
"evaluateJavaScr... | Evaluate script in page frame.
:param script: The script to evaluate. | [
"Evaluate",
"script",
"in",
"page",
"frame",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/dom.py#L28-L37 | train | 207,128 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/dom.py | DOMWidget.set_input_value | def set_input_value(self, selector, value):
"""Set the value of the input matched by given selector."""
script = 'document.querySelector("%s").setAttribute("value", "%s")'
script = script % (selector, value)
self.evaluate(script) | python | def set_input_value(self, selector, value):
"""Set the value of the input matched by given selector."""
script = 'document.querySelector("%s").setAttribute("value", "%s")'
script = script % (selector, value)
self.evaluate(script) | [
"def",
"set_input_value",
"(",
"self",
",",
"selector",
",",
"value",
")",
":",
"script",
"=",
"'document.querySelector(\"%s\").setAttribute(\"value\", \"%s\")'",
"script",
"=",
"script",
"%",
"(",
"selector",
",",
"value",
")",
"self",
".",
"evaluate",
"(",
"scri... | Set the value of the input matched by given selector. | [
"Set",
"the",
"value",
"of",
"the",
"input",
"matched",
"by",
"given",
"selector",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/dom.py#L59-L63 | train | 207,129 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | main | def main():
"""Simple test."""
from spyder.utils.qthelpers import qapplication
app = qapplication()
widget = NotebookClient(plugin=None, name='')
widget.show()
widget.set_url('http://google.com')
sys.exit(app.exec_()) | python | def main():
"""Simple test."""
from spyder.utils.qthelpers import qapplication
app = qapplication()
widget = NotebookClient(plugin=None, name='')
widget.show()
widget.set_url('http://google.com')
sys.exit(app.exec_()) | [
"def",
"main",
"(",
")",
":",
"from",
"spyder",
".",
"utils",
".",
"qthelpers",
"import",
"qapplication",
"app",
"=",
"qapplication",
"(",
")",
"widget",
"=",
"NotebookClient",
"(",
"plugin",
"=",
"None",
",",
"name",
"=",
"''",
")",
"widget",
".",
"sh... | Simple test. | [
"Simple",
"test",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L276-L283 | train | 207,130 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookWidget.show_kernel_error | def show_kernel_error(self, error):
"""Show kernel initialization errors."""
# Remove unneeded blank lines at the beginning
eol = sourcecode.get_eol_chars(error)
if eol:
error = error.replace(eol, '<br>')
# Don't break lines in hyphens
# From http://stackoverflow.com/q/7691569/438386
error = error.replace('-', '‑')
message = _("An error occurred while starting the kernel")
kernel_error_template = Template(KERNEL_ERROR)
page = kernel_error_template.substitute(css_path=CSS_PATH,
message=message,
error=error)
self.setHtml(page) | python | def show_kernel_error(self, error):
"""Show kernel initialization errors."""
# Remove unneeded blank lines at the beginning
eol = sourcecode.get_eol_chars(error)
if eol:
error = error.replace(eol, '<br>')
# Don't break lines in hyphens
# From http://stackoverflow.com/q/7691569/438386
error = error.replace('-', '‑')
message = _("An error occurred while starting the kernel")
kernel_error_template = Template(KERNEL_ERROR)
page = kernel_error_template.substitute(css_path=CSS_PATH,
message=message,
error=error)
self.setHtml(page) | [
"def",
"show_kernel_error",
"(",
"self",
",",
"error",
")",
":",
"# Remove unneeded blank lines at the beginning",
"eol",
"=",
"sourcecode",
".",
"get_eol_chars",
"(",
"error",
")",
"if",
"eol",
":",
"error",
"=",
"error",
".",
"replace",
"(",
"eol",
",",
"'<b... | Show kernel initialization errors. | [
"Show",
"kernel",
"initialization",
"errors",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L93-L108 | train | 207,131 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookWidget.show_loading_page | def show_loading_page(self):
"""Show a loading animation while the kernel is starting."""
loading_template = Template(LOADING)
loading_img = get_image_path('loading_sprites.png')
if os.name == 'nt':
loading_img = loading_img.replace('\\', '/')
message = _("Connecting to kernel...")
page = loading_template.substitute(css_path=CSS_PATH,
loading_img=loading_img,
message=message)
self.setHtml(page) | python | def show_loading_page(self):
"""Show a loading animation while the kernel is starting."""
loading_template = Template(LOADING)
loading_img = get_image_path('loading_sprites.png')
if os.name == 'nt':
loading_img = loading_img.replace('\\', '/')
message = _("Connecting to kernel...")
page = loading_template.substitute(css_path=CSS_PATH,
loading_img=loading_img,
message=message)
self.setHtml(page) | [
"def",
"show_loading_page",
"(",
"self",
")",
":",
"loading_template",
"=",
"Template",
"(",
"LOADING",
")",
"loading_img",
"=",
"get_image_path",
"(",
"'loading_sprites.png'",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"loading_img",
"=",
"loading_img",
... | Show a loading animation while the kernel is starting. | [
"Show",
"a",
"loading",
"animation",
"while",
"the",
"kernel",
"is",
"starting",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L110-L120 | train | 207,132 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookClient.register | def register(self, server_info):
"""Register attributes that can be computed with the server info."""
# Path relative to the server directory
self.path = os.path.relpath(self.filename,
start=server_info['notebook_dir'])
# Replace backslashes on Windows
if os.name == 'nt':
self.path = self.path.replace('\\', '/')
# Server url to send requests to
self.server_url = server_info['url']
# Server token
self.token = server_info['token']
url = url_path_join(self.server_url, 'notebooks',
url_escape(self.path))
# Set file url to load this notebook
self.file_url = self.add_token(url) | python | def register(self, server_info):
"""Register attributes that can be computed with the server info."""
# Path relative to the server directory
self.path = os.path.relpath(self.filename,
start=server_info['notebook_dir'])
# Replace backslashes on Windows
if os.name == 'nt':
self.path = self.path.replace('\\', '/')
# Server url to send requests to
self.server_url = server_info['url']
# Server token
self.token = server_info['token']
url = url_path_join(self.server_url, 'notebooks',
url_escape(self.path))
# Set file url to load this notebook
self.file_url = self.add_token(url) | [
"def",
"register",
"(",
"self",
",",
"server_info",
")",
":",
"# Path relative to the server directory",
"self",
".",
"path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"filename",
",",
"start",
"=",
"server_info",
"[",
"'notebook_dir'",
"]",
... | Register attributes that can be computed with the server info. | [
"Register",
"attributes",
"that",
"can",
"be",
"computed",
"with",
"the",
"server",
"info",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L174-L194 | train | 207,133 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookClient.go_to | def go_to(self, url_or_text):
"""Go to page utl."""
if is_text_string(url_or_text):
url = QUrl(url_or_text)
else:
url = url_or_text
self.notebookwidget.load(url) | python | def go_to(self, url_or_text):
"""Go to page utl."""
if is_text_string(url_or_text):
url = QUrl(url_or_text)
else:
url = url_or_text
self.notebookwidget.load(url) | [
"def",
"go_to",
"(",
"self",
",",
"url_or_text",
")",
":",
"if",
"is_text_string",
"(",
"url_or_text",
")",
":",
"url",
"=",
"QUrl",
"(",
"url_or_text",
")",
"else",
":",
"url",
"=",
"url_or_text",
"self",
".",
"notebookwidget",
".",
"load",
"(",
"url",
... | Go to page utl. | [
"Go",
"to",
"page",
"utl",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L196-L202 | train | 207,134 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookClient.get_short_name | def get_short_name(self):
"""Get a short name for the notebook."""
sname = osp.splitext(osp.basename(self.filename))[0]
if len(sname) > 20:
fm = QFontMetrics(QFont())
sname = fm.elidedText(sname, Qt.ElideRight, 110)
return sname | python | def get_short_name(self):
"""Get a short name for the notebook."""
sname = osp.splitext(osp.basename(self.filename))[0]
if len(sname) > 20:
fm = QFontMetrics(QFont())
sname = fm.elidedText(sname, Qt.ElideRight, 110)
return sname | [
"def",
"get_short_name",
"(",
"self",
")",
":",
"sname",
"=",
"osp",
".",
"splitext",
"(",
"osp",
".",
"basename",
"(",
"self",
".",
"filename",
")",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"sname",
")",
">",
"20",
":",
"fm",
"=",
"QFontMetrics",
"... | Get a short name for the notebook. | [
"Get",
"a",
"short",
"name",
"for",
"the",
"notebook",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L216-L222 | train | 207,135 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookClient.get_kernel_id | def get_kernel_id(self):
"""
Get the kernel id of the client.
Return a str with the kernel id or None.
"""
sessions_url = self.get_session_url()
sessions_req = requests.get(sessions_url).content.decode()
sessions = json.loads(sessions_req)
if os.name == 'nt':
path = self.path.replace('\\', '/')
else:
path = self.path
for session in sessions:
notebook_path = session.get('notebook', {}).get('path')
if notebook_path is not None and notebook_path == path:
kernel_id = session['kernel']['id']
return kernel_id | python | def get_kernel_id(self):
"""
Get the kernel id of the client.
Return a str with the kernel id or None.
"""
sessions_url = self.get_session_url()
sessions_req = requests.get(sessions_url).content.decode()
sessions = json.loads(sessions_req)
if os.name == 'nt':
path = self.path.replace('\\', '/')
else:
path = self.path
for session in sessions:
notebook_path = session.get('notebook', {}).get('path')
if notebook_path is not None and notebook_path == path:
kernel_id = session['kernel']['id']
return kernel_id | [
"def",
"get_kernel_id",
"(",
"self",
")",
":",
"sessions_url",
"=",
"self",
".",
"get_session_url",
"(",
")",
"sessions_req",
"=",
"requests",
".",
"get",
"(",
"sessions_url",
")",
".",
"content",
".",
"decode",
"(",
")",
"sessions",
"=",
"json",
".",
"l... | Get the kernel id of the client.
Return a str with the kernel id or None. | [
"Get",
"the",
"kernel",
"id",
"of",
"the",
"client",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L232-L251 | train | 207,136 |
spyder-ide/spyder-notebook | spyder_notebook/widgets/client.py | NotebookClient.shutdown_kernel | def shutdown_kernel(self):
"""Shutdown the kernel of the client."""
kernel_id = self.get_kernel_id()
if kernel_id:
delete_url = self.add_token(url_path_join(self.server_url,
'api/kernels/',
kernel_id))
delete_req = requests.delete(delete_url)
if delete_req.status_code != 204:
QMessageBox.warning(
self,
_("Server error"),
_("The Jupyter Notebook server "
"failed to shutdown the kernel "
"associated with this notebook. "
"If you want to shut it down, "
"you'll have to close Spyder.")) | python | def shutdown_kernel(self):
"""Shutdown the kernel of the client."""
kernel_id = self.get_kernel_id()
if kernel_id:
delete_url = self.add_token(url_path_join(self.server_url,
'api/kernels/',
kernel_id))
delete_req = requests.delete(delete_url)
if delete_req.status_code != 204:
QMessageBox.warning(
self,
_("Server error"),
_("The Jupyter Notebook server "
"failed to shutdown the kernel "
"associated with this notebook. "
"If you want to shut it down, "
"you'll have to close Spyder.")) | [
"def",
"shutdown_kernel",
"(",
"self",
")",
":",
"kernel_id",
"=",
"self",
".",
"get_kernel_id",
"(",
")",
"if",
"kernel_id",
":",
"delete_url",
"=",
"self",
".",
"add_token",
"(",
"url_path_join",
"(",
"self",
".",
"server_url",
",",
"'api/kernels/'",
",",
... | Shutdown the kernel of the client. | [
"Shutdown",
"the",
"kernel",
"of",
"the",
"client",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/widgets/client.py#L253-L270 | train | 207,137 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.register_plugin | def register_plugin(self):
"""Register plugin in Spyder's main window."""
self.focus_changed.connect(self.main.plugin_focus_changed)
self.main.add_dockwidget(self)
self.ipyconsole = self.main.ipyconsole
self.create_new_client(give_focus=False)
icon_path = os.path.join(PACKAGE_PATH, 'images', 'icon.svg')
self.main.add_to_fileswitcher(self, self.tabwidget, self.clients,
QIcon(icon_path))
self.recent_notebook_menu.aboutToShow.connect(self.setup_menu_actions) | python | def register_plugin(self):
"""Register plugin in Spyder's main window."""
self.focus_changed.connect(self.main.plugin_focus_changed)
self.main.add_dockwidget(self)
self.ipyconsole = self.main.ipyconsole
self.create_new_client(give_focus=False)
icon_path = os.path.join(PACKAGE_PATH, 'images', 'icon.svg')
self.main.add_to_fileswitcher(self, self.tabwidget, self.clients,
QIcon(icon_path))
self.recent_notebook_menu.aboutToShow.connect(self.setup_menu_actions) | [
"def",
"register_plugin",
"(",
"self",
")",
":",
"self",
".",
"focus_changed",
".",
"connect",
"(",
"self",
".",
"main",
".",
"plugin_focus_changed",
")",
"self",
".",
"main",
".",
"add_dockwidget",
"(",
"self",
")",
"self",
".",
"ipyconsole",
"=",
"self",... | Register plugin in Spyder's main window. | [
"Register",
"plugin",
"in",
"Spyder",
"s",
"main",
"window",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L193-L202 | train | 207,138 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.check_compatibility | def check_compatibility(self):
"""Check compatibility for PyQt and sWebEngine."""
message = ''
value = True
if PYQT4 or PYSIDE:
message = _("You are working with Qt4 and in order to use this "
"plugin you need to have Qt5.<br><br>"
"Please update your Qt and/or PyQt packages to "
"meet this requirement.")
value = False
return value, message | python | def check_compatibility(self):
"""Check compatibility for PyQt and sWebEngine."""
message = ''
value = True
if PYQT4 or PYSIDE:
message = _("You are working with Qt4 and in order to use this "
"plugin you need to have Qt5.<br><br>"
"Please update your Qt and/or PyQt packages to "
"meet this requirement.")
value = False
return value, message | [
"def",
"check_compatibility",
"(",
"self",
")",
":",
"message",
"=",
"''",
"value",
"=",
"True",
"if",
"PYQT4",
"or",
"PYSIDE",
":",
"message",
"=",
"_",
"(",
"\"You are working with Qt4 and in order to use this \"",
"\"plugin you need to have Qt5.<br><br>\"",
"\"Please... | Check compatibility for PyQt and sWebEngine. | [
"Check",
"compatibility",
"for",
"PyQt",
"and",
"sWebEngine",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L204-L214 | train | 207,139 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.update_notebook_actions | def update_notebook_actions(self):
"""Update actions of the recent notebooks menu."""
if self.recent_notebooks:
self.clear_recent_notebooks_action.setEnabled(True)
else:
self.clear_recent_notebooks_action.setEnabled(False)
client = self.get_current_client()
if client:
if client.get_filename() != WELCOME:
self.save_as_action.setEnabled(True)
self.open_console_action.setEnabled(True)
self.options_menu.clear()
add_actions(self.options_menu, self.menu_actions)
return
self.save_as_action.setEnabled(False)
self.open_console_action.setEnabled(False)
self.options_menu.clear()
add_actions(self.options_menu, self.menu_actions) | python | def update_notebook_actions(self):
"""Update actions of the recent notebooks menu."""
if self.recent_notebooks:
self.clear_recent_notebooks_action.setEnabled(True)
else:
self.clear_recent_notebooks_action.setEnabled(False)
client = self.get_current_client()
if client:
if client.get_filename() != WELCOME:
self.save_as_action.setEnabled(True)
self.open_console_action.setEnabled(True)
self.options_menu.clear()
add_actions(self.options_menu, self.menu_actions)
return
self.save_as_action.setEnabled(False)
self.open_console_action.setEnabled(False)
self.options_menu.clear()
add_actions(self.options_menu, self.menu_actions) | [
"def",
"update_notebook_actions",
"(",
"self",
")",
":",
"if",
"self",
".",
"recent_notebooks",
":",
"self",
".",
"clear_recent_notebooks_action",
".",
"setEnabled",
"(",
"True",
")",
"else",
":",
"self",
".",
"clear_recent_notebooks_action",
".",
"setEnabled",
"(... | Update actions of the recent notebooks menu. | [
"Update",
"actions",
"of",
"the",
"recent",
"notebooks",
"menu",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L240-L257 | train | 207,140 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.add_to_recent | def add_to_recent(self, notebook):
"""
Add an entry to recent notebooks.
We only maintain the list of the 20 most recent notebooks.
"""
if notebook not in self.recent_notebooks:
self.recent_notebooks.insert(0, notebook)
self.recent_notebooks = self.recent_notebooks[:20] | python | def add_to_recent(self, notebook):
"""
Add an entry to recent notebooks.
We only maintain the list of the 20 most recent notebooks.
"""
if notebook not in self.recent_notebooks:
self.recent_notebooks.insert(0, notebook)
self.recent_notebooks = self.recent_notebooks[:20] | [
"def",
"add_to_recent",
"(",
"self",
",",
"notebook",
")",
":",
"if",
"notebook",
"not",
"in",
"self",
".",
"recent_notebooks",
":",
"self",
".",
"recent_notebooks",
".",
"insert",
"(",
"0",
",",
"notebook",
")",
"self",
".",
"recent_notebooks",
"=",
"self... | Add an entry to recent notebooks.
We only maintain the list of the 20 most recent notebooks. | [
"Add",
"an",
"entry",
"to",
"recent",
"notebooks",
".",
"We",
"only",
"maintain",
"the",
"list",
"of",
"the",
"20",
"most",
"recent",
"notebooks",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L259-L267 | train | 207,141 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.get_focus_client | def get_focus_client(self):
"""Return current notebook with focus, if any."""
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.notebookwidget:
return client | python | def get_focus_client(self):
"""Return current notebook with focus, if any."""
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.notebookwidget:
return client | [
"def",
"get_focus_client",
"(",
"self",
")",
":",
"widget",
"=",
"QApplication",
".",
"focusWidget",
"(",
")",
"for",
"client",
"in",
"self",
".",
"get_clients",
"(",
")",
":",
"if",
"widget",
"is",
"client",
"or",
"widget",
"is",
"client",
".",
"noteboo... | Return current notebook with focus, if any. | [
"Return",
"current",
"notebook",
"with",
"focus",
"if",
"any",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L278-L283 | train | 207,142 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.get_current_client | def get_current_client(self):
"""Return the currently selected notebook."""
try:
client = self.tabwidget.currentWidget()
except AttributeError:
client = None
if client is not None:
return client | python | def get_current_client(self):
"""Return the currently selected notebook."""
try:
client = self.tabwidget.currentWidget()
except AttributeError:
client = None
if client is not None:
return client | [
"def",
"get_current_client",
"(",
"self",
")",
":",
"try",
":",
"client",
"=",
"self",
".",
"tabwidget",
".",
"currentWidget",
"(",
")",
"except",
"AttributeError",
":",
"client",
"=",
"None",
"if",
"client",
"is",
"not",
"None",
":",
"return",
"client"
] | Return the currently selected notebook. | [
"Return",
"the",
"currently",
"selected",
"notebook",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L285-L292 | train | 207,143 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.get_current_client_name | def get_current_client_name(self, short=False):
"""Get the current client name."""
client = self.get_current_client()
if client:
if short:
return client.get_short_name()
else:
return client.get_filename() | python | def get_current_client_name(self, short=False):
"""Get the current client name."""
client = self.get_current_client()
if client:
if short:
return client.get_short_name()
else:
return client.get_filename() | [
"def",
"get_current_client_name",
"(",
"self",
",",
"short",
"=",
"False",
")",
":",
"client",
"=",
"self",
".",
"get_current_client",
"(",
")",
"if",
"client",
":",
"if",
"short",
":",
"return",
"client",
".",
"get_short_name",
"(",
")",
"else",
":",
"r... | Get the current client name. | [
"Get",
"the",
"current",
"client",
"name",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L300-L307 | train | 207,144 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.create_new_client | def create_new_client(self, filename=None, give_focus=True):
"""Create a new notebook or load a pre-existing one."""
# Generate the notebook name (in case of a new one)
if not filename:
if not osp.isdir(NOTEBOOK_TMPDIR):
os.makedirs(NOTEBOOK_TMPDIR)
nb_name = 'untitled' + str(self.untitled_num) + '.ipynb'
filename = osp.join(NOTEBOOK_TMPDIR, nb_name)
nb_contents = nbformat.v4.new_notebook()
nbformat.write(nb_contents, filename)
self.untitled_num += 1
# Save spyder_pythonpath before creating a client
# because it's needed by our kernel spec.
if not self.testing:
CONF.set('main', 'spyder_pythonpath',
self.main.get_spyder_pythonpath())
# Open the notebook with nbopen and get the url we need to render
try:
server_info = nbopen(filename)
except (subprocess.CalledProcessError, NBServerError):
QMessageBox.critical(
self,
_("Server error"),
_("The Jupyter Notebook server failed to start or it is "
"taking too much time to do it. Please start it in a "
"system terminal with the command 'jupyter notebook' to "
"check for errors."))
# Create a welcome widget
# See issue 93
self.untitled_num -= 1
self.create_welcome_client()
return
welcome_client = self.create_welcome_client()
client = NotebookClient(self, filename)
self.add_tab(client)
if NOTEBOOK_TMPDIR not in filename:
self.add_to_recent(filename)
self.setup_menu_actions()
client.register(server_info)
client.load_notebook()
if welcome_client and not self.testing:
self.tabwidget.setCurrentIndex(0) | python | def create_new_client(self, filename=None, give_focus=True):
"""Create a new notebook or load a pre-existing one."""
# Generate the notebook name (in case of a new one)
if not filename:
if not osp.isdir(NOTEBOOK_TMPDIR):
os.makedirs(NOTEBOOK_TMPDIR)
nb_name = 'untitled' + str(self.untitled_num) + '.ipynb'
filename = osp.join(NOTEBOOK_TMPDIR, nb_name)
nb_contents = nbformat.v4.new_notebook()
nbformat.write(nb_contents, filename)
self.untitled_num += 1
# Save spyder_pythonpath before creating a client
# because it's needed by our kernel spec.
if not self.testing:
CONF.set('main', 'spyder_pythonpath',
self.main.get_spyder_pythonpath())
# Open the notebook with nbopen and get the url we need to render
try:
server_info = nbopen(filename)
except (subprocess.CalledProcessError, NBServerError):
QMessageBox.critical(
self,
_("Server error"),
_("The Jupyter Notebook server failed to start or it is "
"taking too much time to do it. Please start it in a "
"system terminal with the command 'jupyter notebook' to "
"check for errors."))
# Create a welcome widget
# See issue 93
self.untitled_num -= 1
self.create_welcome_client()
return
welcome_client = self.create_welcome_client()
client = NotebookClient(self, filename)
self.add_tab(client)
if NOTEBOOK_TMPDIR not in filename:
self.add_to_recent(filename)
self.setup_menu_actions()
client.register(server_info)
client.load_notebook()
if welcome_client and not self.testing:
self.tabwidget.setCurrentIndex(0) | [
"def",
"create_new_client",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"give_focus",
"=",
"True",
")",
":",
"# Generate the notebook name (in case of a new one)\r",
"if",
"not",
"filename",
":",
"if",
"not",
"osp",
".",
"isdir",
"(",
"NOTEBOOK_TMPDIR",
")",
... | Create a new notebook or load a pre-existing one. | [
"Create",
"a",
"new",
"notebook",
"or",
"load",
"a",
"pre",
"-",
"existing",
"one",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L309-L353 | train | 207,145 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.create_welcome_client | def create_welcome_client(self):
"""Create a welcome client with some instructions."""
if self.tabwidget.count() == 0:
welcome = open(WELCOME).read()
client = NotebookClient(self, WELCOME, ini_message=welcome)
self.add_tab(client)
return client | python | def create_welcome_client(self):
"""Create a welcome client with some instructions."""
if self.tabwidget.count() == 0:
welcome = open(WELCOME).read()
client = NotebookClient(self, WELCOME, ini_message=welcome)
self.add_tab(client)
return client | [
"def",
"create_welcome_client",
"(",
"self",
")",
":",
"if",
"self",
".",
"tabwidget",
".",
"count",
"(",
")",
"==",
"0",
":",
"welcome",
"=",
"open",
"(",
"WELCOME",
")",
".",
"read",
"(",
")",
"client",
"=",
"NotebookClient",
"(",
"self",
",",
"WEL... | Create a welcome client with some instructions. | [
"Create",
"a",
"welcome",
"client",
"with",
"some",
"instructions",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L404-L410 | train | 207,146 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.save_as | def save_as(self, name=None, close=False):
"""Save notebook as."""
current_client = self.get_current_client()
current_client.save()
original_path = current_client.get_filename()
if not name:
original_name = osp.basename(original_path)
else:
original_name = name
filename, _selfilter = getsavefilename(self, _("Save notebook"),
original_name, FILES_FILTER)
if filename:
nb_contents = nbformat.read(original_path, as_version=4)
nbformat.write(nb_contents, filename)
if not close:
self.close_client(save=True)
self.create_new_client(filename=filename) | python | def save_as(self, name=None, close=False):
"""Save notebook as."""
current_client = self.get_current_client()
current_client.save()
original_path = current_client.get_filename()
if not name:
original_name = osp.basename(original_path)
else:
original_name = name
filename, _selfilter = getsavefilename(self, _("Save notebook"),
original_name, FILES_FILTER)
if filename:
nb_contents = nbformat.read(original_path, as_version=4)
nbformat.write(nb_contents, filename)
if not close:
self.close_client(save=True)
self.create_new_client(filename=filename) | [
"def",
"save_as",
"(",
"self",
",",
"name",
"=",
"None",
",",
"close",
"=",
"False",
")",
":",
"current_client",
"=",
"self",
".",
"get_current_client",
"(",
")",
"current_client",
".",
"save",
"(",
")",
"original_path",
"=",
"current_client",
".",
"get_fi... | Save notebook as. | [
"Save",
"notebook",
"as",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L412-L428 | train | 207,147 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.open_notebook | def open_notebook(self, filenames=None):
"""Open a notebook from file."""
if not filenames:
filenames, _selfilter = getopenfilenames(self, _("Open notebook"),
'', FILES_FILTER)
if filenames:
for filename in filenames:
self.create_new_client(filename=filename) | python | def open_notebook(self, filenames=None):
"""Open a notebook from file."""
if not filenames:
filenames, _selfilter = getopenfilenames(self, _("Open notebook"),
'', FILES_FILTER)
if filenames:
for filename in filenames:
self.create_new_client(filename=filename) | [
"def",
"open_notebook",
"(",
"self",
",",
"filenames",
"=",
"None",
")",
":",
"if",
"not",
"filenames",
":",
"filenames",
",",
"_selfilter",
"=",
"getopenfilenames",
"(",
"self",
",",
"_",
"(",
"\"Open notebook\"",
")",
",",
"''",
",",
"FILES_FILTER",
")",... | Open a notebook from file. | [
"Open",
"a",
"notebook",
"from",
"file",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L430-L437 | train | 207,148 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.open_console | def open_console(self, client=None):
"""Open an IPython console for the given client or the current one."""
if not client:
client = self.get_current_client()
if self.ipyconsole is not None:
kernel_id = client.get_kernel_id()
if not kernel_id:
QMessageBox.critical(
self, _('Error opening console'),
_('There is no kernel associated to this notebook.'))
return
self.ipyconsole._create_client_for_kernel(kernel_id, None, None,
None)
ipyclient = self.ipyconsole.get_current_client()
ipyclient.allow_rename = False
self.ipyconsole.rename_client_tab(ipyclient,
client.get_short_name()) | python | def open_console(self, client=None):
"""Open an IPython console for the given client or the current one."""
if not client:
client = self.get_current_client()
if self.ipyconsole is not None:
kernel_id = client.get_kernel_id()
if not kernel_id:
QMessageBox.critical(
self, _('Error opening console'),
_('There is no kernel associated to this notebook.'))
return
self.ipyconsole._create_client_for_kernel(kernel_id, None, None,
None)
ipyclient = self.ipyconsole.get_current_client()
ipyclient.allow_rename = False
self.ipyconsole.rename_client_tab(ipyclient,
client.get_short_name()) | [
"def",
"open_console",
"(",
"self",
",",
"client",
"=",
"None",
")",
":",
"if",
"not",
"client",
":",
"client",
"=",
"self",
".",
"get_current_client",
"(",
")",
"if",
"self",
".",
"ipyconsole",
"is",
"not",
"None",
":",
"kernel_id",
"=",
"client",
"."... | Open an IPython console for the given client or the current one. | [
"Open",
"an",
"IPython",
"console",
"for",
"the",
"given",
"client",
"or",
"the",
"current",
"one",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L439-L455 | train | 207,149 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.add_tab | def add_tab(self, widget):
"""Add tab."""
self.clients.append(widget)
index = self.tabwidget.addTab(widget, widget.get_short_name())
self.tabwidget.setCurrentIndex(index)
self.tabwidget.setTabToolTip(index, widget.get_filename())
if self.dockwidget and not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_()
self.activateWindow()
widget.notebookwidget.setFocus() | python | def add_tab(self, widget):
"""Add tab."""
self.clients.append(widget)
index = self.tabwidget.addTab(widget, widget.get_short_name())
self.tabwidget.setCurrentIndex(index)
self.tabwidget.setTabToolTip(index, widget.get_filename())
if self.dockwidget and not self.ismaximized:
self.dockwidget.setVisible(True)
self.dockwidget.raise_()
self.activateWindow()
widget.notebookwidget.setFocus() | [
"def",
"add_tab",
"(",
"self",
",",
"widget",
")",
":",
"self",
".",
"clients",
".",
"append",
"(",
"widget",
")",
"index",
"=",
"self",
".",
"tabwidget",
".",
"addTab",
"(",
"widget",
",",
"widget",
".",
"get_short_name",
"(",
")",
")",
"self",
".",... | Add tab. | [
"Add",
"tab",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L458-L468 | train | 207,150 |
spyder-ide/spyder-notebook | spyder_notebook/notebookplugin.py | NotebookPlugin.set_stack_index | def set_stack_index(self, index, instance):
"""Set the index of the current notebook."""
if instance == self:
self.tabwidget.setCurrentIndex(index) | python | def set_stack_index(self, index, instance):
"""Set the index of the current notebook."""
if instance == self:
self.tabwidget.setCurrentIndex(index) | [
"def",
"set_stack_index",
"(",
"self",
",",
"index",
",",
"instance",
")",
":",
"if",
"instance",
"==",
"self",
":",
"self",
".",
"tabwidget",
".",
"setCurrentIndex",
"(",
"index",
")"
] | Set the index of the current notebook. | [
"Set",
"the",
"index",
"of",
"the",
"current",
"notebook",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/notebookplugin.py#L476-L479 | train | 207,151 |
spyder-ide/spyder-notebook | setup.py | get_version | def get_version(module='spyder_notebook'):
"""Get version."""
with open(os.path.join(HERE, module, '_version.py'), 'r') as f:
data = f.read()
lines = data.split('\n')
for line in lines:
if line.startswith('VERSION_INFO'):
version_tuple = ast.literal_eval(line.split('=')[-1].strip())
version = '.'.join(map(str, version_tuple))
break
return version | python | def get_version(module='spyder_notebook'):
"""Get version."""
with open(os.path.join(HERE, module, '_version.py'), 'r') as f:
data = f.read()
lines = data.split('\n')
for line in lines:
if line.startswith('VERSION_INFO'):
version_tuple = ast.literal_eval(line.split('=')[-1].strip())
version = '.'.join(map(str, version_tuple))
break
return version | [
"def",
"get_version",
"(",
"module",
"=",
"'spyder_notebook'",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"HERE",
",",
"module",
",",
"'_version.py'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"("... | Get version. | [
"Get",
"version",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/setup.py#L25-L35 | train | 207,152 |
spyder-ide/spyder-notebook | spyder_notebook/utils/nbopen.py | find_best_server | def find_best_server(filename):
"""Find the best server to open a notebook with."""
servers = [si for si in notebookapp.list_running_servers()
if filename.startswith(si['notebook_dir'])]
try:
return max(servers, key=lambda si: len(si['notebook_dir']))
except ValueError:
return None | python | def find_best_server(filename):
"""Find the best server to open a notebook with."""
servers = [si for si in notebookapp.list_running_servers()
if filename.startswith(si['notebook_dir'])]
try:
return max(servers, key=lambda si: len(si['notebook_dir']))
except ValueError:
return None | [
"def",
"find_best_server",
"(",
"filename",
")",
":",
"servers",
"=",
"[",
"si",
"for",
"si",
"in",
"notebookapp",
".",
"list_running_servers",
"(",
")",
"if",
"filename",
".",
"startswith",
"(",
"si",
"[",
"'notebook_dir'",
"]",
")",
"]",
"try",
":",
"r... | Find the best server to open a notebook with. | [
"Find",
"the",
"best",
"server",
"to",
"open",
"a",
"notebook",
"with",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/utils/nbopen.py#L38-L45 | train | 207,153 |
spyder-ide/spyder-notebook | spyder_notebook/utils/nbopen.py | nbopen | def nbopen(filename):
"""
Open a notebook using the best available server.
Returns information about the selected server.
"""
filename = osp.abspath(filename)
home_dir = get_home_dir()
server_info = find_best_server(filename)
if server_info is not None:
print("Using existing server at", server_info['notebook_dir'])
return server_info
else:
if filename.startswith(home_dir):
nbdir = home_dir
else:
nbdir = osp.dirname(filename)
print("Starting new server")
command = [sys.executable, '-m', 'notebook', '--no-browser',
'--notebook-dir={}'.format(nbdir),
'--NotebookApp.password=',
"--KernelSpecManager.kernel_spec_class='{}'".format(
KERNELSPEC)]
if os.name == 'nt':
creation_flag = 0x08000000 # CREATE_NO_WINDOW
else:
creation_flag = 0 # Default value
if DEV:
env = os.environ.copy()
env["PYTHONPATH"] = osp.dirname(get_module_path('spyder'))
proc = subprocess.Popen(command, creationflags=creation_flag,
env=env)
else:
proc = subprocess.Popen(command, creationflags=creation_flag)
# Kill the server at exit. We need to use psutil for this because
# Popen.terminate doesn't work when creationflags or shell=True
# are used.
def kill_server_and_childs(pid):
ps_proc = psutil.Process(pid)
for child in ps_proc.children(recursive=True):
child.kill()
ps_proc.kill()
atexit.register(kill_server_and_childs, proc.pid)
# Wait ~25 secs for the server to be up
for _x in range(100):
server_info = find_best_server(filename)
if server_info is not None:
break
else:
time.sleep(0.25)
if server_info is None:
raise NBServerError()
return server_info | python | def nbopen(filename):
"""
Open a notebook using the best available server.
Returns information about the selected server.
"""
filename = osp.abspath(filename)
home_dir = get_home_dir()
server_info = find_best_server(filename)
if server_info is not None:
print("Using existing server at", server_info['notebook_dir'])
return server_info
else:
if filename.startswith(home_dir):
nbdir = home_dir
else:
nbdir = osp.dirname(filename)
print("Starting new server")
command = [sys.executable, '-m', 'notebook', '--no-browser',
'--notebook-dir={}'.format(nbdir),
'--NotebookApp.password=',
"--KernelSpecManager.kernel_spec_class='{}'".format(
KERNELSPEC)]
if os.name == 'nt':
creation_flag = 0x08000000 # CREATE_NO_WINDOW
else:
creation_flag = 0 # Default value
if DEV:
env = os.environ.copy()
env["PYTHONPATH"] = osp.dirname(get_module_path('spyder'))
proc = subprocess.Popen(command, creationflags=creation_flag,
env=env)
else:
proc = subprocess.Popen(command, creationflags=creation_flag)
# Kill the server at exit. We need to use psutil for this because
# Popen.terminate doesn't work when creationflags or shell=True
# are used.
def kill_server_and_childs(pid):
ps_proc = psutil.Process(pid)
for child in ps_proc.children(recursive=True):
child.kill()
ps_proc.kill()
atexit.register(kill_server_and_childs, proc.pid)
# Wait ~25 secs for the server to be up
for _x in range(100):
server_info = find_best_server(filename)
if server_info is not None:
break
else:
time.sleep(0.25)
if server_info is None:
raise NBServerError()
return server_info | [
"def",
"nbopen",
"(",
"filename",
")",
":",
"filename",
"=",
"osp",
".",
"abspath",
"(",
"filename",
")",
"home_dir",
"=",
"get_home_dir",
"(",
")",
"server_info",
"=",
"find_best_server",
"(",
"filename",
")",
"if",
"server_info",
"is",
"not",
"None",
":"... | Open a notebook using the best available server.
Returns information about the selected server. | [
"Open",
"a",
"notebook",
"using",
"the",
"best",
"available",
"server",
"."
] | 54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db | https://github.com/spyder-ide/spyder-notebook/blob/54e626b9d2a3fccd3e4625b0f97fe06e5bb1a6db/spyder_notebook/utils/nbopen.py#L48-L109 | train | 207,154 |
muatik/flask-profiler | flask_profiler/flask_profiler.py | profile | def profile(*args, **kwargs):
"""
http endpoint decorator
"""
if _is_initialized():
def wrapper(f):
return wrapHttpEndpoint(f)
return wrapper
raise Exception(
"before measuring anything, you need to call init_app()") | python | def profile(*args, **kwargs):
"""
http endpoint decorator
"""
if _is_initialized():
def wrapper(f):
return wrapHttpEndpoint(f)
return wrapper
raise Exception(
"before measuring anything, you need to call init_app()") | [
"def",
"profile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_is_initialized",
"(",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"return",
"wrapHttpEndpoint",
"(",
"f",
")",
"return",
"wrapper",
"raise",
"Exception",
"(",
"\"before ... | http endpoint decorator | [
"http",
"endpoint",
"decorator"
] | 51b4354fc14f8cfdd538ec9db98fa1cf545ccd18 | https://github.com/muatik/flask-profiler/blob/51b4354fc14f8cfdd538ec9db98fa1cf545ccd18/flask_profiler/flask_profiler.py#L154-L164 | train | 207,155 |
muatik/flask-profiler | flask_profiler/flask_profiler.py | registerInternalRouters | def registerInternalRouters(app):
"""
These are the endpoints which are used to display measurements in the
flask-profiler dashboard.
Note: these should be defined after wrapping user defined endpoints
via wrapAppEndpoints()
:param app: Flask application instance
:return:
"""
urlPath = CONF.get("endpointRoot", "flask-profiler")
fp = Blueprint(
'flask-profiler', __name__,
url_prefix="/" + urlPath,
static_folder="static/dist/", static_url_path='/static/dist')
@fp.route("/".format(urlPath))
@auth.login_required
def index():
return fp.send_static_file("index.html")
@fp.route("/api/measurements/".format(urlPath))
@auth.login_required
def filterMeasurements():
args = dict(request.args.items())
measurements = collection.filter(args)
return jsonify({"measurements": list(measurements)})
@fp.route("/api/measurements/grouped".format(urlPath))
@auth.login_required
def getMeasurementsSummary():
args = dict(request.args.items())
measurements = collection.getSummary(args)
return jsonify({"measurements": list(measurements)})
@fp.route("/api/measurements/<measurementId>".format(urlPath))
@auth.login_required
def getContext(measurementId):
return jsonify(collection.get(measurementId))
@fp.route("/api/measurements/timeseries/".format(urlPath))
@auth.login_required
def getRequestsTimeseries():
args = dict(request.args.items())
return jsonify({"series": collection.getTimeseries(args)})
@fp.route("/api/measurements/methodDistribution/".format(urlPath))
@auth.login_required
def getMethodDistribution():
args = dict(request.args.items())
return jsonify({
"distribution": collection.getMethodDistribution(args)})
@fp.route("/db/dumpDatabase")
@auth.login_required
def dumpDatabase():
response = jsonify({
"summary": collection.getSummary()})
response.headers["Content-Disposition"] = "attachment; filename=dump.json"
return response
@fp.route("/db/deleteDatabase")
@auth.login_required
def deleteDatabase():
response = jsonify({
"status": collection.truncate()})
return response
@fp.after_request
def x_robots_tag_header(response):
response.headers['X-Robots-Tag'] = 'noindex, nofollow'
return response
app.register_blueprint(fp) | python | def registerInternalRouters(app):
"""
These are the endpoints which are used to display measurements in the
flask-profiler dashboard.
Note: these should be defined after wrapping user defined endpoints
via wrapAppEndpoints()
:param app: Flask application instance
:return:
"""
urlPath = CONF.get("endpointRoot", "flask-profiler")
fp = Blueprint(
'flask-profiler', __name__,
url_prefix="/" + urlPath,
static_folder="static/dist/", static_url_path='/static/dist')
@fp.route("/".format(urlPath))
@auth.login_required
def index():
return fp.send_static_file("index.html")
@fp.route("/api/measurements/".format(urlPath))
@auth.login_required
def filterMeasurements():
args = dict(request.args.items())
measurements = collection.filter(args)
return jsonify({"measurements": list(measurements)})
@fp.route("/api/measurements/grouped".format(urlPath))
@auth.login_required
def getMeasurementsSummary():
args = dict(request.args.items())
measurements = collection.getSummary(args)
return jsonify({"measurements": list(measurements)})
@fp.route("/api/measurements/<measurementId>".format(urlPath))
@auth.login_required
def getContext(measurementId):
return jsonify(collection.get(measurementId))
@fp.route("/api/measurements/timeseries/".format(urlPath))
@auth.login_required
def getRequestsTimeseries():
args = dict(request.args.items())
return jsonify({"series": collection.getTimeseries(args)})
@fp.route("/api/measurements/methodDistribution/".format(urlPath))
@auth.login_required
def getMethodDistribution():
args = dict(request.args.items())
return jsonify({
"distribution": collection.getMethodDistribution(args)})
@fp.route("/db/dumpDatabase")
@auth.login_required
def dumpDatabase():
response = jsonify({
"summary": collection.getSummary()})
response.headers["Content-Disposition"] = "attachment; filename=dump.json"
return response
@fp.route("/db/deleteDatabase")
@auth.login_required
def deleteDatabase():
response = jsonify({
"status": collection.truncate()})
return response
@fp.after_request
def x_robots_tag_header(response):
response.headers['X-Robots-Tag'] = 'noindex, nofollow'
return response
app.register_blueprint(fp) | [
"def",
"registerInternalRouters",
"(",
"app",
")",
":",
"urlPath",
"=",
"CONF",
".",
"get",
"(",
"\"endpointRoot\"",
",",
"\"flask-profiler\"",
")",
"fp",
"=",
"Blueprint",
"(",
"'flask-profiler'",
",",
"__name__",
",",
"url_prefix",
"=",
"\"/\"",
"+",
"urlPat... | These are the endpoints which are used to display measurements in the
flask-profiler dashboard.
Note: these should be defined after wrapping user defined endpoints
via wrapAppEndpoints()
:param app: Flask application instance
:return: | [
"These",
"are",
"the",
"endpoints",
"which",
"are",
"used",
"to",
"display",
"measurements",
"in",
"the",
"flask",
"-",
"profiler",
"dashboard",
"."
] | 51b4354fc14f8cfdd538ec9db98fa1cf545ccd18 | https://github.com/muatik/flask-profiler/blob/51b4354fc14f8cfdd538ec9db98fa1cf545ccd18/flask_profiler/flask_profiler.py#L167-L241 | train | 207,156 |
sassoftware/sas_kernel | sas_kernel/magics/log_magic.py | logMagic.line_showLog | def line_showLog(self):
"""
SAS Kernel magic to show the SAS log for the previous submitted code.
This magic is only available within the SAS Kernel
"""
if self.kernel.mva is None:
print("Can't show log because no session exists")
else:
return self.kernel.Display(HTML(self.kernel.cachedlog)) | python | def line_showLog(self):
"""
SAS Kernel magic to show the SAS log for the previous submitted code.
This magic is only available within the SAS Kernel
"""
if self.kernel.mva is None:
print("Can't show log because no session exists")
else:
return self.kernel.Display(HTML(self.kernel.cachedlog)) | [
"def",
"line_showLog",
"(",
"self",
")",
":",
"if",
"self",
".",
"kernel",
".",
"mva",
"is",
"None",
":",
"print",
"(",
"\"Can't show log because no session exists\"",
")",
"else",
":",
"return",
"self",
".",
"kernel",
".",
"Display",
"(",
"HTML",
"(",
"se... | SAS Kernel magic to show the SAS log for the previous submitted code.
This magic is only available within the SAS Kernel | [
"SAS",
"Kernel",
"magic",
"to",
"show",
"the",
"SAS",
"log",
"for",
"the",
"previous",
"submitted",
"code",
".",
"This",
"magic",
"is",
"only",
"available",
"within",
"the",
"SAS",
"Kernel"
] | ed63dceb9d1d51157b465f4892ffb793c1c32307 | https://github.com/sassoftware/sas_kernel/blob/ed63dceb9d1d51157b465f4892ffb793c1c32307/sas_kernel/magics/log_magic.py#L26-L34 | train | 207,157 |
sassoftware/sas_kernel | sas_kernel/kernel.py | SASKernel._which_display | def _which_display(self, log: str, output: str) -> HTML:
"""
Determines if the log or lst should be returned as the results for the cell based on parsing the log
looking for errors and the presence of lst output.
:param log: str log from code submission
:param output: None or str lst output if there was any
:return: The correct results based on log and lst
:rtype: str
"""
lines = re.split(r'[\n]\s*', log)
i = 0
elog = []
for line in lines:
i += 1
e = []
if line.startswith('ERROR'):
logger.debug("In ERROR Condition")
e = lines[(max(i - 15, 0)):(min(i + 16, len(lines)))]
elog = elog + e
tlog = '\n'.join(elog)
logger.debug("elog count: " + str(len(elog)))
logger.debug("tlog: " + str(tlog))
color_log = highlight(log, SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>"))
# store the log for display in the showSASLog nbextension
self.cachedlog = color_log
# Are there errors in the log? if show the lines on each side of the error
if len(elog) == 0 and len(output) > self.lst_len: # no error and LST output
debug1 = 1
logger.debug("DEBUG1: " + str(debug1) + " no error and LST output ")
return HTML(output)
elif len(elog) == 0 and len(output) <= self.lst_len: # no error and no LST
debug1 = 2
logger.debug("DEBUG1: " + str(debug1) + " no error and no LST")
return HTML(color_log)
elif len(elog) > 0 and len(output) <= self.lst_len: # error and no LST
debug1 = 3
logger.debug("DEBUG1: " + str(debug1) + " error and no LST")
return HTML(color_log)
else: # errors and LST
debug1 = 4
logger.debug("DEBUG1: " + str(debug1) + " errors and LST")
return HTML(color_log + output) | python | def _which_display(self, log: str, output: str) -> HTML:
"""
Determines if the log or lst should be returned as the results for the cell based on parsing the log
looking for errors and the presence of lst output.
:param log: str log from code submission
:param output: None or str lst output if there was any
:return: The correct results based on log and lst
:rtype: str
"""
lines = re.split(r'[\n]\s*', log)
i = 0
elog = []
for line in lines:
i += 1
e = []
if line.startswith('ERROR'):
logger.debug("In ERROR Condition")
e = lines[(max(i - 15, 0)):(min(i + 16, len(lines)))]
elog = elog + e
tlog = '\n'.join(elog)
logger.debug("elog count: " + str(len(elog)))
logger.debug("tlog: " + str(tlog))
color_log = highlight(log, SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>"))
# store the log for display in the showSASLog nbextension
self.cachedlog = color_log
# Are there errors in the log? if show the lines on each side of the error
if len(elog) == 0 and len(output) > self.lst_len: # no error and LST output
debug1 = 1
logger.debug("DEBUG1: " + str(debug1) + " no error and LST output ")
return HTML(output)
elif len(elog) == 0 and len(output) <= self.lst_len: # no error and no LST
debug1 = 2
logger.debug("DEBUG1: " + str(debug1) + " no error and no LST")
return HTML(color_log)
elif len(elog) > 0 and len(output) <= self.lst_len: # error and no LST
debug1 = 3
logger.debug("DEBUG1: " + str(debug1) + " error and no LST")
return HTML(color_log)
else: # errors and LST
debug1 = 4
logger.debug("DEBUG1: " + str(debug1) + " errors and LST")
return HTML(color_log + output) | [
"def",
"_which_display",
"(",
"self",
",",
"log",
":",
"str",
",",
"output",
":",
"str",
")",
"->",
"HTML",
":",
"lines",
"=",
"re",
".",
"split",
"(",
"r'[\\n]\\s*'",
",",
"log",
")",
"i",
"=",
"0",
"elog",
"=",
"[",
"]",
"for",
"line",
"in",
... | Determines if the log or lst should be returned as the results for the cell based on parsing the log
looking for errors and the presence of lst output.
:param log: str log from code submission
:param output: None or str lst output if there was any
:return: The correct results based on log and lst
:rtype: str | [
"Determines",
"if",
"the",
"log",
"or",
"lst",
"should",
"be",
"returned",
"as",
"the",
"results",
"for",
"the",
"cell",
"based",
"on",
"parsing",
"the",
"log",
"looking",
"for",
"errors",
"and",
"the",
"presence",
"of",
"lst",
"output",
"."
] | ed63dceb9d1d51157b465f4892ffb793c1c32307 | https://github.com/sassoftware/sas_kernel/blob/ed63dceb9d1d51157b465f4892ffb793c1c32307/sas_kernel/kernel.py#L86-L129 | train | 207,158 |
sassoftware/sas_kernel | sas_kernel/kernel.py | SASKernel.do_execute_direct | def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]:
"""
This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list
"""
if not code.strip():
return {'status': 'ok', 'execution_count': self.execution_count,
'payload': [], 'user_expressions': {}}
if self.mva is None:
self._allow_stdin = True
self._start_sas()
if self.lst_len < 0:
self._get_lst_len()
if code.startswith('Obfuscated SAS Code'):
logger.debug("decoding string")
tmp1 = code.split()
decode = base64.b64decode(tmp1[-1])
code = decode.decode('utf-8')
if code.startswith('showSASLog_11092015') == False and code.startswith("CompleteshowSASLog_11092015") == False:
logger.debug("code type: " + str(type(code)))
logger.debug("code length: " + str(len(code)))
logger.debug("code string: " + code)
if code.startswith("/*SASKernelTest*/"):
res = self.mva.submit(code, "text")
else:
res = self.mva.submit(code, prompt=self.promptDict)
self.promptDict = {}
if res['LOG'].find("SAS process has terminated unexpectedly") > -1:
print(res['LOG'], '\n' "Restarting SAS session on your behalf")
self.do_shutdown(True)
return res['LOG']
output = res['LST']
log = res['LOG']
return self._which_display(log, output)
elif code.startswith("CompleteshowSASLog_11092015") == True and code.startswith('showSASLog_11092015') == False:
full_log = highlight(self.mva.saslog(), SASLogLexer(),
HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>",
title="Full SAS Log"))
return full_log.replace('\n', ' ')
else:
return self.cachedlog.replace('\n', ' ') | python | def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]:
"""
This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list
"""
if not code.strip():
return {'status': 'ok', 'execution_count': self.execution_count,
'payload': [], 'user_expressions': {}}
if self.mva is None:
self._allow_stdin = True
self._start_sas()
if self.lst_len < 0:
self._get_lst_len()
if code.startswith('Obfuscated SAS Code'):
logger.debug("decoding string")
tmp1 = code.split()
decode = base64.b64decode(tmp1[-1])
code = decode.decode('utf-8')
if code.startswith('showSASLog_11092015') == False and code.startswith("CompleteshowSASLog_11092015") == False:
logger.debug("code type: " + str(type(code)))
logger.debug("code length: " + str(len(code)))
logger.debug("code string: " + code)
if code.startswith("/*SASKernelTest*/"):
res = self.mva.submit(code, "text")
else:
res = self.mva.submit(code, prompt=self.promptDict)
self.promptDict = {}
if res['LOG'].find("SAS process has terminated unexpectedly") > -1:
print(res['LOG'], '\n' "Restarting SAS session on your behalf")
self.do_shutdown(True)
return res['LOG']
output = res['LST']
log = res['LOG']
return self._which_display(log, output)
elif code.startswith("CompleteshowSASLog_11092015") == True and code.startswith('showSASLog_11092015') == False:
full_log = highlight(self.mva.saslog(), SASLogLexer(),
HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>",
title="Full SAS Log"))
return full_log.replace('\n', ' ')
else:
return self.cachedlog.replace('\n', ' ') | [
"def",
"do_execute_direct",
"(",
"self",
",",
"code",
":",
"str",
",",
"silent",
":",
"bool",
"=",
"False",
")",
"->",
"[",
"str",
",",
"dict",
"]",
":",
"if",
"not",
"code",
".",
"strip",
"(",
")",
":",
"return",
"{",
"'status'",
":",
"'ok'",
",... | This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list | [
"This",
"is",
"the",
"main",
"method",
"that",
"takes",
"code",
"from",
"the",
"Jupyter",
"cell",
"and",
"submits",
"it",
"to",
"the",
"SAS",
"server"
] | ed63dceb9d1d51157b465f4892ffb793c1c32307 | https://github.com/sassoftware/sas_kernel/blob/ed63dceb9d1d51157b465f4892ffb793c1c32307/sas_kernel/kernel.py#L131-L179 | train | 207,159 |
sassoftware/sas_kernel | sas_kernel/kernel.py | SASKernel.get_completions | def get_completions(self, info):
"""
Get completions from kernel for procs and statements.
"""
if info['line_num'] > 1:
relstart = info['column'] - (info['help_pos'] - info['start'])
else:
relstart = info['start']
seg = info['line'][:relstart]
if relstart > 0 and re.match('(?i)proc', seg.rsplit(None, 1)[-1]):
potentials = re.findall('(?i)^' + info['obj'] + '.*', self.strproclist, re.MULTILINE)
return potentials
else:
lastproc = info['code'].lower()[:info['help_pos']].rfind('proc')
lastdata = info['code'].lower()[:info['help_pos']].rfind('data ')
proc = False
data = False
if lastproc + lastdata == -2:
pass
else:
if lastproc > lastdata:
proc = True
else:
data = True
if proc:
# we are not in data section should see if proc option or statement
lastsemi = info['code'].rfind(';')
mykey = 's'
if lastproc > lastsemi:
mykey = 'p'
procer = re.search('(?i)proc\s\w+', info['code'][lastproc:])
method = procer.group(0).split(' ')[-1].upper() + mykey
mylist = self.compglo[method][0]
potentials = re.findall('(?i)' + info['obj'] + '.+', '\n'.join(str(x) for x in mylist), re.MULTILINE)
return potentials
elif data:
# we are in statements (probably if there is no data)
# assuming we are in the middle of the code
lastsemi = info['code'].rfind(';')
mykey = 's'
if lastproc > lastsemi:
mykey = 'p'
mylist = self.compglo['DATA' + mykey][0]
potentials = re.findall('(?i)^' + info['obj'] + '.*', '\n'.join(str(x) for x in mylist), re.MULTILINE)
return potentials
else:
potentials = ['']
return potentials | python | def get_completions(self, info):
"""
Get completions from kernel for procs and statements.
"""
if info['line_num'] > 1:
relstart = info['column'] - (info['help_pos'] - info['start'])
else:
relstart = info['start']
seg = info['line'][:relstart]
if relstart > 0 and re.match('(?i)proc', seg.rsplit(None, 1)[-1]):
potentials = re.findall('(?i)^' + info['obj'] + '.*', self.strproclist, re.MULTILINE)
return potentials
else:
lastproc = info['code'].lower()[:info['help_pos']].rfind('proc')
lastdata = info['code'].lower()[:info['help_pos']].rfind('data ')
proc = False
data = False
if lastproc + lastdata == -2:
pass
else:
if lastproc > lastdata:
proc = True
else:
data = True
if proc:
# we are not in data section should see if proc option or statement
lastsemi = info['code'].rfind(';')
mykey = 's'
if lastproc > lastsemi:
mykey = 'p'
procer = re.search('(?i)proc\s\w+', info['code'][lastproc:])
method = procer.group(0).split(' ')[-1].upper() + mykey
mylist = self.compglo[method][0]
potentials = re.findall('(?i)' + info['obj'] + '.+', '\n'.join(str(x) for x in mylist), re.MULTILINE)
return potentials
elif data:
# we are in statements (probably if there is no data)
# assuming we are in the middle of the code
lastsemi = info['code'].rfind(';')
mykey = 's'
if lastproc > lastsemi:
mykey = 'p'
mylist = self.compglo['DATA' + mykey][0]
potentials = re.findall('(?i)^' + info['obj'] + '.*', '\n'.join(str(x) for x in mylist), re.MULTILINE)
return potentials
else:
potentials = ['']
return potentials | [
"def",
"get_completions",
"(",
"self",
",",
"info",
")",
":",
"if",
"info",
"[",
"'line_num'",
"]",
">",
"1",
":",
"relstart",
"=",
"info",
"[",
"'column'",
"]",
"-",
"(",
"info",
"[",
"'help_pos'",
"]",
"-",
"info",
"[",
"'start'",
"]",
")",
"else... | Get completions from kernel for procs and statements. | [
"Get",
"completions",
"from",
"kernel",
"for",
"procs",
"and",
"statements",
"."
] | ed63dceb9d1d51157b465f4892ffb793c1c32307 | https://github.com/sassoftware/sas_kernel/blob/ed63dceb9d1d51157b465f4892ffb793c1c32307/sas_kernel/kernel.py#L181-L230 | train | 207,160 |
sassoftware/sas_kernel | sas_kernel/kernel.py | SASKernel.do_shutdown | def do_shutdown(self, restart):
"""
Shut down the app gracefully, saving history.
"""
print("in shutdown function")
if self.hist_file:
with open(self.hist_file, 'wb') as fid:
data = '\n'.join(self.hist_cache[-self.max_hist_cache:])
fid.write(data.encode('utf-8'))
if self.mva:
self.mva._endsas()
self.mva = None
if restart:
self.Print("Restarting kernel...")
self.reload_magics()
self.restart_kernel()
self.Print("Done!")
return {'status': 'ok', 'restart': restart} | python | def do_shutdown(self, restart):
"""
Shut down the app gracefully, saving history.
"""
print("in shutdown function")
if self.hist_file:
with open(self.hist_file, 'wb') as fid:
data = '\n'.join(self.hist_cache[-self.max_hist_cache:])
fid.write(data.encode('utf-8'))
if self.mva:
self.mva._endsas()
self.mva = None
if restart:
self.Print("Restarting kernel...")
self.reload_magics()
self.restart_kernel()
self.Print("Done!")
return {'status': 'ok', 'restart': restart} | [
"def",
"do_shutdown",
"(",
"self",
",",
"restart",
")",
":",
"print",
"(",
"\"in shutdown function\"",
")",
"if",
"self",
".",
"hist_file",
":",
"with",
"open",
"(",
"self",
".",
"hist_file",
",",
"'wb'",
")",
"as",
"fid",
":",
"data",
"=",
"'\\n'",
".... | Shut down the app gracefully, saving history. | [
"Shut",
"down",
"the",
"app",
"gracefully",
"saving",
"history",
"."
] | ed63dceb9d1d51157b465f4892ffb793c1c32307 | https://github.com/sassoftware/sas_kernel/blob/ed63dceb9d1d51157b465f4892ffb793c1c32307/sas_kernel/kernel.py#L259-L276 | train | 207,161 |
Kozea/wdb | client/wdb/ui.py | Interaction.get_globals | def get_globals(self):
"""Get enriched globals"""
if self.shell:
globals_ = dict(_initial_globals)
else:
globals_ = dict(self.current_frame.f_globals)
globals_['_'] = self.db.last_obj
if cut is not None:
globals_.setdefault('cut', cut)
# For meta debuging purpose
globals_['___wdb'] = self.db
# Hack for function scope eval
globals_.update(self.current_locals)
for var, val in self.db.extra_vars.items():
globals_[var] = val
self.db.extra_items = {}
return globals_ | python | def get_globals(self):
"""Get enriched globals"""
if self.shell:
globals_ = dict(_initial_globals)
else:
globals_ = dict(self.current_frame.f_globals)
globals_['_'] = self.db.last_obj
if cut is not None:
globals_.setdefault('cut', cut)
# For meta debuging purpose
globals_['___wdb'] = self.db
# Hack for function scope eval
globals_.update(self.current_locals)
for var, val in self.db.extra_vars.items():
globals_[var] = val
self.db.extra_items = {}
return globals_ | [
"def",
"get_globals",
"(",
"self",
")",
":",
"if",
"self",
".",
"shell",
":",
"globals_",
"=",
"dict",
"(",
"_initial_globals",
")",
"else",
":",
"globals_",
"=",
"dict",
"(",
"self",
".",
"current_frame",
".",
"f_globals",
")",
"globals_",
"[",
"'_'",
... | Get enriched globals | [
"Get",
"enriched",
"globals"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/ui.py#L135-L151 | train | 207,162 |
Kozea/wdb | client/wdb/ui.py | Interaction.handle_exc | def handle_exc(self):
"""Return a formated exception traceback for wdb.js use"""
exc_info = sys.exc_info()
type_, value = exc_info[:2]
self.db.obj_cache[id(exc_info)] = exc_info
return '<a href="%d" class="inspect">%s: %s</a>' % (
id(exc_info), escape(type_.__name__), escape(repr(value))
) | python | def handle_exc(self):
"""Return a formated exception traceback for wdb.js use"""
exc_info = sys.exc_info()
type_, value = exc_info[:2]
self.db.obj_cache[id(exc_info)] = exc_info
return '<a href="%d" class="inspect">%s: %s</a>' % (
id(exc_info), escape(type_.__name__), escape(repr(value))
) | [
"def",
"handle_exc",
"(",
"self",
")",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"type_",
",",
"value",
"=",
"exc_info",
"[",
":",
"2",
"]",
"self",
".",
"db",
".",
"obj_cache",
"[",
"id",
"(",
"exc_info",
")",
"]",
"=",
"exc_info",
... | Return a formated exception traceback for wdb.js use | [
"Return",
"a",
"formated",
"exception",
"traceback",
"for",
"wdb",
".",
"js",
"use"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/ui.py#L879-L887 | train | 207,163 |
Kozea/wdb | client/wdb/ui.py | Interaction.fail | def fail(self, cmd, title=None, message=None):
"""Send back captured exceptions"""
if message is None:
message = self.handle_exc()
else:
message = escape(message)
self.db.send(
'Echo|%s' % dump({
'for': escape(title or '%s failed' % cmd),
'val': message
})
) | python | def fail(self, cmd, title=None, message=None):
"""Send back captured exceptions"""
if message is None:
message = self.handle_exc()
else:
message = escape(message)
self.db.send(
'Echo|%s' % dump({
'for': escape(title or '%s failed' % cmd),
'val': message
})
) | [
"def",
"fail",
"(",
"self",
",",
"cmd",
",",
"title",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"self",
".",
"handle_exc",
"(",
")",
"else",
":",
"message",
"=",
"escape",
"(",
"message"... | Send back captured exceptions | [
"Send",
"back",
"captured",
"exceptions"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/ui.py#L889-L900 | train | 207,164 |
Kozea/wdb | client/wdb/__main__.py | main | def main():
"""Wdb entry point"""
sys.path.insert(0, os.getcwd())
args, extrargs = parser.parse_known_args()
sys.argv = ['wdb'] + args.args + extrargs
if args.file:
file = os.path.join(os.getcwd(), args.file)
if args.source:
print('The source argument cannot be used with file.')
sys.exit(1)
if not os.path.exists(file):
print('Error:', file, 'does not exist')
sys.exit(1)
if args.trace:
Wdb.get().run_file(file)
else:
def wdb_pm(xtype, value, traceback):
sys.__excepthook__(xtype, value, traceback)
wdb = Wdb.get()
wdb.reset()
wdb.interaction(None, traceback, post_mortem=True)
sys.excepthook = wdb_pm
with open(file) as f:
code = compile(f.read(), file, 'exec')
execute(code, globals(), globals())
else:
source = None
if args.source:
source = os.path.join(os.getcwd(), args.source)
if not os.path.exists(source):
print('Error:', source, 'does not exist')
sys.exit(1)
Wdb.get().shell(source) | python | def main():
"""Wdb entry point"""
sys.path.insert(0, os.getcwd())
args, extrargs = parser.parse_known_args()
sys.argv = ['wdb'] + args.args + extrargs
if args.file:
file = os.path.join(os.getcwd(), args.file)
if args.source:
print('The source argument cannot be used with file.')
sys.exit(1)
if not os.path.exists(file):
print('Error:', file, 'does not exist')
sys.exit(1)
if args.trace:
Wdb.get().run_file(file)
else:
def wdb_pm(xtype, value, traceback):
sys.__excepthook__(xtype, value, traceback)
wdb = Wdb.get()
wdb.reset()
wdb.interaction(None, traceback, post_mortem=True)
sys.excepthook = wdb_pm
with open(file) as f:
code = compile(f.read(), file, 'exec')
execute(code, globals(), globals())
else:
source = None
if args.source:
source = os.path.join(os.getcwd(), args.source)
if not os.path.exists(source):
print('Error:', source, 'does not exist')
sys.exit(1)
Wdb.get().shell(source) | [
"def",
"main",
"(",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"getcwd",
"(",
")",
")",
"args",
",",
"extrargs",
"=",
"parser",
".",
"parse_known_args",
"(",
")",
"sys",
".",
"argv",
"=",
"[",
"'wdb'",
"]",
"+",
"arg... | Wdb entry point | [
"Wdb",
"entry",
"point"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__main__.py#L25-L64 | train | 207,165 |
Kozea/wdb | client/wdb/ext.py | _patch_tcpserver | def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if thread in _exc_cache:
post_mortem_interaction(*_exc_cache.pop(thread))
TCPServer.shutdown_request = shutdown_request_patched | python | def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if thread in _exc_cache:
post_mortem_interaction(*_exc_cache.pop(thread))
TCPServer.shutdown_request = shutdown_request_patched | [
"def",
"_patch_tcpserver",
"(",
")",
":",
"shutdown_request",
"=",
"TCPServer",
".",
"shutdown_request",
"def",
"shutdown_request_patched",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"current_thread",
"(",
")",
"shutdown_request",
"(",
... | Patch shutdown_request to open blocking interaction after the end of the
request | [
"Patch",
"shutdown_request",
"to",
"open",
"blocking",
"interaction",
"after",
"the",
"end",
"of",
"the",
"request"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/ext.py#L33-L46 | train | 207,166 |
Kozea/wdb | client/wdb/state.py | State.up | def up(self):
"""Go up in stack and return True if top frame"""
if self.frame:
self.frame = self.frame.f_back
return self.frame is None | python | def up(self):
"""Go up in stack and return True if top frame"""
if self.frame:
self.frame = self.frame.f_back
return self.frame is None | [
"def",
"up",
"(",
"self",
")",
":",
"if",
"self",
".",
"frame",
":",
"self",
".",
"frame",
"=",
"self",
".",
"frame",
".",
"f_back",
"return",
"self",
".",
"frame",
"is",
"None"
] | Go up in stack and return True if top frame | [
"Go",
"up",
"in",
"stack",
"and",
"return",
"True",
"if",
"top",
"frame"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/state.py#L8-L12 | train | 207,167 |
Kozea/wdb | client/wdb/__init__.py | set_trace | def set_trace(frame=None, skip=0, server=None, port=None):
"""Set trace on current line, or on given frame"""
frame = frame or sys._getframe().f_back
for i in range(skip):
if not frame.f_back:
break
frame = frame.f_back
wdb = Wdb.get(server=server, port=port)
wdb.set_trace(frame)
return wdb | python | def set_trace(frame=None, skip=0, server=None, port=None):
"""Set trace on current line, or on given frame"""
frame = frame or sys._getframe().f_back
for i in range(skip):
if not frame.f_back:
break
frame = frame.f_back
wdb = Wdb.get(server=server, port=port)
wdb.set_trace(frame)
return wdb | [
"def",
"set_trace",
"(",
"frame",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"frame",
"=",
"frame",
"or",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
"for",
"i",
"in",
"range",
"(",
... | Set trace on current line, or on given frame | [
"Set",
"trace",
"on",
"current",
"line",
"or",
"on",
"given",
"frame"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L987-L996 | train | 207,168 |
Kozea/wdb | client/wdb/__init__.py | cleanup | def cleanup():
"""Close all sockets at exit"""
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) | python | def cleanup():
"""Close all sockets at exit"""
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) | [
"def",
"cleanup",
"(",
")",
":",
"for",
"sck",
"in",
"list",
"(",
"Wdb",
".",
"_sockets",
")",
":",
"try",
":",
"sck",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"log",
".",
"warn",
"(",
"'Error in cleanup'",
",",
"exc_info",
"=",
"True",
... | Close all sockets at exit | [
"Close",
"all",
"sockets",
"at",
"exit"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L1043-L1049 | train | 207,169 |
Kozea/wdb | client/wdb/__init__.py | shell | def shell(source=None, vars=None, server=None, port=None):
"""Start a shell sourcing source or using vars as locals"""
Wdb.get(server=server, port=port).shell(source=source, vars=vars) | python | def shell(source=None, vars=None, server=None, port=None):
"""Start a shell sourcing source or using vars as locals"""
Wdb.get(server=server, port=port).shell(source=source, vars=vars) | [
"def",
"shell",
"(",
"source",
"=",
"None",
",",
"vars",
"=",
"None",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"Wdb",
".",
"get",
"(",
"server",
"=",
"server",
",",
"port",
"=",
"port",
")",
".",
"shell",
"(",
"source",
"... | Start a shell sourcing source or using vars as locals | [
"Start",
"a",
"shell",
"sourcing",
"source",
"or",
"using",
"vars",
"as",
"locals"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L1052-L1054 | train | 207,170 |
Kozea/wdb | client/wdb/__init__.py | Wdb.get | def get(no_create=False, server=None, port=None, force_uuid=None):
"""Get the thread local singleton"""
pid = os.getpid()
thread = threading.current_thread()
wdb = Wdb._instances.get((pid, thread))
if not wdb and not no_create:
wdb = object.__new__(Wdb)
Wdb.__init__(wdb, server, port, force_uuid)
wdb.pid = pid
wdb.thread = thread
Wdb._instances[(pid, thread)] = wdb
elif wdb:
if (server is not None and wdb.server != server
or port is not None and wdb.port != port):
log.warn('Different server/port set, ignoring')
else:
wdb.reconnect_if_needed()
return wdb | python | def get(no_create=False, server=None, port=None, force_uuid=None):
"""Get the thread local singleton"""
pid = os.getpid()
thread = threading.current_thread()
wdb = Wdb._instances.get((pid, thread))
if not wdb and not no_create:
wdb = object.__new__(Wdb)
Wdb.__init__(wdb, server, port, force_uuid)
wdb.pid = pid
wdb.thread = thread
Wdb._instances[(pid, thread)] = wdb
elif wdb:
if (server is not None and wdb.server != server
or port is not None and wdb.port != port):
log.warn('Different server/port set, ignoring')
else:
wdb.reconnect_if_needed()
return wdb | [
"def",
"get",
"(",
"no_create",
"=",
"False",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
",",
"force_uuid",
"=",
"None",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"thread",
"=",
"threading",
".",
"current_thread",
"(",
")",
"w... | Get the thread local singleton | [
"Get",
"the",
"thread",
"local",
"singleton"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L96-L113 | train | 207,171 |
Kozea/wdb | client/wdb/__init__.py | Wdb.pop | def pop():
"""Remove instance from instance list"""
pid = os.getpid()
thread = threading.current_thread()
Wdb._instances.pop((pid, thread)) | python | def pop():
"""Remove instance from instance list"""
pid = os.getpid()
thread = threading.current_thread()
Wdb._instances.pop((pid, thread)) | [
"def",
"pop",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"thread",
"=",
"threading",
".",
"current_thread",
"(",
")",
"Wdb",
".",
"_instances",
".",
"pop",
"(",
"(",
"pid",
",",
"thread",
")",
")"
] | Remove instance from instance list | [
"Remove",
"instance",
"from",
"instance",
"list"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L116-L120 | train | 207,172 |
Kozea/wdb | client/wdb/__init__.py | Wdb.run_file | def run_file(self, filename):
"""Run the file `filename` with trace"""
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": filename,
"__builtins__": __builtins__,
})
with open(filename, "rb") as fp:
statement = compile(fp.read(), filename, 'exec')
self.run(statement, filename) | python | def run_file(self, filename):
"""Run the file `filename` with trace"""
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": filename,
"__builtins__": __builtins__,
})
with open(filename, "rb") as fp:
statement = compile(fp.read(), filename, 'exec')
self.run(statement, filename) | [
"def",
"run_file",
"(",
"self",
",",
"filename",
")",
":",
"import",
"__main__",
"__main__",
".",
"__dict__",
".",
"clear",
"(",
")",
"__main__",
".",
"__dict__",
".",
"update",
"(",
"{",
"\"__name__\"",
":",
"\"__main__\"",
",",
"\"__file__\"",
":",
"file... | Run the file `filename` with trace | [
"Run",
"the",
"file",
"filename",
"with",
"trace"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L152-L163 | train | 207,173 |
Kozea/wdb | client/wdb/__init__.py | Wdb.run | def run(self, cmd, fn=None, globals=None, locals=None):
"""Run the cmd `cmd` with trace"""
if globals is None:
import __main__
globals = __main__.__dict__
if locals is None:
locals = globals
self.reset()
if isinstance(cmd, str):
str_cmd = cmd
cmd = compile(str_cmd, fn or "<wdb>", "exec")
self.compile_cache[id(cmd)] = str_cmd
if fn:
from linecache import getline
lno = 1
while True:
line = getline(fn, lno, globals)
if line is None:
lno = None
break
if executable_line(line):
break
lno += 1
self.start_trace()
if lno is not None:
self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True))
try:
execute(cmd, globals, locals)
finally:
self.stop_trace() | python | def run(self, cmd, fn=None, globals=None, locals=None):
"""Run the cmd `cmd` with trace"""
if globals is None:
import __main__
globals = __main__.__dict__
if locals is None:
locals = globals
self.reset()
if isinstance(cmd, str):
str_cmd = cmd
cmd = compile(str_cmd, fn or "<wdb>", "exec")
self.compile_cache[id(cmd)] = str_cmd
if fn:
from linecache import getline
lno = 1
while True:
line = getline(fn, lno, globals)
if line is None:
lno = None
break
if executable_line(line):
break
lno += 1
self.start_trace()
if lno is not None:
self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True))
try:
execute(cmd, globals, locals)
finally:
self.stop_trace() | [
"def",
"run",
"(",
"self",
",",
"cmd",
",",
"fn",
"=",
"None",
",",
"globals",
"=",
"None",
",",
"locals",
"=",
"None",
")",
":",
"if",
"globals",
"is",
"None",
":",
"import",
"__main__",
"globals",
"=",
"__main__",
".",
"__dict__",
"if",
"locals",
... | Run the cmd `cmd` with trace | [
"Run",
"the",
"cmd",
"cmd",
"with",
"trace"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L165-L195 | train | 207,174 |
Kozea/wdb | client/wdb/__init__.py | Wdb.connect | def connect(self):
"""Connect to wdb server"""
log.info('Connecting socket on %s:%d' % (self.server, self.port))
tries = 0
while not self._socket and tries < 10:
try:
time.sleep(.2 * tries)
self._socket = Socket((self.server, self.port))
except socket.error:
tries += 1
log.warning(
'You must start/install wdb.server '
'(Retrying on %s:%d) [Try #%d/10]' %
(self.server, self.port, tries)
)
self._socket = None
if not self._socket:
log.warning('Could not connect to server')
return
Wdb._sockets.append(self._socket)
self._socket.send_bytes(self.uuid.encode('utf-8')) | python | def connect(self):
"""Connect to wdb server"""
log.info('Connecting socket on %s:%d' % (self.server, self.port))
tries = 0
while not self._socket and tries < 10:
try:
time.sleep(.2 * tries)
self._socket = Socket((self.server, self.port))
except socket.error:
tries += 1
log.warning(
'You must start/install wdb.server '
'(Retrying on %s:%d) [Try #%d/10]' %
(self.server, self.port, tries)
)
self._socket = None
if not self._socket:
log.warning('Could not connect to server')
return
Wdb._sockets.append(self._socket)
self._socket.send_bytes(self.uuid.encode('utf-8')) | [
"def",
"connect",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Connecting socket on %s:%d'",
"%",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
")",
"tries",
"=",
"0",
"while",
"not",
"self",
".",
"_socket",
"and",
"tries",
"<",
"10... | Connect to wdb server | [
"Connect",
"to",
"wdb",
"server"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L215-L237 | train | 207,175 |
Kozea/wdb | client/wdb/__init__.py | Wdb.trace_dispatch | def trace_dispatch(self, frame, event, arg):
"""This function is called every line,
function call, function return and exception during trace"""
fun = getattr(self, 'handle_' + event, None)
if not fun:
return self.trace_dispatch
below, continue_below = self.check_below(frame)
if (self.state.stops(frame, event)
or (event == 'line' and self.breaks(frame))
or (event == 'exception' and (self.full or below))):
fun(frame, arg)
if event == 'return' and frame == self.state.frame:
# Upping state
if self.state.up():
# No more frames
self.stop_trace()
return
# Threading / Multiprocessing support
co = self.state.frame.f_code
if ((co.co_filename.endswith('threading.py')
and co.co_name.endswith('_bootstrap_inner'))
or (self.state.frame.f_code.co_filename.endswith(
os.path.join('multiprocessing', 'process.py'))
and self.state.frame.f_code.co_name == '_bootstrap')):
# Thread / Process is dead
self.stop_trace()
self.die()
return
if (event == 'call' and not self.stepping and not self.full
and not continue_below
and not self.get_file_breaks(frame.f_code.co_filename)):
# Don't trace anymore here
return
return self.trace_dispatch | python | def trace_dispatch(self, frame, event, arg):
"""This function is called every line,
function call, function return and exception during trace"""
fun = getattr(self, 'handle_' + event, None)
if not fun:
return self.trace_dispatch
below, continue_below = self.check_below(frame)
if (self.state.stops(frame, event)
or (event == 'line' and self.breaks(frame))
or (event == 'exception' and (self.full or below))):
fun(frame, arg)
if event == 'return' and frame == self.state.frame:
# Upping state
if self.state.up():
# No more frames
self.stop_trace()
return
# Threading / Multiprocessing support
co = self.state.frame.f_code
if ((co.co_filename.endswith('threading.py')
and co.co_name.endswith('_bootstrap_inner'))
or (self.state.frame.f_code.co_filename.endswith(
os.path.join('multiprocessing', 'process.py'))
and self.state.frame.f_code.co_name == '_bootstrap')):
# Thread / Process is dead
self.stop_trace()
self.die()
return
if (event == 'call' and not self.stepping and not self.full
and not continue_below
and not self.get_file_breaks(frame.f_code.co_filename)):
# Don't trace anymore here
return
return self.trace_dispatch | [
"def",
"trace_dispatch",
"(",
"self",
",",
"frame",
",",
"event",
",",
"arg",
")",
":",
"fun",
"=",
"getattr",
"(",
"self",
",",
"'handle_'",
"+",
"event",
",",
"None",
")",
"if",
"not",
"fun",
":",
"return",
"self",
".",
"trace_dispatch",
"below",
"... | This function is called every line,
function call, function return and exception during trace | [
"This",
"function",
"is",
"called",
"every",
"line",
"function",
"call",
"function",
"return",
"and",
"exception",
"during",
"trace"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L316-L351 | train | 207,176 |
Kozea/wdb | client/wdb/__init__.py | Wdb.trace_debug_dispatch | def trace_debug_dispatch(self, frame, event, arg):
"""Utility function to add debug to tracing"""
trace_log.info(
'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg)
)
trace_log.debug(
'state %r breaks ? %s stops ? %s' % (
self.state, self.breaks(frame, no_remove=True),
self.state.stops(frame, event)
)
)
if event == 'return':
trace_log.debug(
'Return: frame: %s, state: %s, state.f_back: %s' % (
pretty_frame(frame), pretty_frame(self.state.frame),
pretty_frame(self.state.frame.f_back)
)
)
if self.trace_dispatch(frame, event, arg):
return self.trace_debug_dispatch
trace_log.debug("No trace %s" % pretty_frame(frame)) | python | def trace_debug_dispatch(self, frame, event, arg):
"""Utility function to add debug to tracing"""
trace_log.info(
'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg)
)
trace_log.debug(
'state %r breaks ? %s stops ? %s' % (
self.state, self.breaks(frame, no_remove=True),
self.state.stops(frame, event)
)
)
if event == 'return':
trace_log.debug(
'Return: frame: %s, state: %s, state.f_back: %s' % (
pretty_frame(frame), pretty_frame(self.state.frame),
pretty_frame(self.state.frame.f_back)
)
)
if self.trace_dispatch(frame, event, arg):
return self.trace_debug_dispatch
trace_log.debug("No trace %s" % pretty_frame(frame)) | [
"def",
"trace_debug_dispatch",
"(",
"self",
",",
"frame",
",",
"event",
",",
"arg",
")",
":",
"trace_log",
".",
"info",
"(",
"'Frame:%s. Event: %s. Arg: %r'",
"%",
"(",
"pretty_frame",
"(",
"frame",
")",
",",
"event",
",",
"arg",
")",
")",
"trace_log",
"."... | Utility function to add debug to tracing | [
"Utility",
"function",
"to",
"add",
"debug",
"to",
"tracing"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L353-L373 | train | 207,177 |
Kozea/wdb | client/wdb/__init__.py | Wdb.start_trace | def start_trace(self, full=False, frame=None, below=0, under=None):
"""Start tracing from here"""
if self.tracing:
return
self.reset()
log.info('Starting trace')
frame = frame or sys._getframe().f_back
# Setting trace without pausing
self.set_trace(frame, break_=False)
self.tracing = True
self.below = below
self.under = under
self.full = full | python | def start_trace(self, full=False, frame=None, below=0, under=None):
"""Start tracing from here"""
if self.tracing:
return
self.reset()
log.info('Starting trace')
frame = frame or sys._getframe().f_back
# Setting trace without pausing
self.set_trace(frame, break_=False)
self.tracing = True
self.below = below
self.under = under
self.full = full | [
"def",
"start_trace",
"(",
"self",
",",
"full",
"=",
"False",
",",
"frame",
"=",
"None",
",",
"below",
"=",
"0",
",",
"under",
"=",
"None",
")",
":",
"if",
"self",
".",
"tracing",
":",
"return",
"self",
".",
"reset",
"(",
")",
"log",
".",
"info",... | Start tracing from here | [
"Start",
"tracing",
"from",
"here"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L375-L387 | train | 207,178 |
Kozea/wdb | client/wdb/__init__.py | Wdb.set_trace | def set_trace(self, frame=None, break_=True):
"""Break at current state"""
# We are already tracing, do nothing
trace_log.info(
'Setting trace %s (stepping %s) (current_trace: %s)' % (
pretty_frame(frame or sys._getframe().f_back), self.stepping,
sys.gettrace()
)
)
if self.stepping or self.closed:
return
self.reset()
trace = (
self.trace_dispatch
if trace_log.level >= 30 else self.trace_debug_dispatch
)
trace_frame = frame = frame or sys._getframe().f_back
while frame:
frame.f_trace = trace
frame = frame.f_back
self.state = Step(trace_frame) if break_ else Running(trace_frame)
sys.settrace(trace) | python | def set_trace(self, frame=None, break_=True):
"""Break at current state"""
# We are already tracing, do nothing
trace_log.info(
'Setting trace %s (stepping %s) (current_trace: %s)' % (
pretty_frame(frame or sys._getframe().f_back), self.stepping,
sys.gettrace()
)
)
if self.stepping or self.closed:
return
self.reset()
trace = (
self.trace_dispatch
if trace_log.level >= 30 else self.trace_debug_dispatch
)
trace_frame = frame = frame or sys._getframe().f_back
while frame:
frame.f_trace = trace
frame = frame.f_back
self.state = Step(trace_frame) if break_ else Running(trace_frame)
sys.settrace(trace) | [
"def",
"set_trace",
"(",
"self",
",",
"frame",
"=",
"None",
",",
"break_",
"=",
"True",
")",
":",
"# We are already tracing, do nothing",
"trace_log",
".",
"info",
"(",
"'Setting trace %s (stepping %s) (current_trace: %s)'",
"%",
"(",
"pretty_frame",
"(",
"frame",
"... | Break at current state | [
"Break",
"at",
"current",
"state"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L389-L410 | train | 207,179 |
Kozea/wdb | client/wdb/__init__.py | Wdb.stop_trace | def stop_trace(self, frame=None):
"""Stop tracing from here"""
self.tracing = False
self.full = False
frame = frame or sys._getframe().f_back
while frame:
del frame.f_trace
frame = frame.f_back
sys.settrace(None)
log.info('Stopping trace') | python | def stop_trace(self, frame=None):
"""Stop tracing from here"""
self.tracing = False
self.full = False
frame = frame or sys._getframe().f_back
while frame:
del frame.f_trace
frame = frame.f_back
sys.settrace(None)
log.info('Stopping trace') | [
"def",
"stop_trace",
"(",
"self",
",",
"frame",
"=",
"None",
")",
":",
"self",
".",
"tracing",
"=",
"False",
"self",
".",
"full",
"=",
"False",
"frame",
"=",
"frame",
"or",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
"while",
"frame",
":",
"d... | Stop tracing from here | [
"Stop",
"tracing",
"from",
"here"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L412-L421 | train | 207,180 |
Kozea/wdb | client/wdb/__init__.py | Wdb.set_until | def set_until(self, frame, lineno=None):
"""Stop on the next line number."""
self.state = Until(frame, frame.f_lineno) | python | def set_until(self, frame, lineno=None):
"""Stop on the next line number."""
self.state = Until(frame, frame.f_lineno) | [
"def",
"set_until",
"(",
"self",
",",
"frame",
",",
"lineno",
"=",
"None",
")",
":",
"self",
".",
"state",
"=",
"Until",
"(",
"frame",
",",
"frame",
".",
"f_lineno",
")"
] | Stop on the next line number. | [
"Stop",
"on",
"the",
"next",
"line",
"number",
"."
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L423-L425 | train | 207,181 |
Kozea/wdb | client/wdb/__init__.py | Wdb.set_continue | def set_continue(self, frame):
"""Don't stop anymore"""
self.state = Running(frame)
if not self.tracing and not self.breakpoints:
# If we were in a set_trace and there's no breakpoint to trace for
# Run without trace
self.stop_trace() | python | def set_continue(self, frame):
"""Don't stop anymore"""
self.state = Running(frame)
if not self.tracing and not self.breakpoints:
# If we were in a set_trace and there's no breakpoint to trace for
# Run without trace
self.stop_trace() | [
"def",
"set_continue",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"state",
"=",
"Running",
"(",
"frame",
")",
"if",
"not",
"self",
".",
"tracing",
"and",
"not",
"self",
".",
"breakpoints",
":",
"# If we were in a set_trace and there's no breakpoint to tra... | Don't stop anymore | [
"Don",
"t",
"stop",
"anymore"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L439-L445 | train | 207,182 |
Kozea/wdb | client/wdb/__init__.py | Wdb.set_break | def set_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
):
"""Put a breakpoint for filename"""
log.info(
'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary, cond, funcname
)
self.breakpoints.add(breakpoint)
log.info('Breakpoint %r added' % breakpoint)
return breakpoint | python | def set_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
):
"""Put a breakpoint for filename"""
log.info(
'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary, cond, funcname
)
self.breakpoints.add(breakpoint)
log.info('Breakpoint %r added' % breakpoint)
return breakpoint | [
"def",
"set_break",
"(",
"self",
",",
"filename",
",",
"lineno",
"=",
"None",
",",
"temporary",
"=",
"False",
",",
"cond",
"=",
"None",
",",
"funcname",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s'",
"%"... | Put a breakpoint for filename | [
"Put",
"a",
"breakpoint",
"for",
"filename"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L457-L471 | train | 207,183 |
Kozea/wdb | client/wdb/__init__.py | Wdb.clear_break | def clear_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
):
"""Remove a breakpoint"""
log.info(
'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary or False, cond, funcname
)
if temporary is None and breakpoint not in self.breakpoints:
breakpoint = self.get_break(filename, lineno, True, cond, funcname)
try:
self.breakpoints.remove(breakpoint)
log.info('Breakpoint %r removed' % breakpoint)
except Exception:
log.info('Breakpoint %r not removed: not found' % breakpoint) | python | def clear_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
):
"""Remove a breakpoint"""
log.info(
'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary or False, cond, funcname
)
if temporary is None and breakpoint not in self.breakpoints:
breakpoint = self.get_break(filename, lineno, True, cond, funcname)
try:
self.breakpoints.remove(breakpoint)
log.info('Breakpoint %r removed' % breakpoint)
except Exception:
log.info('Breakpoint %r not removed: not found' % breakpoint) | [
"def",
"clear_break",
"(",
"self",
",",
"filename",
",",
"lineno",
"=",
"None",
",",
"temporary",
"=",
"False",
",",
"cond",
"=",
"None",
",",
"funcname",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s'",
... | Remove a breakpoint | [
"Remove",
"a",
"breakpoint"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L473-L493 | train | 207,184 |
Kozea/wdb | client/wdb/__init__.py | Wdb.safe_repr | def safe_repr(self, obj):
"""Like a repr but without exception"""
try:
return repr(obj)
except Exception as e:
return '??? Broken repr (%s: %s)' % (type(e).__name__, e) | python | def safe_repr(self, obj):
"""Like a repr but without exception"""
try:
return repr(obj)
except Exception as e:
return '??? Broken repr (%s: %s)' % (type(e).__name__, e) | [
"def",
"safe_repr",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"return",
"repr",
"(",
"obj",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"'??? Broken repr (%s: %s)'",
"%",
"(",
"type",
"(",
"e",
")",
".",
"__name__",
",",
"e",
")"
] | Like a repr but without exception | [
"Like",
"a",
"repr",
"but",
"without",
"exception"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L495-L500 | train | 207,185 |
Kozea/wdb | client/wdb/__init__.py | Wdb.safe_better_repr | def safe_better_repr(
self, obj, context=None, html=True, level=0, full=False
):
"""Repr with inspect links on objects"""
context = context and dict(context) or {}
recursion = id(obj) in context
if not recursion:
context[id(obj)] = obj
try:
rv = self.better_repr(obj, context, html, level + 1, full)
except Exception:
rv = None
if rv:
return rv
self.obj_cache[id(obj)] = obj
if html:
return '<a href="%d" class="inspect">%s%s</a>' % (
id(obj), 'Recursion of '
if recursion else '', escape(self.safe_repr(obj))
)
return '%s%s' % (
'Recursion of ' if recursion else '', self.safe_repr(obj)
) | python | def safe_better_repr(
self, obj, context=None, html=True, level=0, full=False
):
"""Repr with inspect links on objects"""
context = context and dict(context) or {}
recursion = id(obj) in context
if not recursion:
context[id(obj)] = obj
try:
rv = self.better_repr(obj, context, html, level + 1, full)
except Exception:
rv = None
if rv:
return rv
self.obj_cache[id(obj)] = obj
if html:
return '<a href="%d" class="inspect">%s%s</a>' % (
id(obj), 'Recursion of '
if recursion else '', escape(self.safe_repr(obj))
)
return '%s%s' % (
'Recursion of ' if recursion else '', self.safe_repr(obj)
) | [
"def",
"safe_better_repr",
"(",
"self",
",",
"obj",
",",
"context",
"=",
"None",
",",
"html",
"=",
"True",
",",
"level",
"=",
"0",
",",
"full",
"=",
"False",
")",
":",
"context",
"=",
"context",
"and",
"dict",
"(",
"context",
")",
"or",
"{",
"}",
... | Repr with inspect links on objects | [
"Repr",
"with",
"inspect",
"links",
"on",
"objects"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L502-L525 | train | 207,186 |
Kozea/wdb | client/wdb/__init__.py | Wdb.capture_output | def capture_output(self, with_hook=True):
"""Steal stream output, return them in string, restore them"""
self.hooked = ''
def display_hook(obj):
# That's some dirty hack
self.hooked += self.safe_better_repr(obj)
self.last_obj = obj
stdout, stderr = sys.stdout, sys.stderr
if with_hook:
d_hook = sys.displayhook
sys.displayhook = display_hook
sys.stdout, sys.stderr = StringIO(), StringIO()
out, err = [], []
try:
yield out, err
finally:
out.extend(sys.stdout.getvalue().splitlines())
err.extend(sys.stderr.getvalue().splitlines())
if with_hook:
sys.displayhook = d_hook
sys.stdout, sys.stderr = stdout, stderr | python | def capture_output(self, with_hook=True):
"""Steal stream output, return them in string, restore them"""
self.hooked = ''
def display_hook(obj):
# That's some dirty hack
self.hooked += self.safe_better_repr(obj)
self.last_obj = obj
stdout, stderr = sys.stdout, sys.stderr
if with_hook:
d_hook = sys.displayhook
sys.displayhook = display_hook
sys.stdout, sys.stderr = StringIO(), StringIO()
out, err = [], []
try:
yield out, err
finally:
out.extend(sys.stdout.getvalue().splitlines())
err.extend(sys.stderr.getvalue().splitlines())
if with_hook:
sys.displayhook = d_hook
sys.stdout, sys.stderr = stdout, stderr | [
"def",
"capture_output",
"(",
"self",
",",
"with_hook",
"=",
"True",
")",
":",
"self",
".",
"hooked",
"=",
"''",
"def",
"display_hook",
"(",
"obj",
")",
":",
"# That's some dirty hack",
"self",
".",
"hooked",
"+=",
"self",
".",
"safe_better_repr",
"(",
"ob... | Steal stream output, return them in string, restore them | [
"Steal",
"stream",
"output",
"return",
"them",
"in",
"string",
"restore",
"them"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L634-L658 | train | 207,187 |
Kozea/wdb | client/wdb/__init__.py | Wdb.dmp | def dmp(self, thing):
"""Dump the content of an object in a dict for wdb.js"""
def safe_getattr(key):
"""Avoid crash on getattr"""
try:
return getattr(thing, key)
except Exception as e:
return 'Error getting attr "%s" from "%s" (%s: %s)' % (
key, thing, type(e).__name__, e
)
return dict((
escape(key), {
'val': self.safe_better_repr(safe_getattr(key)),
'type': type(safe_getattr(key)).__name__
}
) for key in dir(thing)) | python | def dmp(self, thing):
"""Dump the content of an object in a dict for wdb.js"""
def safe_getattr(key):
"""Avoid crash on getattr"""
try:
return getattr(thing, key)
except Exception as e:
return 'Error getting attr "%s" from "%s" (%s: %s)' % (
key, thing, type(e).__name__, e
)
return dict((
escape(key), {
'val': self.safe_better_repr(safe_getattr(key)),
'type': type(safe_getattr(key)).__name__
}
) for key in dir(thing)) | [
"def",
"dmp",
"(",
"self",
",",
"thing",
")",
":",
"def",
"safe_getattr",
"(",
"key",
")",
":",
"\"\"\"Avoid crash on getattr\"\"\"",
"try",
":",
"return",
"getattr",
"(",
"thing",
",",
"key",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"'Error g... | Dump the content of an object in a dict for wdb.js | [
"Dump",
"the",
"content",
"of",
"an",
"object",
"in",
"a",
"dict",
"for",
"wdb",
".",
"js"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L660-L677 | train | 207,188 |
Kozea/wdb | client/wdb/__init__.py | Wdb.get_file | def get_file(self, filename):
"""Get file source from cache"""
import linecache
# Hack for frozen importlib bootstrap
if filename == '<frozen importlib._bootstrap>':
filename = os.path.join(
os.path.dirname(linecache.__file__), 'importlib',
'_bootstrap.py'
)
return to_unicode_string(
''.join(linecache.getlines(filename)), filename
) | python | def get_file(self, filename):
"""Get file source from cache"""
import linecache
# Hack for frozen importlib bootstrap
if filename == '<frozen importlib._bootstrap>':
filename = os.path.join(
os.path.dirname(linecache.__file__), 'importlib',
'_bootstrap.py'
)
return to_unicode_string(
''.join(linecache.getlines(filename)), filename
) | [
"def",
"get_file",
"(",
"self",
",",
"filename",
")",
":",
"import",
"linecache",
"# Hack for frozen importlib bootstrap",
"if",
"filename",
"==",
"'<frozen importlib._bootstrap>'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".... | Get file source from cache | [
"Get",
"file",
"source",
"from",
"cache"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L679-L690 | train | 207,189 |
Kozea/wdb | client/wdb/__init__.py | Wdb.get_stack | def get_stack(self, f, t):
"""Build the stack from frame and traceback"""
stack = []
if t and t.tb_frame == f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
while t is not None:
stack.append((t.tb_frame, t.tb_lineno))
t = t.tb_next
if f is None:
i = max(0, len(stack) - 1)
return stack, i | python | def get_stack(self, f, t):
"""Build the stack from frame and traceback"""
stack = []
if t and t.tb_frame == f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
while t is not None:
stack.append((t.tb_frame, t.tb_lineno))
t = t.tb_next
if f is None:
i = max(0, len(stack) - 1)
return stack, i | [
"def",
"get_stack",
"(",
"self",
",",
"f",
",",
"t",
")",
":",
"stack",
"=",
"[",
"]",
"if",
"t",
"and",
"t",
".",
"tb_frame",
"==",
"f",
":",
"t",
"=",
"t",
".",
"tb_next",
"while",
"f",
"is",
"not",
"None",
":",
"stack",
".",
"append",
"(",... | Build the stack from frame and traceback | [
"Build",
"the",
"stack",
"from",
"frame",
"and",
"traceback"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L692-L707 | train | 207,190 |
Kozea/wdb | client/wdb/__init__.py | Wdb.get_trace | def get_trace(self, frame, tb):
"""Get a dict of the traceback for wdb.js use"""
import linecache
frames = []
stack, _ = self.get_stack(frame, tb)
current = 0
for i, (stack_frame, lno) in enumerate(stack):
code = stack_frame.f_code
filename = code.co_filename or '<unspecified>'
line = None
if filename[0] == '<' and filename[-1] == '>':
line = get_source_from_byte_code(code)
fn = filename
else:
fn = os.path.abspath(filename)
if not line:
linecache.checkcache(filename)
line = linecache.getline(filename, lno, stack_frame.f_globals)
if not line:
line = self.compile_cache.get(id(code), '')
line = to_unicode_string(line, filename)
line = line and line.strip()
startlnos = dis.findlinestarts(code)
lastlineno = list(startlnos)[-1][1]
if frame == stack_frame:
current = i
frames.append({
'file': fn,
'function': code.co_name,
'flno': code.co_firstlineno,
'llno': lastlineno,
'lno': lno,
'code': line,
'level': i,
'current': frame == stack_frame
})
# While in exception always put the context to the top
return stack, frames, current | python | def get_trace(self, frame, tb):
"""Get a dict of the traceback for wdb.js use"""
import linecache
frames = []
stack, _ = self.get_stack(frame, tb)
current = 0
for i, (stack_frame, lno) in enumerate(stack):
code = stack_frame.f_code
filename = code.co_filename or '<unspecified>'
line = None
if filename[0] == '<' and filename[-1] == '>':
line = get_source_from_byte_code(code)
fn = filename
else:
fn = os.path.abspath(filename)
if not line:
linecache.checkcache(filename)
line = linecache.getline(filename, lno, stack_frame.f_globals)
if not line:
line = self.compile_cache.get(id(code), '')
line = to_unicode_string(line, filename)
line = line and line.strip()
startlnos = dis.findlinestarts(code)
lastlineno = list(startlnos)[-1][1]
if frame == stack_frame:
current = i
frames.append({
'file': fn,
'function': code.co_name,
'flno': code.co_firstlineno,
'llno': lastlineno,
'lno': lno,
'code': line,
'level': i,
'current': frame == stack_frame
})
# While in exception always put the context to the top
return stack, frames, current | [
"def",
"get_trace",
"(",
"self",
",",
"frame",
",",
"tb",
")",
":",
"import",
"linecache",
"frames",
"=",
"[",
"]",
"stack",
",",
"_",
"=",
"self",
".",
"get_stack",
"(",
"frame",
",",
"tb",
")",
"current",
"=",
"0",
"for",
"i",
",",
"(",
"stack_... | Get a dict of the traceback for wdb.js use | [
"Get",
"a",
"dict",
"of",
"the",
"traceback",
"for",
"wdb",
".",
"js",
"use"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L709-L748 | train | 207,191 |
Kozea/wdb | client/wdb/__init__.py | Wdb.send | def send(self, data):
"""Send data through websocket"""
log.debug('Sending %s' % data)
if not self._socket:
log.warn('No connection')
return
self._socket.send_bytes(data.encode('utf-8')) | python | def send(self, data):
"""Send data through websocket"""
log.debug('Sending %s' % data)
if not self._socket:
log.warn('No connection')
return
self._socket.send_bytes(data.encode('utf-8')) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"log",
".",
"debug",
"(",
"'Sending %s'",
"%",
"data",
")",
"if",
"not",
"self",
".",
"_socket",
":",
"log",
".",
"warn",
"(",
"'No connection'",
")",
"return",
"self",
".",
"_socket",
".",
"send_byt... | Send data through websocket | [
"Send",
"data",
"through",
"websocket"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L750-L756 | train | 207,192 |
Kozea/wdb | client/wdb/__init__.py | Wdb.receive | def receive(self, timeout=None):
"""Receive data through websocket"""
log.debug('Receiving')
if not self._socket:
log.warn('No connection')
return
try:
if timeout:
rv = self._socket.poll(timeout)
if not rv:
log.info('Connection timeouted')
return 'Quit'
data = self._socket.recv_bytes()
except Exception:
log.error('Connection lost')
return 'Quit'
log.debug('Got %s' % data)
return data.decode('utf-8') | python | def receive(self, timeout=None):
"""Receive data through websocket"""
log.debug('Receiving')
if not self._socket:
log.warn('No connection')
return
try:
if timeout:
rv = self._socket.poll(timeout)
if not rv:
log.info('Connection timeouted')
return 'Quit'
data = self._socket.recv_bytes()
except Exception:
log.error('Connection lost')
return 'Quit'
log.debug('Got %s' % data)
return data.decode('utf-8') | [
"def",
"receive",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Receiving'",
")",
"if",
"not",
"self",
".",
"_socket",
":",
"log",
".",
"warn",
"(",
"'No connection'",
")",
"return",
"try",
":",
"if",
"timeout",
":",... | Receive data through websocket | [
"Receive",
"data",
"through",
"websocket"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L758-L776 | train | 207,193 |
Kozea/wdb | client/wdb/__init__.py | Wdb.interaction | def interaction(
self,
frame,
tb=None,
exception='Wdb',
exception_description='Stepping',
init=None,
shell=False,
shell_vars=None,
source=None,
iframe_mode=False,
timeout=None,
post_mortem=False
):
"""User interaction handling blocking on socket receive"""
log.info(
'Interaction %r %r %r %r' %
(frame, tb, exception, exception_description)
)
self.reconnect_if_needed()
self.stepping = not shell
if not iframe_mode:
opts = {}
if shell:
opts['type_'] = 'shell'
if post_mortem:
opts['type_'] = 'pm'
self.open_browser(**opts)
lvl = len(self.interaction_stack)
if lvl:
exception_description += ' [recursive%s]' % (
'^%d' % lvl if lvl > 1 else ''
)
interaction = Interaction(
self,
frame,
tb,
exception,
exception_description,
init=init,
shell=shell,
shell_vars=shell_vars,
source=source,
timeout=timeout
)
self.interaction_stack.append(interaction)
# For meta debugging purpose
self._ui = interaction
if self.begun:
# Each new state sends the trace and selects a frame
interaction.init()
else:
self.begun = True
interaction.loop()
self.interaction_stack.pop()
if lvl:
self.interaction_stack[-1].init() | python | def interaction(
self,
frame,
tb=None,
exception='Wdb',
exception_description='Stepping',
init=None,
shell=False,
shell_vars=None,
source=None,
iframe_mode=False,
timeout=None,
post_mortem=False
):
"""User interaction handling blocking on socket receive"""
log.info(
'Interaction %r %r %r %r' %
(frame, tb, exception, exception_description)
)
self.reconnect_if_needed()
self.stepping = not shell
if not iframe_mode:
opts = {}
if shell:
opts['type_'] = 'shell'
if post_mortem:
opts['type_'] = 'pm'
self.open_browser(**opts)
lvl = len(self.interaction_stack)
if lvl:
exception_description += ' [recursive%s]' % (
'^%d' % lvl if lvl > 1 else ''
)
interaction = Interaction(
self,
frame,
tb,
exception,
exception_description,
init=init,
shell=shell,
shell_vars=shell_vars,
source=source,
timeout=timeout
)
self.interaction_stack.append(interaction)
# For meta debugging purpose
self._ui = interaction
if self.begun:
# Each new state sends the trace and selects a frame
interaction.init()
else:
self.begun = True
interaction.loop()
self.interaction_stack.pop()
if lvl:
self.interaction_stack[-1].init() | [
"def",
"interaction",
"(",
"self",
",",
"frame",
",",
"tb",
"=",
"None",
",",
"exception",
"=",
"'Wdb'",
",",
"exception_description",
"=",
"'Stepping'",
",",
"init",
"=",
"None",
",",
"shell",
"=",
"False",
",",
"shell_vars",
"=",
"None",
",",
"source",... | User interaction handling blocking on socket receive | [
"User",
"interaction",
"handling",
"blocking",
"on",
"socket",
"receive"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L813-L876 | train | 207,194 |
Kozea/wdb | client/wdb/__init__.py | Wdb.breaks | def breaks(self, frame, no_remove=False):
"""Return True if there's a breakpoint at frame"""
for breakpoint in set(self.breakpoints):
if breakpoint.breaks(frame):
if breakpoint.temporary and not no_remove:
self.breakpoints.remove(breakpoint)
return True
return False | python | def breaks(self, frame, no_remove=False):
"""Return True if there's a breakpoint at frame"""
for breakpoint in set(self.breakpoints):
if breakpoint.breaks(frame):
if breakpoint.temporary and not no_remove:
self.breakpoints.remove(breakpoint)
return True
return False | [
"def",
"breaks",
"(",
"self",
",",
"frame",
",",
"no_remove",
"=",
"False",
")",
":",
"for",
"breakpoint",
"in",
"set",
"(",
"self",
".",
"breakpoints",
")",
":",
"if",
"breakpoint",
".",
"breaks",
"(",
"frame",
")",
":",
"if",
"breakpoint",
".",
"te... | Return True if there's a breakpoint at frame | [
"Return",
"True",
"if",
"there",
"s",
"a",
"breakpoint",
"at",
"frame"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L946-L953 | train | 207,195 |
Kozea/wdb | client/wdb/__init__.py | Wdb.get_file_breaks | def get_file_breaks(self, filename):
"""List all file `filename` breakpoints"""
return [
breakpoint for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
] | python | def get_file_breaks(self, filename):
"""List all file `filename` breakpoints"""
return [
breakpoint for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
] | [
"def",
"get_file_breaks",
"(",
"self",
",",
"filename",
")",
":",
"return",
"[",
"breakpoint",
"for",
"breakpoint",
"in",
"self",
".",
"breakpoints",
"if",
"breakpoint",
".",
"on_file",
"(",
"filename",
")",
"]"
] | List all file `filename` breakpoints | [
"List",
"all",
"file",
"filename",
"breakpoints"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L955-L960 | train | 207,196 |
Kozea/wdb | client/wdb/__init__.py | Wdb.get_breaks_lno | def get_breaks_lno(self, filename):
"""List all line numbers that have a breakpoint"""
return list(
filter(
lambda x: x is not None, [
getattr(breakpoint, 'line', None)
for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
]
)
) | python | def get_breaks_lno(self, filename):
"""List all line numbers that have a breakpoint"""
return list(
filter(
lambda x: x is not None, [
getattr(breakpoint, 'line', None)
for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
]
)
) | [
"def",
"get_breaks_lno",
"(",
"self",
",",
"filename",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"[",
"getattr",
"(",
"breakpoint",
",",
"'line'",
",",
"None",
")",
"for",
"breakpoint",
"in",
"... | List all line numbers that have a breakpoint | [
"List",
"all",
"line",
"numbers",
"that",
"have",
"a",
"breakpoint"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L962-L972 | train | 207,197 |
Kozea/wdb | client/wdb/__init__.py | Wdb.die | def die(self):
"""Time to quit"""
log.info('Time to die')
if self.connected:
try:
self.send('Die')
except Exception:
pass
if self._socket:
self._socket.close()
self.pop() | python | def die(self):
"""Time to quit"""
log.info('Time to die')
if self.connected:
try:
self.send('Die')
except Exception:
pass
if self._socket:
self._socket.close()
self.pop() | [
"def",
"die",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Time to die'",
")",
"if",
"self",
".",
"connected",
":",
"try",
":",
"self",
".",
"send",
"(",
"'Die'",
")",
"except",
"Exception",
":",
"pass",
"if",
"self",
".",
"_socket",
":",
"sel... | Time to quit | [
"Time",
"to",
"quit"
] | 6af7901b02e866d76f8b0a697a8c078e5b70d1aa | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L974-L984 | train | 207,198 |
nickstenning/honcho | honcho/manager.py | Manager._killall | def _killall(self, force=False):
"""Kill all remaining processes, forcefully if requested."""
for_termination = []
for n, p in iteritems(self._processes):
if 'returncode' not in p:
for_termination.append(n)
for n in for_termination:
p = self._processes[n]
signame = 'SIGKILL' if force else 'SIGTERM'
self._system_print("sending %s to %s (pid %s)\n" %
(signame, n, p['pid']))
if force:
self._env.kill(p['pid'])
else:
self._env.terminate(p['pid']) | python | def _killall(self, force=False):
"""Kill all remaining processes, forcefully if requested."""
for_termination = []
for n, p in iteritems(self._processes):
if 'returncode' not in p:
for_termination.append(n)
for n in for_termination:
p = self._processes[n]
signame = 'SIGKILL' if force else 'SIGTERM'
self._system_print("sending %s to %s (pid %s)\n" %
(signame, n, p['pid']))
if force:
self._env.kill(p['pid'])
else:
self._env.terminate(p['pid']) | [
"def",
"_killall",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"for_termination",
"=",
"[",
"]",
"for",
"n",
",",
"p",
"in",
"iteritems",
"(",
"self",
".",
"_processes",
")",
":",
"if",
"'returncode'",
"not",
"in",
"p",
":",
"for_termination",
... | Kill all remaining processes, forcefully if requested. | [
"Kill",
"all",
"remaining",
"processes",
"forcefully",
"if",
"requested",
"."
] | f3b2e1e11868283f4c3463102b7ed3bd00f26b32 | https://github.com/nickstenning/honcho/blob/f3b2e1e11868283f4c3463102b7ed3bd00f26b32/honcho/manager.py#L157-L173 | train | 207,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.