partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
valid
|
Parser.parse_definitions
|
Parse multiple definitions and yield them.
|
flake8_rst_docstrings.py
|
def parse_definitions(self, class_, all=False):
"""Parse multiple definitions and yield them."""
while self.current is not None:
self.log.debug(
"parsing definition list, current token is %r (%s)",
self.current.kind,
self.current.value,
)
self.log.debug("got_newline: %s", self.stream.got_logical_newline)
if all and self.current.value == "__all__":
self.parse_all()
elif (
self.current.kind == tk.OP
and self.current.value == "@"
and self.stream.got_logical_newline
):
self.consume(tk.OP)
self.parse_decorators()
elif self.current.value in ["def", "class"]:
yield self.parse_definition(class_._nest(self.current.value))
elif self.current.kind == tk.INDENT:
self.consume(tk.INDENT)
for definition in self.parse_definitions(class_):
yield definition
elif self.current.kind == tk.DEDENT:
self.consume(tk.DEDENT)
return
elif self.current.value == "from":
self.parse_from_import_statement()
else:
self.stream.move()
|
def parse_definitions(self, class_, all=False):
"""Parse multiple definitions and yield them."""
while self.current is not None:
self.log.debug(
"parsing definition list, current token is %r (%s)",
self.current.kind,
self.current.value,
)
self.log.debug("got_newline: %s", self.stream.got_logical_newline)
if all and self.current.value == "__all__":
self.parse_all()
elif (
self.current.kind == tk.OP
and self.current.value == "@"
and self.stream.got_logical_newline
):
self.consume(tk.OP)
self.parse_decorators()
elif self.current.value in ["def", "class"]:
yield self.parse_definition(class_._nest(self.current.value))
elif self.current.kind == tk.INDENT:
self.consume(tk.INDENT)
for definition in self.parse_definitions(class_):
yield definition
elif self.current.kind == tk.DEDENT:
self.consume(tk.DEDENT)
return
elif self.current.value == "from":
self.parse_from_import_statement()
else:
self.stream.move()
|
[
"Parse",
"multiple",
"definitions",
"and",
"yield",
"them",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L695-L725
|
[
"def",
"parse_definitions",
"(",
"self",
",",
"class_",
",",
"all",
"=",
"False",
")",
":",
"while",
"self",
".",
"current",
"is",
"not",
"None",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"parsing definition list, current token is %r (%s)\"",
",",
"self",
".",
"current",
".",
"kind",
",",
"self",
".",
"current",
".",
"value",
",",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"got_newline: %s\"",
",",
"self",
".",
"stream",
".",
"got_logical_newline",
")",
"if",
"all",
"and",
"self",
".",
"current",
".",
"value",
"==",
"\"__all__\"",
":",
"self",
".",
"parse_all",
"(",
")",
"elif",
"(",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"OP",
"and",
"self",
".",
"current",
".",
"value",
"==",
"\"@\"",
"and",
"self",
".",
"stream",
".",
"got_logical_newline",
")",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"OP",
")",
"self",
".",
"parse_decorators",
"(",
")",
"elif",
"self",
".",
"current",
".",
"value",
"in",
"[",
"\"def\"",
",",
"\"class\"",
"]",
":",
"yield",
"self",
".",
"parse_definition",
"(",
"class_",
".",
"_nest",
"(",
"self",
".",
"current",
".",
"value",
")",
")",
"elif",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"INDENT",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"INDENT",
")",
"for",
"definition",
"in",
"self",
".",
"parse_definitions",
"(",
"class_",
")",
":",
"yield",
"definition",
"elif",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"DEDENT",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"DEDENT",
")",
"return",
"elif",
"self",
".",
"current",
".",
"value",
"==",
"\"from\"",
":",
"self",
".",
"parse_from_import_statement",
"(",
")",
"else",
":",
"self",
".",
"stream",
".",
"move",
"(",
")"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
Parser.parse_all
|
Parse the __all__ definition in a module.
|
flake8_rst_docstrings.py
|
def parse_all(self):
"""Parse the __all__ definition in a module."""
assert self.current.value == "__all__"
self.consume(tk.NAME)
if self.current.value != "=":
raise AllError("Could not evaluate contents of __all__. ")
self.consume(tk.OP)
if self.current.value not in "([":
raise AllError("Could not evaluate contents of __all__. ")
self.consume(tk.OP)
self.all = []
all_content = "("
while self.current.kind != tk.OP or self.current.value not in ")]":
if self.current.kind in (tk.NL, tk.COMMENT):
pass
elif self.current.kind == tk.STRING or self.current.value == ",":
all_content += self.current.value
else:
raise AllError(
"Unexpected token kind in __all__: {!r}. ".format(
self.current.kind
)
)
self.stream.move()
self.consume(tk.OP)
all_content += ")"
try:
self.all = eval(all_content, {})
except BaseException as e:
raise AllError(
"Could not evaluate contents of __all__."
"\bThe value was {}. The exception was:\n{}".format(all_content, e)
)
|
def parse_all(self):
"""Parse the __all__ definition in a module."""
assert self.current.value == "__all__"
self.consume(tk.NAME)
if self.current.value != "=":
raise AllError("Could not evaluate contents of __all__. ")
self.consume(tk.OP)
if self.current.value not in "([":
raise AllError("Could not evaluate contents of __all__. ")
self.consume(tk.OP)
self.all = []
all_content = "("
while self.current.kind != tk.OP or self.current.value not in ")]":
if self.current.kind in (tk.NL, tk.COMMENT):
pass
elif self.current.kind == tk.STRING or self.current.value == ",":
all_content += self.current.value
else:
raise AllError(
"Unexpected token kind in __all__: {!r}. ".format(
self.current.kind
)
)
self.stream.move()
self.consume(tk.OP)
all_content += ")"
try:
self.all = eval(all_content, {})
except BaseException as e:
raise AllError(
"Could not evaluate contents of __all__."
"\bThe value was {}. The exception was:\n{}".format(all_content, e)
)
|
[
"Parse",
"the",
"__all__",
"definition",
"in",
"a",
"module",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L727-L760
|
[
"def",
"parse_all",
"(",
"self",
")",
":",
"assert",
"self",
".",
"current",
".",
"value",
"==",
"\"__all__\"",
"self",
".",
"consume",
"(",
"tk",
".",
"NAME",
")",
"if",
"self",
".",
"current",
".",
"value",
"!=",
"\"=\"",
":",
"raise",
"AllError",
"(",
"\"Could not evaluate contents of __all__. \"",
")",
"self",
".",
"consume",
"(",
"tk",
".",
"OP",
")",
"if",
"self",
".",
"current",
".",
"value",
"not",
"in",
"\"([\"",
":",
"raise",
"AllError",
"(",
"\"Could not evaluate contents of __all__. \"",
")",
"self",
".",
"consume",
"(",
"tk",
".",
"OP",
")",
"self",
".",
"all",
"=",
"[",
"]",
"all_content",
"=",
"\"(\"",
"while",
"self",
".",
"current",
".",
"kind",
"!=",
"tk",
".",
"OP",
"or",
"self",
".",
"current",
".",
"value",
"not",
"in",
"\")]\"",
":",
"if",
"self",
".",
"current",
".",
"kind",
"in",
"(",
"tk",
".",
"NL",
",",
"tk",
".",
"COMMENT",
")",
":",
"pass",
"elif",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"STRING",
"or",
"self",
".",
"current",
".",
"value",
"==",
"\",\"",
":",
"all_content",
"+=",
"self",
".",
"current",
".",
"value",
"else",
":",
"raise",
"AllError",
"(",
"\"Unexpected token kind in __all__: {!r}. \"",
".",
"format",
"(",
"self",
".",
"current",
".",
"kind",
")",
")",
"self",
".",
"stream",
".",
"move",
"(",
")",
"self",
".",
"consume",
"(",
"tk",
".",
"OP",
")",
"all_content",
"+=",
"\")\"",
"try",
":",
"self",
".",
"all",
"=",
"eval",
"(",
"all_content",
",",
"{",
"}",
")",
"except",
"BaseException",
"as",
"e",
":",
"raise",
"AllError",
"(",
"\"Could not evaluate contents of __all__.\"",
"\"\\bThe value was {}. The exception was:\\n{}\"",
".",
"format",
"(",
"all_content",
",",
"e",
")",
")"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
Parser.parse_module
|
Parse a module (and its children) and return a Module object.
|
flake8_rst_docstrings.py
|
def parse_module(self):
"""Parse a module (and its children) and return a Module object."""
self.log.debug("parsing module.")
start = self.line
docstring = self.parse_docstring()
children = list(self.parse_definitions(Module, all=True))
assert self.current is None, self.current
end = self.line
cls = Module
if self.filename.endswith("__init__.py"):
cls = Package
module = cls(
self.filename,
self.source,
start,
end,
[],
docstring,
children,
None,
self.all,
None,
"",
)
for child in module.children:
child.parent = module
module.future_imports = self.future_imports
self.log.debug("finished parsing module.")
return module
|
def parse_module(self):
"""Parse a module (and its children) and return a Module object."""
self.log.debug("parsing module.")
start = self.line
docstring = self.parse_docstring()
children = list(self.parse_definitions(Module, all=True))
assert self.current is None, self.current
end = self.line
cls = Module
if self.filename.endswith("__init__.py"):
cls = Package
module = cls(
self.filename,
self.source,
start,
end,
[],
docstring,
children,
None,
self.all,
None,
"",
)
for child in module.children:
child.parent = module
module.future_imports = self.future_imports
self.log.debug("finished parsing module.")
return module
|
[
"Parse",
"a",
"module",
"(",
"and",
"its",
"children",
")",
"and",
"return",
"a",
"Module",
"object",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L762-L790
|
[
"def",
"parse_module",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"parsing module.\"",
")",
"start",
"=",
"self",
".",
"line",
"docstring",
"=",
"self",
".",
"parse_docstring",
"(",
")",
"children",
"=",
"list",
"(",
"self",
".",
"parse_definitions",
"(",
"Module",
",",
"all",
"=",
"True",
")",
")",
"assert",
"self",
".",
"current",
"is",
"None",
",",
"self",
".",
"current",
"end",
"=",
"self",
".",
"line",
"cls",
"=",
"Module",
"if",
"self",
".",
"filename",
".",
"endswith",
"(",
"\"__init__.py\"",
")",
":",
"cls",
"=",
"Package",
"module",
"=",
"cls",
"(",
"self",
".",
"filename",
",",
"self",
".",
"source",
",",
"start",
",",
"end",
",",
"[",
"]",
",",
"docstring",
",",
"children",
",",
"None",
",",
"self",
".",
"all",
",",
"None",
",",
"\"\"",
",",
")",
"for",
"child",
"in",
"module",
".",
"children",
":",
"child",
".",
"parent",
"=",
"module",
"module",
".",
"future_imports",
"=",
"self",
".",
"future_imports",
"self",
".",
"log",
".",
"debug",
"(",
"\"finished parsing module.\"",
")",
"return",
"module"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
Parser.check_current
|
Verify the current token is of type `kind` and equals `value`.
|
flake8_rst_docstrings.py
|
def check_current(self, kind=None, value=None):
"""Verify the current token is of type `kind` and equals `value`."""
msg = textwrap.dedent(
"""
Unexpected token at line {self.line}:
In file: {self.filename}
Got kind {self.current.kind!r}
Got value {self.current.value}
""".format(
self=self
)
)
kind_valid = self.current.kind == kind if kind else True
value_valid = self.current.value == value if value else True
assert kind_valid and value_valid, msg
|
def check_current(self, kind=None, value=None):
"""Verify the current token is of type `kind` and equals `value`."""
msg = textwrap.dedent(
"""
Unexpected token at line {self.line}:
In file: {self.filename}
Got kind {self.current.kind!r}
Got value {self.current.value}
""".format(
self=self
)
)
kind_valid = self.current.kind == kind if kind else True
value_valid = self.current.value == value if value else True
assert kind_valid and value_valid, msg
|
[
"Verify",
"the",
"current",
"token",
"is",
"of",
"type",
"kind",
"and",
"equals",
"value",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L865-L879
|
[
"def",
"check_current",
"(",
"self",
",",
"kind",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"msg",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n Unexpected token at line {self.line}:\n In file: {self.filename}\n Got kind {self.current.kind!r}\n Got value {self.current.value}\n \"\"\"",
".",
"format",
"(",
"self",
"=",
"self",
")",
")",
"kind_valid",
"=",
"self",
".",
"current",
".",
"kind",
"==",
"kind",
"if",
"kind",
"else",
"True",
"value_valid",
"=",
"self",
".",
"current",
".",
"value",
"==",
"value",
"if",
"value",
"else",
"True",
"assert",
"kind_valid",
"and",
"value_valid",
",",
"msg"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
Parser.parse_from_import_statement
|
Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
|
flake8_rst_docstrings.py
|
def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug("parsing from/import statement.")
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_import)
|
def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug("parsing from/import statement.")
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_import)
|
[
"Parse",
"a",
"from",
"x",
"import",
"y",
"statement",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L881-L888
|
[
"def",
"parse_from_import_statement",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"parsing from/import statement.\"",
")",
"is_future_import",
"=",
"self",
".",
"_parse_from_import_source",
"(",
")",
"self",
".",
"_parse_from_import_names",
"(",
"is_future_import",
")"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
Parser._parse_from_import_names
|
Parse the 'y' part in a 'from x import y' statement.
|
flake8_rst_docstrings.py
|
def _parse_from_import_names(self, is_future_import):
"""Parse the 'y' part in a 'from x import y' statement."""
if self.current.value == "(":
self.consume(tk.OP)
expected_end_kinds = (tk.OP,)
else:
expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)
while self.current.kind not in expected_end_kinds and not (
self.current.kind == tk.OP and self.current.value == ";"
):
if self.current.kind != tk.NAME:
self.stream.move()
continue
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if is_future_import:
self.log.debug("found future import: %s", self.current.value)
self.future_imports.add(self.current.value)
self.consume(tk.NAME)
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if self.current.kind == tk.NAME and self.current.value == "as":
self.consume(tk.NAME) # as
if self.current.kind == tk.NAME:
self.consume(tk.NAME) # new name, irrelevant
if self.current.value == ",":
self.consume(tk.OP)
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
|
def _parse_from_import_names(self, is_future_import):
"""Parse the 'y' part in a 'from x import y' statement."""
if self.current.value == "(":
self.consume(tk.OP)
expected_end_kinds = (tk.OP,)
else:
expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)
while self.current.kind not in expected_end_kinds and not (
self.current.kind == tk.OP and self.current.value == ";"
):
if self.current.kind != tk.NAME:
self.stream.move()
continue
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if is_future_import:
self.log.debug("found future import: %s", self.current.value)
self.future_imports.add(self.current.value)
self.consume(tk.NAME)
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if self.current.kind == tk.NAME and self.current.value == "as":
self.consume(tk.NAME) # as
if self.current.kind == tk.NAME:
self.consume(tk.NAME) # new name, irrelevant
if self.current.value == ",":
self.consume(tk.OP)
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
|
[
"Parse",
"the",
"y",
"part",
"in",
"a",
"from",
"x",
"import",
"y",
"statement",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L912-L949
|
[
"def",
"_parse_from_import_names",
"(",
"self",
",",
"is_future_import",
")",
":",
"if",
"self",
".",
"current",
".",
"value",
"==",
"\"(\"",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"OP",
")",
"expected_end_kinds",
"=",
"(",
"tk",
".",
"OP",
",",
")",
"else",
":",
"expected_end_kinds",
"=",
"(",
"tk",
".",
"NEWLINE",
",",
"tk",
".",
"ENDMARKER",
")",
"while",
"self",
".",
"current",
".",
"kind",
"not",
"in",
"expected_end_kinds",
"and",
"not",
"(",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"OP",
"and",
"self",
".",
"current",
".",
"value",
"==",
"\";\"",
")",
":",
"if",
"self",
".",
"current",
".",
"kind",
"!=",
"tk",
".",
"NAME",
":",
"self",
".",
"stream",
".",
"move",
"(",
")",
"continue",
"self",
".",
"log",
".",
"debug",
"(",
"\"parsing import, token is %r (%s)\"",
",",
"self",
".",
"current",
".",
"kind",
",",
"self",
".",
"current",
".",
"value",
",",
")",
"if",
"is_future_import",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"found future import: %s\"",
",",
"self",
".",
"current",
".",
"value",
")",
"self",
".",
"future_imports",
".",
"add",
"(",
"self",
".",
"current",
".",
"value",
")",
"self",
".",
"consume",
"(",
"tk",
".",
"NAME",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"parsing import, token is %r (%s)\"",
",",
"self",
".",
"current",
".",
"kind",
",",
"self",
".",
"current",
".",
"value",
",",
")",
"if",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"NAME",
"and",
"self",
".",
"current",
".",
"value",
"==",
"\"as\"",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"NAME",
")",
"# as",
"if",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"NAME",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"NAME",
")",
"# new name, irrelevant",
"if",
"self",
".",
"current",
".",
"value",
"==",
"\",\"",
":",
"self",
".",
"consume",
"(",
"tk",
".",
"OP",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"parsing import, token is %r (%s)\"",
",",
"self",
".",
"current",
".",
"kind",
",",
"self",
".",
"current",
".",
"value",
",",
")"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
reStructuredTextChecker.run
|
Use docutils to check docstrings are valid RST.
|
flake8_rst_docstrings.py
|
def run(self):
"""Use docutils to check docstrings are valid RST."""
# Is there any reason not to call load_source here?
if self.err is not None:
assert self.source is None
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_load,
"Failed to load file: %s" % self.err,
)
yield 0, 0, msg, type(self)
module = []
try:
module = parse(StringIO(self.source), self.filename)
except SyntaxError as err:
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_parse,
"Failed to parse file: %s" % err,
)
yield 0, 0, msg, type(self)
module = []
except AllError:
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_all,
"Failed to parse __all__ entry.",
)
yield 0, 0, msg, type(self)
module = []
for definition in module:
if not definition.docstring:
# People can use flake8-docstrings to report missing
# docstrings
continue
try:
# Note we use the PEP257 trim algorithm to remove the
# leading whitespace from each line - this avoids false
# positive severe error "Unexpected section title."
unindented = trim(dequote_docstring(definition.docstring))
# Off load RST validation to reStructuredText-lint
# which calls docutils internally.
# TODO: Should we pass the Python filename as filepath?
rst_errors = list(rst_lint.lint(unindented))
except Exception as err:
# e.g. UnicodeDecodeError
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_lint,
"Failed to lint docstring: %s - %s" % (definition.name, err),
)
yield definition.start, 0, msg, type(self)
continue
for rst_error in rst_errors:
# TODO - make this a configuration option?
if rst_error.level <= 1:
continue
# Levels:
#
# 0 - debug --> we don't receive these
# 1 - info --> RST1## codes
# 2 - warning --> RST2## codes
# 3 - error --> RST3## codes
# 4 - severe --> RST4## codes
#
# Map the string to a unique code:
msg = rst_error.message.split("\n", 1)[0]
code = code_mapping(rst_error.level, msg)
assert code < 100, code
code += 100 * rst_error.level
msg = "%s%03i %s" % (rst_prefix, code, msg)
# This will return the line number by combining the
# start of the docstring with the offet within it.
# We don't know the column number, leaving as zero.
yield definition.start + rst_error.line, 0, msg, type(self)
|
def run(self):
"""Use docutils to check docstrings are valid RST."""
# Is there any reason not to call load_source here?
if self.err is not None:
assert self.source is None
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_load,
"Failed to load file: %s" % self.err,
)
yield 0, 0, msg, type(self)
module = []
try:
module = parse(StringIO(self.source), self.filename)
except SyntaxError as err:
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_parse,
"Failed to parse file: %s" % err,
)
yield 0, 0, msg, type(self)
module = []
except AllError:
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_all,
"Failed to parse __all__ entry.",
)
yield 0, 0, msg, type(self)
module = []
for definition in module:
if not definition.docstring:
# People can use flake8-docstrings to report missing
# docstrings
continue
try:
# Note we use the PEP257 trim algorithm to remove the
# leading whitespace from each line - this avoids false
# positive severe error "Unexpected section title."
unindented = trim(dequote_docstring(definition.docstring))
# Off load RST validation to reStructuredText-lint
# which calls docutils internally.
# TODO: Should we pass the Python filename as filepath?
rst_errors = list(rst_lint.lint(unindented))
except Exception as err:
# e.g. UnicodeDecodeError
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_lint,
"Failed to lint docstring: %s - %s" % (definition.name, err),
)
yield definition.start, 0, msg, type(self)
continue
for rst_error in rst_errors:
# TODO - make this a configuration option?
if rst_error.level <= 1:
continue
# Levels:
#
# 0 - debug --> we don't receive these
# 1 - info --> RST1## codes
# 2 - warning --> RST2## codes
# 3 - error --> RST3## codes
# 4 - severe --> RST4## codes
#
# Map the string to a unique code:
msg = rst_error.message.split("\n", 1)[0]
code = code_mapping(rst_error.level, msg)
assert code < 100, code
code += 100 * rst_error.level
msg = "%s%03i %s" % (rst_prefix, code, msg)
# This will return the line number by combining the
# start of the docstring with the offet within it.
# We don't know the column number, leaving as zero.
yield definition.start + rst_error.line, 0, msg, type(self)
|
[
"Use",
"docutils",
"to",
"check",
"docstrings",
"are",
"valid",
"RST",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L979-L1054
|
[
"def",
"run",
"(",
"self",
")",
":",
"# Is there any reason not to call load_source here?",
"if",
"self",
".",
"err",
"is",
"not",
"None",
":",
"assert",
"self",
".",
"source",
"is",
"None",
"msg",
"=",
"\"%s%03i %s\"",
"%",
"(",
"rst_prefix",
",",
"rst_fail_load",
",",
"\"Failed to load file: %s\"",
"%",
"self",
".",
"err",
",",
")",
"yield",
"0",
",",
"0",
",",
"msg",
",",
"type",
"(",
"self",
")",
"module",
"=",
"[",
"]",
"try",
":",
"module",
"=",
"parse",
"(",
"StringIO",
"(",
"self",
".",
"source",
")",
",",
"self",
".",
"filename",
")",
"except",
"SyntaxError",
"as",
"err",
":",
"msg",
"=",
"\"%s%03i %s\"",
"%",
"(",
"rst_prefix",
",",
"rst_fail_parse",
",",
"\"Failed to parse file: %s\"",
"%",
"err",
",",
")",
"yield",
"0",
",",
"0",
",",
"msg",
",",
"type",
"(",
"self",
")",
"module",
"=",
"[",
"]",
"except",
"AllError",
":",
"msg",
"=",
"\"%s%03i %s\"",
"%",
"(",
"rst_prefix",
",",
"rst_fail_all",
",",
"\"Failed to parse __all__ entry.\"",
",",
")",
"yield",
"0",
",",
"0",
",",
"msg",
",",
"type",
"(",
"self",
")",
"module",
"=",
"[",
"]",
"for",
"definition",
"in",
"module",
":",
"if",
"not",
"definition",
".",
"docstring",
":",
"# People can use flake8-docstrings to report missing",
"# docstrings",
"continue",
"try",
":",
"# Note we use the PEP257 trim algorithm to remove the",
"# leading whitespace from each line - this avoids false",
"# positive severe error \"Unexpected section title.\"",
"unindented",
"=",
"trim",
"(",
"dequote_docstring",
"(",
"definition",
".",
"docstring",
")",
")",
"# Off load RST validation to reStructuredText-lint",
"# which calls docutils internally.",
"# TODO: Should we pass the Python filename as filepath?",
"rst_errors",
"=",
"list",
"(",
"rst_lint",
".",
"lint",
"(",
"unindented",
")",
")",
"except",
"Exception",
"as",
"err",
":",
"# e.g. UnicodeDecodeError",
"msg",
"=",
"\"%s%03i %s\"",
"%",
"(",
"rst_prefix",
",",
"rst_fail_lint",
",",
"\"Failed to lint docstring: %s - %s\"",
"%",
"(",
"definition",
".",
"name",
",",
"err",
")",
",",
")",
"yield",
"definition",
".",
"start",
",",
"0",
",",
"msg",
",",
"type",
"(",
"self",
")",
"continue",
"for",
"rst_error",
"in",
"rst_errors",
":",
"# TODO - make this a configuration option?",
"if",
"rst_error",
".",
"level",
"<=",
"1",
":",
"continue",
"# Levels:",
"#",
"# 0 - debug --> we don't receive these",
"# 1 - info --> RST1## codes",
"# 2 - warning --> RST2## codes",
"# 3 - error --> RST3## codes",
"# 4 - severe --> RST4## codes",
"#",
"# Map the string to a unique code:",
"msg",
"=",
"rst_error",
".",
"message",
".",
"split",
"(",
"\"\\n\"",
",",
"1",
")",
"[",
"0",
"]",
"code",
"=",
"code_mapping",
"(",
"rst_error",
".",
"level",
",",
"msg",
")",
"assert",
"code",
"<",
"100",
",",
"code",
"code",
"+=",
"100",
"*",
"rst_error",
".",
"level",
"msg",
"=",
"\"%s%03i %s\"",
"%",
"(",
"rst_prefix",
",",
"code",
",",
"msg",
")",
"# This will return the line number by combining the",
"# start of the docstring with the offet within it.",
"# We don't know the column number, leaving as zero.",
"yield",
"definition",
".",
"start",
"+",
"rst_error",
".",
"line",
",",
"0",
",",
"msg",
",",
"type",
"(",
"self",
")"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
reStructuredTextChecker.load_source
|
Load the source for the specified file.
|
flake8_rst_docstrings.py
|
def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = "stdin"
if sys.version_info[0] < 3:
self.source = sys.stdin.read()
else:
self.source = TextIOWrapper(sys.stdin.buffer, errors="ignore").read()
else:
# Could be a Python 2.7 StringIO with no context manager, sigh.
# with tokenize_open(self.filename) as fd:
# self.source = fd.read()
handle = tokenize_open(self.filename)
self.source = handle.read()
handle.close()
|
def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = "stdin"
if sys.version_info[0] < 3:
self.source = sys.stdin.read()
else:
self.source = TextIOWrapper(sys.stdin.buffer, errors="ignore").read()
else:
# Could be a Python 2.7 StringIO with no context manager, sigh.
# with tokenize_open(self.filename) as fd:
# self.source = fd.read()
handle = tokenize_open(self.filename)
self.source = handle.read()
handle.close()
|
[
"Load",
"the",
"source",
"for",
"the",
"specified",
"file",
"."
] |
peterjc/flake8-rst-docstrings
|
python
|
https://github.com/peterjc/flake8-rst-docstrings/blob/b8b17d0317fc6728d5586553ab29a7d97e6417fd/flake8_rst_docstrings.py#L1056-L1070
|
[
"def",
"load_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
"in",
"self",
".",
"STDIN_NAMES",
":",
"self",
".",
"filename",
"=",
"\"stdin\"",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"self",
".",
"source",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"else",
":",
"self",
".",
"source",
"=",
"TextIOWrapper",
"(",
"sys",
".",
"stdin",
".",
"buffer",
",",
"errors",
"=",
"\"ignore\"",
")",
".",
"read",
"(",
")",
"else",
":",
"# Could be a Python 2.7 StringIO with no context manager, sigh.",
"# with tokenize_open(self.filename) as fd:",
"# self.source = fd.read()",
"handle",
"=",
"tokenize_open",
"(",
"self",
".",
"filename",
")",
"self",
".",
"source",
"=",
"handle",
".",
"read",
"(",
")",
"handle",
".",
"close",
"(",
")"
] |
b8b17d0317fc6728d5586553ab29a7d97e6417fd
|
valid
|
lab_to_rgb
|
Converts CIE Lab to RGB components.
First we have to convert to XYZ color space.
Conversion involves using a white point,
in this case D65 which represents daylight illumination.
Algorithms adopted from:
http://www.easyrgb.com/math.php
|
lib/web/kuler.py
|
def lab_to_rgb(l, a, b):
""" Converts CIE Lab to RGB components.
First we have to convert to XYZ color space.
Conversion involves using a white point,
in this case D65 which represents daylight illumination.
Algorithms adopted from:
http://www.easyrgb.com/math.php
"""
y = (l+16) / 116.0
x = a/500.0 + y
z = y - b/200.0
v = [x,y,z]
for i in range(3):
if pow(v[i],3) > 0.008856:
v[i] = pow(v[i],3)
else:
v[i] = (v[i]-16/116.0) / 7.787
# Observer = 2, Illuminant = D65
x = v[0] * 95.047/100
y = v[1] * 100.0/100
z = v[2] * 108.883/100
r = x * 3.2406 + y *-1.5372 + z *-0.4986
g = x *-0.9689 + y * 1.8758 + z * 0.0415
b = x * 0.0557 + y *-0.2040 + z * 1.0570
v = [r,g,b]
for i in range(3):
if v[i] > 0.0031308:
v[i] = 1.055 * pow(v[i], 1/2.4) - 0.055
else:
v[i] = 12.92 * v[i]
#r, g, b = v[0]*255, v[1]*255, v[2]*255
r, g, b = v[0], v[1], v[2]
return r, g, b
|
def lab_to_rgb(l, a, b):
""" Converts CIE Lab to RGB components.
First we have to convert to XYZ color space.
Conversion involves using a white point,
in this case D65 which represents daylight illumination.
Algorithms adopted from:
http://www.easyrgb.com/math.php
"""
y = (l+16) / 116.0
x = a/500.0 + y
z = y - b/200.0
v = [x,y,z]
for i in range(3):
if pow(v[i],3) > 0.008856:
v[i] = pow(v[i],3)
else:
v[i] = (v[i]-16/116.0) / 7.787
# Observer = 2, Illuminant = D65
x = v[0] * 95.047/100
y = v[1] * 100.0/100
z = v[2] * 108.883/100
r = x * 3.2406 + y *-1.5372 + z *-0.4986
g = x *-0.9689 + y * 1.8758 + z * 0.0415
b = x * 0.0557 + y *-0.2040 + z * 1.0570
v = [r,g,b]
for i in range(3):
if v[i] > 0.0031308:
v[i] = 1.055 * pow(v[i], 1/2.4) - 0.055
else:
v[i] = 12.92 * v[i]
#r, g, b = v[0]*255, v[1]*255, v[2]*255
r, g, b = v[0], v[1], v[2]
return r, g, b
|
[
"Converts",
"CIE",
"Lab",
"to",
"RGB",
"components",
".",
"First",
"we",
"have",
"to",
"convert",
"to",
"XYZ",
"color",
"space",
".",
"Conversion",
"involves",
"using",
"a",
"white",
"point",
"in",
"this",
"case",
"D65",
"which",
"represents",
"daylight",
"illumination",
".",
"Algorithms",
"adopted",
"from",
":",
"http",
":",
"//",
"www",
".",
"easyrgb",
".",
"com",
"/",
"math",
".",
"php"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/kuler.py#L31-L71
|
[
"def",
"lab_to_rgb",
"(",
"l",
",",
"a",
",",
"b",
")",
":",
"y",
"=",
"(",
"l",
"+",
"16",
")",
"/",
"116.0",
"x",
"=",
"a",
"/",
"500.0",
"+",
"y",
"z",
"=",
"y",
"-",
"b",
"/",
"200.0",
"v",
"=",
"[",
"x",
",",
"y",
",",
"z",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"if",
"pow",
"(",
"v",
"[",
"i",
"]",
",",
"3",
")",
">",
"0.008856",
":",
"v",
"[",
"i",
"]",
"=",
"pow",
"(",
"v",
"[",
"i",
"]",
",",
"3",
")",
"else",
":",
"v",
"[",
"i",
"]",
"=",
"(",
"v",
"[",
"i",
"]",
"-",
"16",
"/",
"116.0",
")",
"/",
"7.787",
"# Observer = 2, Illuminant = D65",
"x",
"=",
"v",
"[",
"0",
"]",
"*",
"95.047",
"/",
"100",
"y",
"=",
"v",
"[",
"1",
"]",
"*",
"100.0",
"/",
"100",
"z",
"=",
"v",
"[",
"2",
"]",
"*",
"108.883",
"/",
"100",
"r",
"=",
"x",
"*",
"3.2406",
"+",
"y",
"*",
"-",
"1.5372",
"+",
"z",
"*",
"-",
"0.4986",
"g",
"=",
"x",
"*",
"-",
"0.9689",
"+",
"y",
"*",
"1.8758",
"+",
"z",
"*",
"0.0415",
"b",
"=",
"x",
"*",
"0.0557",
"+",
"y",
"*",
"-",
"0.2040",
"+",
"z",
"*",
"1.0570",
"v",
"=",
"[",
"r",
",",
"g",
",",
"b",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"if",
"v",
"[",
"i",
"]",
">",
"0.0031308",
":",
"v",
"[",
"i",
"]",
"=",
"1.055",
"*",
"pow",
"(",
"v",
"[",
"i",
"]",
",",
"1",
"/",
"2.4",
")",
"-",
"0.055",
"else",
":",
"v",
"[",
"i",
"]",
"=",
"12.92",
"*",
"v",
"[",
"i",
"]",
"#r, g, b = v[0]*255, v[1]*255, v[2]*255",
"r",
",",
"g",
",",
"b",
"=",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
",",
"v",
"[",
"2",
"]",
"return",
"r",
",",
"g",
",",
"b"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KulerTheme._darkest
|
Returns the darkest swatch.
Knowing the contract between a light and a dark swatch
can help us decide how to display readable typography.
|
lib/web/kuler.py
|
def _darkest(self):
""" Returns the darkest swatch.
Knowing the contract between a light and a dark swatch
can help us decide how to display readable typography.
"""
rgb, n = (1.0, 1.0, 1.0), 3.0
for r,g,b in self:
if r+g+b < n:
rgb, n = (r,g,b), r+g+b
return rgb
|
def _darkest(self):
""" Returns the darkest swatch.
Knowing the contract between a light and a dark swatch
can help us decide how to display readable typography.
"""
rgb, n = (1.0, 1.0, 1.0), 3.0
for r,g,b in self:
if r+g+b < n:
rgb, n = (r,g,b), r+g+b
return rgb
|
[
"Returns",
"the",
"darkest",
"swatch",
".",
"Knowing",
"the",
"contract",
"between",
"a",
"light",
"and",
"a",
"dark",
"swatch",
"can",
"help",
"us",
"decide",
"how",
"to",
"display",
"readable",
"typography",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/kuler.py#L84-L98
|
[
"def",
"_darkest",
"(",
"self",
")",
":",
"rgb",
",",
"n",
"=",
"(",
"1.0",
",",
"1.0",
",",
"1.0",
")",
",",
"3.0",
"for",
"r",
",",
"g",
",",
"b",
"in",
"self",
":",
"if",
"r",
"+",
"g",
"+",
"b",
"<",
"n",
":",
"rgb",
",",
"n",
"=",
"(",
"r",
",",
"g",
",",
"b",
")",
",",
"r",
"+",
"g",
"+",
"b",
"return",
"rgb"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
Kuler.parse_theme
|
Parses a theme from XML returned by Kuler.
Gets the theme's id, label and swatches.
All of the swatches are converted to RGB.
If we have a full description for a theme id in cache,
parse that to get tags associated with the theme.
|
lib/web/kuler.py
|
def parse_theme(self, xml):
""" Parses a theme from XML returned by Kuler.
Gets the theme's id, label and swatches.
All of the swatches are converted to RGB.
If we have a full description for a theme id in cache,
parse that to get tags associated with the theme.
"""
kt = KulerTheme()
kt.author = xml.getElementsByTagName("author")[0]
kt.author = kt.author.childNodes[1].childNodes[0].nodeValue
kt.id = int(self.parse_tag(xml, "id"))
kt.label = self.parse_tag(xml, "label")
mode = self.parse_tag(xml, "mode")
for swatch in xml.getElementsByTagName("swatch"):
c1 = float(self.parse_tag(swatch, "c1"))
c2 = float(self.parse_tag(swatch, "c2"))
c3 = float(self.parse_tag(swatch, "c3"))
c4 = float(self.parse_tag(swatch, "c4"))
if mode == "rgb":
kt.append((c1,c2,c3))
if mode == "cmyk":
kt.append(cmyk_to_rgb(c1,c2,c3,c4))
if mode == "hsv":
kt.append(colorsys.hsv_to_rgb(c1,c2,c3))
if mode == "hex":
kt.append(hex_to_rgb(c1))
if mode == "lab":
kt.append(lab_to_rgb(c1,c2,c3))
# If we have the full theme in cache,
# parse tags from it.
if self._cache.exists(self.id_string + str(kt.id)):
xml = self._cache.read(self.id_string + str(kt.id))
xml = minidom.parseString(xml)
for tags in xml.getElementsByTagName("tag"):
tags = self.parse_tag(tags, "label")
tags = tags.split(" ")
kt.tags.extend(tags)
return kt
|
def parse_theme(self, xml):
""" Parses a theme from XML returned by Kuler.
Gets the theme's id, label and swatches.
All of the swatches are converted to RGB.
If we have a full description for a theme id in cache,
parse that to get tags associated with the theme.
"""
kt = KulerTheme()
kt.author = xml.getElementsByTagName("author")[0]
kt.author = kt.author.childNodes[1].childNodes[0].nodeValue
kt.id = int(self.parse_tag(xml, "id"))
kt.label = self.parse_tag(xml, "label")
mode = self.parse_tag(xml, "mode")
for swatch in xml.getElementsByTagName("swatch"):
c1 = float(self.parse_tag(swatch, "c1"))
c2 = float(self.parse_tag(swatch, "c2"))
c3 = float(self.parse_tag(swatch, "c3"))
c4 = float(self.parse_tag(swatch, "c4"))
if mode == "rgb":
kt.append((c1,c2,c3))
if mode == "cmyk":
kt.append(cmyk_to_rgb(c1,c2,c3,c4))
if mode == "hsv":
kt.append(colorsys.hsv_to_rgb(c1,c2,c3))
if mode == "hex":
kt.append(hex_to_rgb(c1))
if mode == "lab":
kt.append(lab_to_rgb(c1,c2,c3))
# If we have the full theme in cache,
# parse tags from it.
if self._cache.exists(self.id_string + str(kt.id)):
xml = self._cache.read(self.id_string + str(kt.id))
xml = minidom.parseString(xml)
for tags in xml.getElementsByTagName("tag"):
tags = self.parse_tag(tags, "label")
tags = tags.split(" ")
kt.tags.extend(tags)
return kt
|
[
"Parses",
"a",
"theme",
"from",
"XML",
"returned",
"by",
"Kuler",
".",
"Gets",
"the",
"theme",
"s",
"id",
"label",
"and",
"swatches",
".",
"All",
"of",
"the",
"swatches",
"are",
"converted",
"to",
"RGB",
".",
"If",
"we",
"have",
"a",
"full",
"description",
"for",
"a",
"theme",
"id",
"in",
"cache",
"parse",
"that",
"to",
"get",
"tags",
"associated",
"with",
"the",
"theme",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/kuler.py#L181-L227
|
[
"def",
"parse_theme",
"(",
"self",
",",
"xml",
")",
":",
"kt",
"=",
"KulerTheme",
"(",
")",
"kt",
".",
"author",
"=",
"xml",
".",
"getElementsByTagName",
"(",
"\"author\"",
")",
"[",
"0",
"]",
"kt",
".",
"author",
"=",
"kt",
".",
"author",
".",
"childNodes",
"[",
"1",
"]",
".",
"childNodes",
"[",
"0",
"]",
".",
"nodeValue",
"kt",
".",
"id",
"=",
"int",
"(",
"self",
".",
"parse_tag",
"(",
"xml",
",",
"\"id\"",
")",
")",
"kt",
".",
"label",
"=",
"self",
".",
"parse_tag",
"(",
"xml",
",",
"\"label\"",
")",
"mode",
"=",
"self",
".",
"parse_tag",
"(",
"xml",
",",
"\"mode\"",
")",
"for",
"swatch",
"in",
"xml",
".",
"getElementsByTagName",
"(",
"\"swatch\"",
")",
":",
"c1",
"=",
"float",
"(",
"self",
".",
"parse_tag",
"(",
"swatch",
",",
"\"c1\"",
")",
")",
"c2",
"=",
"float",
"(",
"self",
".",
"parse_tag",
"(",
"swatch",
",",
"\"c2\"",
")",
")",
"c3",
"=",
"float",
"(",
"self",
".",
"parse_tag",
"(",
"swatch",
",",
"\"c3\"",
")",
")",
"c4",
"=",
"float",
"(",
"self",
".",
"parse_tag",
"(",
"swatch",
",",
"\"c4\"",
")",
")",
"if",
"mode",
"==",
"\"rgb\"",
":",
"kt",
".",
"append",
"(",
"(",
"c1",
",",
"c2",
",",
"c3",
")",
")",
"if",
"mode",
"==",
"\"cmyk\"",
":",
"kt",
".",
"append",
"(",
"cmyk_to_rgb",
"(",
"c1",
",",
"c2",
",",
"c3",
",",
"c4",
")",
")",
"if",
"mode",
"==",
"\"hsv\"",
":",
"kt",
".",
"append",
"(",
"colorsys",
".",
"hsv_to_rgb",
"(",
"c1",
",",
"c2",
",",
"c3",
")",
")",
"if",
"mode",
"==",
"\"hex\"",
":",
"kt",
".",
"append",
"(",
"hex_to_rgb",
"(",
"c1",
")",
")",
"if",
"mode",
"==",
"\"lab\"",
":",
"kt",
".",
"append",
"(",
"lab_to_rgb",
"(",
"c1",
",",
"c2",
",",
"c3",
")",
")",
"# If we have the full theme in cache,",
"# parse tags from it.",
"if",
"self",
".",
"_cache",
".",
"exists",
"(",
"self",
".",
"id_string",
"+",
"str",
"(",
"kt",
".",
"id",
")",
")",
":",
"xml",
"=",
"self",
".",
"_cache",
".",
"read",
"(",
"self",
".",
"id_string",
"+",
"str",
"(",
"kt",
".",
"id",
")",
")",
"xml",
"=",
"minidom",
".",
"parseString",
"(",
"xml",
")",
"for",
"tags",
"in",
"xml",
".",
"getElementsByTagName",
"(",
"\"tag\"",
")",
":",
"tags",
"=",
"self",
".",
"parse_tag",
"(",
"tags",
",",
"\"label\"",
")",
"tags",
"=",
"tags",
".",
"split",
"(",
"\" \"",
")",
"kt",
".",
"tags",
".",
"extend",
"(",
"tags",
")",
"return",
"kt"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
create_listening_socket
|
Create socket and set listening options
:param host:
:param port:
:param handler:
:return:
|
shoebot/sbio/socket_server.py
|
def create_listening_socket(host, port, handler):
"""
Create socket and set listening options
:param host:
:param port:
:param handler:
:return:
"""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(1)
GObject.io_add_watch(sock, GObject.IO_IN, handler)
return sock
|
def create_listening_socket(host, port, handler):
"""
Create socket and set listening options
:param host:
:param port:
:param handler:
:return:
"""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(1)
GObject.io_add_watch(sock, GObject.IO_IN, handler)
return sock
|
[
"Create",
"socket",
"and",
"set",
"listening",
"options",
":",
"param",
"host",
":",
":",
"param",
"port",
":",
":",
"param",
"handler",
":",
":",
"return",
":"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/socket_server.py#L56-L71
|
[
"def",
"create_listening_socket",
"(",
"host",
",",
"port",
",",
"handler",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
")",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"sock",
".",
"bind",
"(",
"(",
"host",
",",
"port",
")",
")",
"sock",
".",
"listen",
"(",
"1",
")",
"GObject",
".",
"io_add_watch",
"(",
"sock",
",",
"GObject",
".",
"IO_IN",
",",
"handler",
")",
"return",
"sock"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
SocketServer.listener
|
Asynchronous connection listener. Starts a handler for each connection.
|
shoebot/sbio/socket_server.py
|
def listener(self, sock, *args):
'''Asynchronous connection listener. Starts a handler for each connection.'''
conn, addr = sock.accept()
f = conn.makefile(conn)
self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)
print(_("Connected"))
GObject.io_add_watch(conn, GObject.IO_IN, self.handler)
if self.shell.intro:
self.shell.stdout.write(str(self.shell.intro)+"\n")
self.shell.stdout.flush()
return True
|
def listener(self, sock, *args):
'''Asynchronous connection listener. Starts a handler for each connection.'''
conn, addr = sock.accept()
f = conn.makefile(conn)
self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)
print(_("Connected"))
GObject.io_add_watch(conn, GObject.IO_IN, self.handler)
if self.shell.intro:
self.shell.stdout.write(str(self.shell.intro)+"\n")
self.shell.stdout.flush()
return True
|
[
"Asynchronous",
"connection",
"listener",
".",
"Starts",
"a",
"handler",
"for",
"each",
"connection",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/socket_server.py#L80-L91
|
[
"def",
"listener",
"(",
"self",
",",
"sock",
",",
"*",
"args",
")",
":",
"conn",
",",
"addr",
"=",
"sock",
".",
"accept",
"(",
")",
"f",
"=",
"conn",
".",
"makefile",
"(",
"conn",
")",
"self",
".",
"shell",
"=",
"ShoebotCmd",
"(",
"self",
".",
"bot",
",",
"stdin",
"=",
"f",
",",
"stdout",
"=",
"f",
",",
"intro",
"=",
"INTRO",
")",
"print",
"(",
"_",
"(",
"\"Connected\"",
")",
")",
"GObject",
".",
"io_add_watch",
"(",
"conn",
",",
"GObject",
".",
"IO_IN",
",",
"self",
".",
"handler",
")",
"if",
"self",
".",
"shell",
".",
"intro",
":",
"self",
".",
"shell",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"self",
".",
"shell",
".",
"intro",
")",
"+",
"\"\\n\"",
")",
"self",
".",
"shell",
".",
"stdout",
".",
"flush",
"(",
")",
"return",
"True"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
SocketServer.handler
|
Asynchronous connection handler. Processes each line from the socket.
|
shoebot/sbio/socket_server.py
|
def handler(self, conn, *args):
'''
Asynchronous connection handler. Processes each line from the socket.
'''
# lines from cmd.Cmd
self.shell.stdout.write(self.shell.prompt)
line = self.shell.stdin.readline()
if not len(line):
line = 'EOF'
return False
else:
line = line.rstrip('\r\n')
line = self.shell.precmd(line)
stop = self.shell.onecmd(line)
stop = self.shell.postcmd(stop, line)
self.shell.stdout.flush()
self.shell.postloop()
# end lines from cmd.Cmd
if stop:
self.shell = None
conn.close()
return not stop
|
def handler(self, conn, *args):
'''
Asynchronous connection handler. Processes each line from the socket.
'''
# lines from cmd.Cmd
self.shell.stdout.write(self.shell.prompt)
line = self.shell.stdin.readline()
if not len(line):
line = 'EOF'
return False
else:
line = line.rstrip('\r\n')
line = self.shell.precmd(line)
stop = self.shell.onecmd(line)
stop = self.shell.postcmd(stop, line)
self.shell.stdout.flush()
self.shell.postloop()
# end lines from cmd.Cmd
if stop:
self.shell = None
conn.close()
return not stop
|
[
"Asynchronous",
"connection",
"handler",
".",
"Processes",
"each",
"line",
"from",
"the",
"socket",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/socket_server.py#L93-L114
|
[
"def",
"handler",
"(",
"self",
",",
"conn",
",",
"*",
"args",
")",
":",
"# lines from cmd.Cmd",
"self",
".",
"shell",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"shell",
".",
"prompt",
")",
"line",
"=",
"self",
".",
"shell",
".",
"stdin",
".",
"readline",
"(",
")",
"if",
"not",
"len",
"(",
"line",
")",
":",
"line",
"=",
"'EOF'",
"return",
"False",
"else",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"line",
"=",
"self",
".",
"shell",
".",
"precmd",
"(",
"line",
")",
"stop",
"=",
"self",
".",
"shell",
".",
"onecmd",
"(",
"line",
")",
"stop",
"=",
"self",
".",
"shell",
".",
"postcmd",
"(",
"stop",
",",
"line",
")",
"self",
".",
"shell",
".",
"stdout",
".",
"flush",
"(",
")",
"self",
".",
"shell",
".",
"postloop",
"(",
")",
"# end lines from cmd.Cmd",
"if",
"stop",
":",
"self",
".",
"shell",
"=",
"None",
"conn",
".",
"close",
"(",
")",
"return",
"not",
"stop"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
trusted_cmd
|
Trusted commands cannot be run remotely
:param f:
:return:
|
shoebot/sbio/shell.py
|
def trusted_cmd(f):
"""
Trusted commands cannot be run remotely
:param f:
:return:
"""
def run_cmd(self, line):
if self.trusted:
f(self, line)
else:
print("Sorry cannot do %s here." % f.__name__[3:])
global trusted_cmds
trusted_cmds.add(f.__name__)
run_cmd.__doc__ = f.__doc__
return run_cmd
|
def trusted_cmd(f):
"""
Trusted commands cannot be run remotely
:param f:
:return:
"""
def run_cmd(self, line):
if self.trusted:
f(self, line)
else:
print("Sorry cannot do %s here." % f.__name__[3:])
global trusted_cmds
trusted_cmds.add(f.__name__)
run_cmd.__doc__ = f.__doc__
return run_cmd
|
[
"Trusted",
"commands",
"cannot",
"be",
"run",
"remotely"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L51-L67
|
[
"def",
"trusted_cmd",
"(",
"f",
")",
":",
"def",
"run_cmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"trusted",
":",
"f",
"(",
"self",
",",
"line",
")",
"else",
":",
"print",
"(",
"\"Sorry cannot do %s here.\"",
"%",
"f",
".",
"__name__",
"[",
"3",
":",
"]",
")",
"global",
"trusted_cmds",
"trusted_cmds",
".",
"add",
"(",
"f",
".",
"__name__",
")",
"run_cmd",
".",
"__doc__",
"=",
"f",
".",
"__doc__",
"return",
"run_cmd"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.print_response
|
print response, if cookie is set then print that each line
:param args:
:param keep: if True more output is to come
:param cookie: set a custom cookie,
if set to 'None' then self.cookie will be used.
if set to 'False' disables cookie output entirely
:return:
|
shoebot/sbio/shell.py
|
def print_response(self, input='', keep=False, *args, **kwargs):
"""
print response, if cookie is set then print that each line
:param args:
:param keep: if True more output is to come
:param cookie: set a custom cookie,
if set to 'None' then self.cookie will be used.
if set to 'False' disables cookie output entirely
:return:
"""
cookie = kwargs.get('cookie')
if cookie is None:
cookie = self.cookie or ''
status = kwargs.get('status')
lines = input.splitlines()
if status and not lines:
lines = ['']
if cookie:
output_template = '{cookie} {status}{cookie_char}{line}'
else:
output_template = '{line}'
for i, line in enumerate(lines):
if i != len(lines) - 1 or keep is True:
cookie_char = '>'
else:
# last line
cookie_char = ':'
print(output_template.format(
cookie_char=cookie_char,
cookie=cookie,
status=status or '',
line=line.strip()), file=self.stdout)
|
def print_response(self, input='', keep=False, *args, **kwargs):
"""
print response, if cookie is set then print that each line
:param args:
:param keep: if True more output is to come
:param cookie: set a custom cookie,
if set to 'None' then self.cookie will be used.
if set to 'False' disables cookie output entirely
:return:
"""
cookie = kwargs.get('cookie')
if cookie is None:
cookie = self.cookie or ''
status = kwargs.get('status')
lines = input.splitlines()
if status and not lines:
lines = ['']
if cookie:
output_template = '{cookie} {status}{cookie_char}{line}'
else:
output_template = '{line}'
for i, line in enumerate(lines):
if i != len(lines) - 1 or keep is True:
cookie_char = '>'
else:
# last line
cookie_char = ':'
print(output_template.format(
cookie_char=cookie_char,
cookie=cookie,
status=status or '',
line=line.strip()), file=self.stdout)
|
[
"print",
"response",
"if",
"cookie",
"is",
"set",
"then",
"print",
"that",
"each",
"line",
":",
"param",
"args",
":",
":",
"param",
"keep",
":",
"if",
"True",
"more",
"output",
"is",
"to",
"come",
":",
"param",
"cookie",
":",
"set",
"a",
"custom",
"cookie",
"if",
"set",
"to",
"None",
"then",
"self",
".",
"cookie",
"will",
"be",
"used",
".",
"if",
"set",
"to",
"False",
"disables",
"cookie",
"output",
"entirely",
":",
"return",
":"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L108-L142
|
[
"def",
"print_response",
"(",
"self",
",",
"input",
"=",
"''",
",",
"keep",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cookie",
"=",
"kwargs",
".",
"get",
"(",
"'cookie'",
")",
"if",
"cookie",
"is",
"None",
":",
"cookie",
"=",
"self",
".",
"cookie",
"or",
"''",
"status",
"=",
"kwargs",
".",
"get",
"(",
"'status'",
")",
"lines",
"=",
"input",
".",
"splitlines",
"(",
")",
"if",
"status",
"and",
"not",
"lines",
":",
"lines",
"=",
"[",
"''",
"]",
"if",
"cookie",
":",
"output_template",
"=",
"'{cookie} {status}{cookie_char}{line}'",
"else",
":",
"output_template",
"=",
"'{line}'",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"i",
"!=",
"len",
"(",
"lines",
")",
"-",
"1",
"or",
"keep",
"is",
"True",
":",
"cookie_char",
"=",
"'>'",
"else",
":",
"# last line",
"cookie_char",
"=",
"':'",
"print",
"(",
"output_template",
".",
"format",
"(",
"cookie_char",
"=",
"cookie_char",
",",
"cookie",
"=",
"cookie",
",",
"status",
"=",
"status",
"or",
"''",
",",
"line",
"=",
"line",
".",
"strip",
"(",
")",
")",
",",
"file",
"=",
"self",
".",
"stdout",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_escape_nl
|
Escape newlines in any responses
|
shoebot/sbio/shell.py
|
def do_escape_nl(self, arg):
"""
Escape newlines in any responses
"""
if arg.lower() == 'off':
self.escape_nl = False
else:
self.escape_nl = True
|
def do_escape_nl(self, arg):
"""
Escape newlines in any responses
"""
if arg.lower() == 'off':
self.escape_nl = False
else:
self.escape_nl = True
|
[
"Escape",
"newlines",
"in",
"any",
"responses"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L152-L159
|
[
"def",
"do_escape_nl",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
".",
"lower",
"(",
")",
"==",
"'off'",
":",
"self",
".",
"escape_nl",
"=",
"False",
"else",
":",
"self",
".",
"escape_nl",
"=",
"True"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_prompt
|
Enable or disable prompt
:param arg: on|off
:return:
|
shoebot/sbio/shell.py
|
def do_prompt(self, arg):
"""
Enable or disable prompt
:param arg: on|off
:return:
"""
if arg.lower() == 'off':
self.response_prompt = ''
self.prompt = ''
return
elif arg.lower() == 'on':
self.prompt = PROMPT
self.response_prompt = RESPONSE_PROMPT
self.print_response('prompt: %s' % self.prompt, '\n', 'response: %s' % self.response_prompt)
|
def do_prompt(self, arg):
"""
Enable or disable prompt
:param arg: on|off
:return:
"""
if arg.lower() == 'off':
self.response_prompt = ''
self.prompt = ''
return
elif arg.lower() == 'on':
self.prompt = PROMPT
self.response_prompt = RESPONSE_PROMPT
self.print_response('prompt: %s' % self.prompt, '\n', 'response: %s' % self.response_prompt)
|
[
"Enable",
"or",
"disable",
"prompt",
":",
"param",
"arg",
":",
"on|off",
":",
"return",
":"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L161-L174
|
[
"def",
"do_prompt",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
".",
"lower",
"(",
")",
"==",
"'off'",
":",
"self",
".",
"response_prompt",
"=",
"''",
"self",
".",
"prompt",
"=",
"''",
"return",
"elif",
"arg",
".",
"lower",
"(",
")",
"==",
"'on'",
":",
"self",
".",
"prompt",
"=",
"PROMPT",
"self",
".",
"response_prompt",
"=",
"RESPONSE_PROMPT",
"self",
".",
"print_response",
"(",
"'prompt: %s'",
"%",
"self",
".",
"prompt",
",",
"'\\n'",
",",
"'response: %s'",
"%",
"self",
".",
"response_prompt",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_speed
|
rewind
|
shoebot/sbio/shell.py
|
def do_speed(self, speed):
"""
rewind
"""
if speed:
try:
self.bot._speed = float(speed)
except Exception as e:
self.print_response('%s is not a valid framerate' % speed)
return
self.print_response('Speed: %s FPS' % self.bot._speed)
|
def do_speed(self, speed):
"""
rewind
"""
if speed:
try:
self.bot._speed = float(speed)
except Exception as e:
self.print_response('%s is not a valid framerate' % speed)
return
self.print_response('Speed: %s FPS' % self.bot._speed)
|
[
"rewind"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L182-L192
|
[
"def",
"do_speed",
"(",
"self",
",",
"speed",
")",
":",
"if",
"speed",
":",
"try",
":",
"self",
".",
"bot",
".",
"_speed",
"=",
"float",
"(",
"speed",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"print_response",
"(",
"'%s is not a valid framerate'",
"%",
"speed",
")",
"return",
"self",
".",
"print_response",
"(",
"'Speed: %s FPS'",
"%",
"self",
".",
"bot",
".",
"_speed",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_restart
|
Attempt to restart the bot.
|
shoebot/sbio/shell.py
|
def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace)
|
def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace)
|
[
"Attempt",
"to",
"restart",
"the",
"bot",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L194-L200
|
[
"def",
"do_restart",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"bot",
".",
"_frame",
"=",
"0",
"self",
".",
"bot",
".",
"_namespace",
".",
"clear",
"(",
")",
"self",
".",
"bot",
".",
"_namespace",
".",
"update",
"(",
"self",
".",
"bot",
".",
"_initial_namespace",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_pause
|
Toggle pause
|
shoebot/sbio/shell.py
|
def do_pause(self, line):
"""
Toggle pause
"""
# along with stuff in socketserver and shell
if self.pause_speed is None:
self.pause_speed = self.bot._speed
self.bot._speed = 0
self.print_response('Paused')
else:
self.bot._speed = self.pause_speed
self.pause_speed = None
self.print_response('Playing')
|
def do_pause(self, line):
"""
Toggle pause
"""
# along with stuff in socketserver and shell
if self.pause_speed is None:
self.pause_speed = self.bot._speed
self.bot._speed = 0
self.print_response('Paused')
else:
self.bot._speed = self.pause_speed
self.pause_speed = None
self.print_response('Playing')
|
[
"Toggle",
"pause"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L202-L214
|
[
"def",
"do_pause",
"(",
"self",
",",
"line",
")",
":",
"# along with stuff in socketserver and shell",
"if",
"self",
".",
"pause_speed",
"is",
"None",
":",
"self",
".",
"pause_speed",
"=",
"self",
".",
"bot",
".",
"_speed",
"self",
".",
"bot",
".",
"_speed",
"=",
"0",
"self",
".",
"print_response",
"(",
"'Paused'",
")",
"else",
":",
"self",
".",
"bot",
".",
"_speed",
"=",
"self",
".",
"pause_speed",
"self",
".",
"pause_speed",
"=",
"None",
"self",
".",
"print_response",
"(",
"'Playing'",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_play
|
Resume playback if bot is paused
|
shoebot/sbio/shell.py
|
def do_play(self, line):
"""
Resume playback if bot is paused
"""
if self.pause_speed is None:
self.bot._speed = self.pause_speed
self.pause_speed = None
self.print_response("Play")
|
def do_play(self, line):
"""
Resume playback if bot is paused
"""
if self.pause_speed is None:
self.bot._speed = self.pause_speed
self.pause_speed = None
self.print_response("Play")
|
[
"Resume",
"playback",
"if",
"bot",
"is",
"paused"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L216-L223
|
[
"def",
"do_play",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"pause_speed",
"is",
"None",
":",
"self",
".",
"bot",
".",
"_speed",
"=",
"self",
".",
"pause_speed",
"self",
".",
"pause_speed",
"=",
"None",
"self",
".",
"print_response",
"(",
"\"Play\"",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_goto
|
Go to specific frame
:param line:
:return:
|
shoebot/sbio/shell.py
|
def do_goto(self, line):
"""
Go to specific frame
:param line:
:return:
"""
self.print_response("Go to frame %s" % line)
self.bot._frame = int(line)
|
def do_goto(self, line):
"""
Go to specific frame
:param line:
:return:
"""
self.print_response("Go to frame %s" % line)
self.bot._frame = int(line)
|
[
"Go",
"to",
"specific",
"frame",
":",
"param",
"line",
":",
":",
"return",
":"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L225-L232
|
[
"def",
"do_goto",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"print_response",
"(",
"\"Go to frame %s\"",
"%",
"line",
")",
"self",
".",
"bot",
".",
"_frame",
"=",
"int",
"(",
"line",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_rewind
|
rewind
|
shoebot/sbio/shell.py
|
def do_rewind(self, line):
"""
rewind
"""
self.print_response("Rewinding from frame %s to 0" % self.bot._frame)
self.bot._frame = 0
|
def do_rewind(self, line):
"""
rewind
"""
self.print_response("Rewinding from frame %s to 0" % self.bot._frame)
self.bot._frame = 0
|
[
"rewind"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L234-L239
|
[
"def",
"do_rewind",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"print_response",
"(",
"\"Rewinding from frame %s to 0\"",
"%",
"self",
".",
"bot",
".",
"_frame",
")",
"self",
".",
"bot",
".",
"_frame",
"=",
"0"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_vars
|
List bot variables and values
|
shoebot/sbio/shell.py
|
def do_vars(self, line):
"""
List bot variables and values
"""
if self.bot._vars:
max_name_len = max([len(name) for name in self.bot._vars])
for i, (name, v) in enumerate(self.bot._vars.items()):
keep = i < len(self.bot._vars) - 1
self.print_response("%s = %s" % (name.ljust(max_name_len), v.value), keep=keep)
else:
self.print_response("No vars")
|
def do_vars(self, line):
"""
List bot variables and values
"""
if self.bot._vars:
max_name_len = max([len(name) for name in self.bot._vars])
for i, (name, v) in enumerate(self.bot._vars.items()):
keep = i < len(self.bot._vars) - 1
self.print_response("%s = %s" % (name.ljust(max_name_len), v.value), keep=keep)
else:
self.print_response("No vars")
|
[
"List",
"bot",
"variables",
"and",
"values"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L241-L251
|
[
"def",
"do_vars",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"bot",
".",
"_vars",
":",
"max_name_len",
"=",
"max",
"(",
"[",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"self",
".",
"bot",
".",
"_vars",
"]",
")",
"for",
"i",
",",
"(",
"name",
",",
"v",
")",
"in",
"enumerate",
"(",
"self",
".",
"bot",
".",
"_vars",
".",
"items",
"(",
")",
")",
":",
"keep",
"=",
"i",
"<",
"len",
"(",
"self",
".",
"bot",
".",
"_vars",
")",
"-",
"1",
"self",
".",
"print_response",
"(",
"\"%s = %s\"",
"%",
"(",
"name",
".",
"ljust",
"(",
"max_name_len",
")",
",",
"v",
".",
"value",
")",
",",
"keep",
"=",
"keep",
")",
"else",
":",
"self",
".",
"print_response",
"(",
"\"No vars\"",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_load_base64
|
load filename=(file)
load base64=(base64 encoded)
Send new code to shoebot.
If it does not run successfully shoebot will attempt to role back.
Editors can enable livecoding by sending new code as it is edited.
|
shoebot/sbio/shell.py
|
def do_load_base64(self, line):
"""
load filename=(file)
load base64=(base64 encoded)
Send new code to shoebot.
If it does not run successfully shoebot will attempt to role back.
Editors can enable livecoding by sending new code as it is edited.
"""
cookie = self.cookie
executor = self.bot._executor
def source_good():
self.print_response(status=RESPONSE_CODE_OK, cookie=cookie)
executor.clear_callbacks()
def source_bad(tb):
if called_good:
# good and bad callbacks shouldn't both be called
raise ValueError('Good AND Bad callbacks called !')
self.print_response(status=RESPONSE_REVERTED, keep=True, cookie=cookie)
self.print_response(tb.replace('\n', '\\n'), cookie=cookie)
executor.clear_callbacks()
called_good = False
source = str(base64.b64decode(line))
# Test compile
publish_event(SOURCE_CHANGED_EVENT, data=source, extra_channels="shoebot.source")
self.bot._executor.load_edited_source(source, good_cb=source_good, bad_cb=source_bad)
|
def do_load_base64(self, line):
"""
load filename=(file)
load base64=(base64 encoded)
Send new code to shoebot.
If it does not run successfully shoebot will attempt to role back.
Editors can enable livecoding by sending new code as it is edited.
"""
cookie = self.cookie
executor = self.bot._executor
def source_good():
self.print_response(status=RESPONSE_CODE_OK, cookie=cookie)
executor.clear_callbacks()
def source_bad(tb):
if called_good:
# good and bad callbacks shouldn't both be called
raise ValueError('Good AND Bad callbacks called !')
self.print_response(status=RESPONSE_REVERTED, keep=True, cookie=cookie)
self.print_response(tb.replace('\n', '\\n'), cookie=cookie)
executor.clear_callbacks()
called_good = False
source = str(base64.b64decode(line))
# Test compile
publish_event(SOURCE_CHANGED_EVENT, data=source, extra_channels="shoebot.source")
self.bot._executor.load_edited_source(source, good_cb=source_good, bad_cb=source_bad)
|
[
"load",
"filename",
"=",
"(",
"file",
")",
"load",
"base64",
"=",
"(",
"base64",
"encoded",
")"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L254-L284
|
[
"def",
"do_load_base64",
"(",
"self",
",",
"line",
")",
":",
"cookie",
"=",
"self",
".",
"cookie",
"executor",
"=",
"self",
".",
"bot",
".",
"_executor",
"def",
"source_good",
"(",
")",
":",
"self",
".",
"print_response",
"(",
"status",
"=",
"RESPONSE_CODE_OK",
",",
"cookie",
"=",
"cookie",
")",
"executor",
".",
"clear_callbacks",
"(",
")",
"def",
"source_bad",
"(",
"tb",
")",
":",
"if",
"called_good",
":",
"# good and bad callbacks shouldn't both be called",
"raise",
"ValueError",
"(",
"'Good AND Bad callbacks called !'",
")",
"self",
".",
"print_response",
"(",
"status",
"=",
"RESPONSE_REVERTED",
",",
"keep",
"=",
"True",
",",
"cookie",
"=",
"cookie",
")",
"self",
".",
"print_response",
"(",
"tb",
".",
"replace",
"(",
"'\\n'",
",",
"'\\\\n'",
")",
",",
"cookie",
"=",
"cookie",
")",
"executor",
".",
"clear_callbacks",
"(",
")",
"called_good",
"=",
"False",
"source",
"=",
"str",
"(",
"base64",
".",
"b64decode",
"(",
"line",
")",
")",
"# Test compile",
"publish_event",
"(",
"SOURCE_CHANGED_EVENT",
",",
"data",
"=",
"source",
",",
"extra_channels",
"=",
"\"shoebot.source\"",
")",
"self",
".",
"bot",
".",
"_executor",
".",
"load_edited_source",
"(",
"source",
",",
"good_cb",
"=",
"source_good",
",",
"bad_cb",
"=",
"source_bad",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_exit
|
Exit shell and shoebot
|
shoebot/sbio/shell.py
|
def do_exit(self, line):
"""
Exit shell and shoebot
"""
if self.trusted:
publish_event(QUIT_EVENT)
self.print_response('Bye.\n')
return True
|
def do_exit(self, line):
"""
Exit shell and shoebot
"""
if self.trusted:
publish_event(QUIT_EVENT)
self.print_response('Bye.\n')
return True
|
[
"Exit",
"shell",
"and",
"shoebot"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L294-L301
|
[
"def",
"do_exit",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"trusted",
":",
"publish_event",
"(",
"QUIT_EVENT",
")",
"self",
".",
"print_response",
"(",
"'Bye.\\n'",
")",
"return",
"True"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_fullscreen
|
Make the current window fullscreen
|
shoebot/sbio/shell.py
|
def do_fullscreen(self, line):
"""
Make the current window fullscreen
"""
self.bot.canvas.sink.trigger_fullscreen_action(True)
print(self.response_prompt, file=self.stdout)
|
def do_fullscreen(self, line):
"""
Make the current window fullscreen
"""
self.bot.canvas.sink.trigger_fullscreen_action(True)
print(self.response_prompt, file=self.stdout)
|
[
"Make",
"the",
"current",
"window",
"fullscreen"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L311-L316
|
[
"def",
"do_fullscreen",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"bot",
".",
"canvas",
".",
"sink",
".",
"trigger_fullscreen_action",
"(",
"True",
")",
"print",
"(",
"self",
".",
"response_prompt",
",",
"file",
"=",
"self",
".",
"stdout",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_windowed
|
Un-fullscreen the current window
|
shoebot/sbio/shell.py
|
def do_windowed(self, line):
"""
Un-fullscreen the current window
"""
self.bot.canvas.sink.trigger_fullscreen_action(False)
print(self.response_prompt, file=self.stdout)
|
def do_windowed(self, line):
"""
Un-fullscreen the current window
"""
self.bot.canvas.sink.trigger_fullscreen_action(False)
print(self.response_prompt, file=self.stdout)
|
[
"Un",
"-",
"fullscreen",
"the",
"current",
"window"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L318-L323
|
[
"def",
"do_windowed",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"bot",
".",
"canvas",
".",
"sink",
".",
"trigger_fullscreen_action",
"(",
"False",
")",
"print",
"(",
"self",
".",
"response_prompt",
",",
"file",
"=",
"self",
".",
"stdout",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_EOF
|
Exit shell and shoebot
Alias for exit.
|
shoebot/sbio/shell.py
|
def do_EOF(self, line):
"""
Exit shell and shoebot
Alias for exit.
"""
print(self.response_prompt, file=self.stdout)
return self.do_exit(line)
|
def do_EOF(self, line):
"""
Exit shell and shoebot
Alias for exit.
"""
print(self.response_prompt, file=self.stdout)
return self.do_exit(line)
|
[
"Exit",
"shell",
"and",
"shoebot"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L325-L332
|
[
"def",
"do_EOF",
"(",
"self",
",",
"line",
")",
":",
"print",
"(",
"self",
".",
"response_prompt",
",",
"file",
"=",
"self",
".",
"stdout",
")",
"return",
"self",
".",
"do_exit",
"(",
"line",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_help
|
Show help on all commands.
|
shoebot/sbio/shell.py
|
def do_help(self, arg):
"""
Show help on all commands.
"""
print(self.response_prompt, file=self.stdout)
return cmd.Cmd.do_help(self, arg)
|
def do_help(self, arg):
"""
Show help on all commands.
"""
print(self.response_prompt, file=self.stdout)
return cmd.Cmd.do_help(self, arg)
|
[
"Show",
"help",
"on",
"all",
"commands",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L334-L339
|
[
"def",
"do_help",
"(",
"self",
",",
"arg",
")",
":",
"print",
"(",
"self",
".",
"response_prompt",
",",
"file",
"=",
"self",
".",
"stdout",
")",
"return",
"cmd",
".",
"Cmd",
".",
"do_help",
"(",
"self",
",",
"arg",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.do_set
|
Set a variable.
|
shoebot/sbio/shell.py
|
def do_set(self, line):
"""
Set a variable.
"""
try:
name, value = [part.strip() for part in line.split('=')]
if name not in self.bot._vars:
self.print_response('No such variable %s enter vars to see available vars' % name)
return
variable = self.bot._vars[name]
variable.value = variable.sanitize(value.strip(';'))
success, msg = self.bot.canvas.sink.var_changed(name, variable.value)
if success:
print('{}={}'.format(name, variable.value), file=self.stdout)
else:
print('{}\n'.format(msg), file=self.stdout)
except Exception as e:
print('Invalid Syntax.', e)
return
|
def do_set(self, line):
"""
Set a variable.
"""
try:
name, value = [part.strip() for part in line.split('=')]
if name not in self.bot._vars:
self.print_response('No such variable %s enter vars to see available vars' % name)
return
variable = self.bot._vars[name]
variable.value = variable.sanitize(value.strip(';'))
success, msg = self.bot.canvas.sink.var_changed(name, variable.value)
if success:
print('{}={}'.format(name, variable.value), file=self.stdout)
else:
print('{}\n'.format(msg), file=self.stdout)
except Exception as e:
print('Invalid Syntax.', e)
return
|
[
"Set",
"a",
"variable",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L341-L360
|
[
"def",
"do_set",
"(",
"self",
",",
"line",
")",
":",
"try",
":",
"name",
",",
"value",
"=",
"[",
"part",
".",
"strip",
"(",
")",
"for",
"part",
"in",
"line",
".",
"split",
"(",
"'='",
")",
"]",
"if",
"name",
"not",
"in",
"self",
".",
"bot",
".",
"_vars",
":",
"self",
".",
"print_response",
"(",
"'No such variable %s enter vars to see available vars'",
"%",
"name",
")",
"return",
"variable",
"=",
"self",
".",
"bot",
".",
"_vars",
"[",
"name",
"]",
"variable",
".",
"value",
"=",
"variable",
".",
"sanitize",
"(",
"value",
".",
"strip",
"(",
"';'",
")",
")",
"success",
",",
"msg",
"=",
"self",
".",
"bot",
".",
"canvas",
".",
"sink",
".",
"var_changed",
"(",
"name",
",",
"variable",
".",
"value",
")",
"if",
"success",
":",
"print",
"(",
"'{}={}'",
".",
"format",
"(",
"name",
",",
"variable",
".",
"value",
")",
",",
"file",
"=",
"self",
".",
"stdout",
")",
"else",
":",
"print",
"(",
"'{}\\n'",
".",
"format",
"(",
"msg",
")",
",",
"file",
"=",
"self",
".",
"stdout",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'Invalid Syntax.'",
",",
"e",
")",
"return"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotCmd.precmd
|
Allow commands to have a last parameter of 'cookie=somevalue'
TODO somevalue will be prepended onto any output lines so
that editors can distinguish output from certain kinds
of events they have sent.
:param line:
:return:
|
shoebot/sbio/shell.py
|
def precmd(self, line):
"""
Allow commands to have a last parameter of 'cookie=somevalue'
TODO somevalue will be prepended onto any output lines so
that editors can distinguish output from certain kinds
of events they have sent.
:param line:
:return:
"""
args = shlex.split(line or "")
if args and 'cookie=' in args[-1]:
cookie_index = line.index('cookie=')
cookie = line[cookie_index + 7:]
line = line[:cookie_index].strip()
self.cookie = cookie
if line.startswith('#'):
return ''
elif '=' in line:
# allow somevar=somevalue
# first check if we really mean a command
cmdname = line.partition(" ")[0]
if hasattr(self, "do_%s" % cmdname):
return line
if not line.startswith("set "):
return "set " + line
else:
return line
if len(args) and args[0] in self.shortcuts:
return "%s %s" % (self.shortcuts[args[0]], " ".join(args[1:]))
else:
return line
|
def precmd(self, line):
"""
Allow commands to have a last parameter of 'cookie=somevalue'
TODO somevalue will be prepended onto any output lines so
that editors can distinguish output from certain kinds
of events they have sent.
:param line:
:return:
"""
args = shlex.split(line or "")
if args and 'cookie=' in args[-1]:
cookie_index = line.index('cookie=')
cookie = line[cookie_index + 7:]
line = line[:cookie_index].strip()
self.cookie = cookie
if line.startswith('#'):
return ''
elif '=' in line:
# allow somevar=somevalue
# first check if we really mean a command
cmdname = line.partition(" ")[0]
if hasattr(self, "do_%s" % cmdname):
return line
if not line.startswith("set "):
return "set " + line
else:
return line
if len(args) and args[0] in self.shortcuts:
return "%s %s" % (self.shortcuts[args[0]], " ".join(args[1:]))
else:
return line
|
[
"Allow",
"commands",
"to",
"have",
"a",
"last",
"parameter",
"of",
"cookie",
"=",
"somevalue"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L362-L396
|
[
"def",
"precmd",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
"or",
"\"\"",
")",
"if",
"args",
"and",
"'cookie='",
"in",
"args",
"[",
"-",
"1",
"]",
":",
"cookie_index",
"=",
"line",
".",
"index",
"(",
"'cookie='",
")",
"cookie",
"=",
"line",
"[",
"cookie_index",
"+",
"7",
":",
"]",
"line",
"=",
"line",
"[",
":",
"cookie_index",
"]",
".",
"strip",
"(",
")",
"self",
".",
"cookie",
"=",
"cookie",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"return",
"''",
"elif",
"'='",
"in",
"line",
":",
"# allow somevar=somevalue",
"# first check if we really mean a command",
"cmdname",
"=",
"line",
".",
"partition",
"(",
"\" \"",
")",
"[",
"0",
"]",
"if",
"hasattr",
"(",
"self",
",",
"\"do_%s\"",
"%",
"cmdname",
")",
":",
"return",
"line",
"if",
"not",
"line",
".",
"startswith",
"(",
"\"set \"",
")",
":",
"return",
"\"set \"",
"+",
"line",
"else",
":",
"return",
"line",
"if",
"len",
"(",
"args",
")",
"and",
"args",
"[",
"0",
"]",
"in",
"self",
".",
"shortcuts",
":",
"return",
"\"%s %s\"",
"%",
"(",
"self",
".",
"shortcuts",
"[",
"args",
"[",
"0",
"]",
"]",
",",
"\" \"",
".",
"join",
"(",
"args",
"[",
"1",
":",
"]",
")",
")",
"else",
":",
"return",
"line"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
drawdaisy
|
Draw a daisy at x, y
|
examples/libraries/making_libraries/daisylib.py
|
def drawdaisy(x, y, color='#fefefe'):
"""
Draw a daisy at x, y
"""
# save location, size etc
_ctx.push()
# save fill and stroke
_fill =_ctx.fill()
_stroke = _ctx.stroke()
sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0
# draw stalk
_ctx.strokewidth(sc * 2.0)
_ctx.stroke('#3B240B')
_ctx.line(x + (sin(x * 0.1) * 10.0), y + 80, x + sin(_ctx.FRAME * 0.1), y)
# draw flower
_ctx.translate(-20, 0)
_ctx.scale(sc)
# draw petals
_ctx.fill(color)
_ctx.nostroke()
for angle in xrange(0, 360, 45):
_ctx.rotate(degrees=45)
_ctx.rect(x, y, 40, 8, 1)
# draw centre
_ctx.fill('#F7FE2E')
_ctx.ellipse(x + 15, y, 10, 10)
# restore fill and stroke
_ctx.fill(_fill)
_ctx.stroke(_stroke)
# restore location, size etc
_ctx.pop()
|
def drawdaisy(x, y, color='#fefefe'):
"""
Draw a daisy at x, y
"""
# save location, size etc
_ctx.push()
# save fill and stroke
_fill =_ctx.fill()
_stroke = _ctx.stroke()
sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0
# draw stalk
_ctx.strokewidth(sc * 2.0)
_ctx.stroke('#3B240B')
_ctx.line(x + (sin(x * 0.1) * 10.0), y + 80, x + sin(_ctx.FRAME * 0.1), y)
# draw flower
_ctx.translate(-20, 0)
_ctx.scale(sc)
# draw petals
_ctx.fill(color)
_ctx.nostroke()
for angle in xrange(0, 360, 45):
_ctx.rotate(degrees=45)
_ctx.rect(x, y, 40, 8, 1)
# draw centre
_ctx.fill('#F7FE2E')
_ctx.ellipse(x + 15, y, 10, 10)
# restore fill and stroke
_ctx.fill(_fill)
_ctx.stroke(_stroke)
# restore location, size etc
_ctx.pop()
|
[
"Draw",
"a",
"daisy",
"at",
"x",
"y"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/examples/libraries/making_libraries/daisylib.py#L16-L55
|
[
"def",
"drawdaisy",
"(",
"x",
",",
"y",
",",
"color",
"=",
"'#fefefe'",
")",
":",
"# save location, size etc",
"_ctx",
".",
"push",
"(",
")",
"# save fill and stroke",
"_fill",
"=",
"_ctx",
".",
"fill",
"(",
")",
"_stroke",
"=",
"_ctx",
".",
"stroke",
"(",
")",
"sc",
"=",
"(",
"1.0",
"/",
"_ctx",
".",
"HEIGHT",
")",
"*",
"float",
"(",
"y",
"*",
"0.5",
")",
"*",
"4.0",
"# draw stalk",
"_ctx",
".",
"strokewidth",
"(",
"sc",
"*",
"2.0",
")",
"_ctx",
".",
"stroke",
"(",
"'#3B240B'",
")",
"_ctx",
".",
"line",
"(",
"x",
"+",
"(",
"sin",
"(",
"x",
"*",
"0.1",
")",
"*",
"10.0",
")",
",",
"y",
"+",
"80",
",",
"x",
"+",
"sin",
"(",
"_ctx",
".",
"FRAME",
"*",
"0.1",
")",
",",
"y",
")",
"# draw flower",
"_ctx",
".",
"translate",
"(",
"-",
"20",
",",
"0",
")",
"_ctx",
".",
"scale",
"(",
"sc",
")",
"# draw petals",
"_ctx",
".",
"fill",
"(",
"color",
")",
"_ctx",
".",
"nostroke",
"(",
")",
"for",
"angle",
"in",
"xrange",
"(",
"0",
",",
"360",
",",
"45",
")",
":",
"_ctx",
".",
"rotate",
"(",
"degrees",
"=",
"45",
")",
"_ctx",
".",
"rect",
"(",
"x",
",",
"y",
",",
"40",
",",
"8",
",",
"1",
")",
"# draw centre",
"_ctx",
".",
"fill",
"(",
"'#F7FE2E'",
")",
"_ctx",
".",
"ellipse",
"(",
"x",
"+",
"15",
",",
"y",
",",
"10",
",",
"10",
")",
"# restore fill and stroke",
"_ctx",
".",
"fill",
"(",
"_fill",
")",
"_ctx",
".",
"stroke",
"(",
"_stroke",
")",
"# restore location, size etc",
"_ctx",
".",
"pop",
"(",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
fft_bandpassfilter
|
http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801
|
lib/sbaudio/__init__.py
|
def fft_bandpassfilter(data, fs, lowcut, highcut):
"""
http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801
"""
fft = np.fft.fft(data)
# n = len(data)
# timestep = 1.0 / fs
# freq = np.fft.fftfreq(n, d=timestep)
bp = fft.copy()
# Zero out fft coefficients
# bp[10:-10] = 0
# Normalise
# bp *= real(fft.dot(fft))/real(bp.dot(bp))
bp *= fft.dot(fft) / bp.dot(bp)
# must multipy by 2 to get the correct amplitude
ibp = 12 * np.fft.ifft(bp)
return ibp
|
def fft_bandpassfilter(data, fs, lowcut, highcut):
"""
http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801
"""
fft = np.fft.fft(data)
# n = len(data)
# timestep = 1.0 / fs
# freq = np.fft.fftfreq(n, d=timestep)
bp = fft.copy()
# Zero out fft coefficients
# bp[10:-10] = 0
# Normalise
# bp *= real(fft.dot(fft))/real(bp.dot(bp))
bp *= fft.dot(fft) / bp.dot(bp)
# must multipy by 2 to get the correct amplitude
ibp = 12 * np.fft.ifft(bp)
return ibp
|
[
"http",
":",
"//",
"www",
".",
"swharden",
".",
"com",
"/",
"blog",
"/",
"2009",
"-",
"01",
"-",
"21",
"-",
"signal",
"-",
"filtering",
"-",
"with",
"-",
"python",
"/",
"#comment",
"-",
"16801"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/sbaudio/__init__.py#L14-L34
|
[
"def",
"fft_bandpassfilter",
"(",
"data",
",",
"fs",
",",
"lowcut",
",",
"highcut",
")",
":",
"fft",
"=",
"np",
".",
"fft",
".",
"fft",
"(",
"data",
")",
"# n = len(data)",
"# timestep = 1.0 / fs",
"# freq = np.fft.fftfreq(n, d=timestep)",
"bp",
"=",
"fft",
".",
"copy",
"(",
")",
"# Zero out fft coefficients",
"# bp[10:-10] = 0",
"# Normalise",
"# bp *= real(fft.dot(fft))/real(bp.dot(bp))",
"bp",
"*=",
"fft",
".",
"dot",
"(",
"fft",
")",
"/",
"bp",
".",
"dot",
"(",
"bp",
")",
"# must multipy by 2 to get the correct amplitude",
"ibp",
"=",
"12",
"*",
"np",
".",
"fft",
".",
"ifft",
"(",
"bp",
")",
"return",
"ibp"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
flatten_fft
|
Produces a nicer graph, I'm not sure if this is correct
|
lib/sbaudio/__init__.py
|
def flatten_fft(scale=1.0):
"""
Produces a nicer graph, I'm not sure if this is correct
"""
_len = len(audio.spectrogram)
for i, v in enumerate(audio.spectrogram):
yield scale * (i * v) / _len
|
def flatten_fft(scale=1.0):
"""
Produces a nicer graph, I'm not sure if this is correct
"""
_len = len(audio.spectrogram)
for i, v in enumerate(audio.spectrogram):
yield scale * (i * v) / _len
|
[
"Produces",
"a",
"nicer",
"graph",
"I",
"m",
"not",
"sure",
"if",
"this",
"is",
"correct"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/sbaudio/__init__.py#L46-L52
|
[
"def",
"flatten_fft",
"(",
"scale",
"=",
"1.0",
")",
":",
"_len",
"=",
"len",
"(",
"audio",
".",
"spectrogram",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"audio",
".",
"spectrogram",
")",
":",
"yield",
"scale",
"*",
"(",
"i",
"*",
"v",
")",
"/",
"_len"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
scaled_fft
|
Produces a nicer graph, I'm not sure if this is correct
|
lib/sbaudio/__init__.py
|
def scaled_fft(fft, scale=1.0):
"""
Produces a nicer graph, I'm not sure if this is correct
"""
data = np.zeros(len(fft))
for i, v in enumerate(fft):
data[i] = scale * (i * v) / NUM_SAMPLES
return data
|
def scaled_fft(fft, scale=1.0):
"""
Produces a nicer graph, I'm not sure if this is correct
"""
data = np.zeros(len(fft))
for i, v in enumerate(fft):
data[i] = scale * (i * v) / NUM_SAMPLES
return data
|
[
"Produces",
"a",
"nicer",
"graph",
"I",
"m",
"not",
"sure",
"if",
"this",
"is",
"correct"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/sbaudio/__init__.py#L55-L63
|
[
"def",
"scaled_fft",
"(",
"fft",
",",
"scale",
"=",
"1.0",
")",
":",
"data",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"fft",
")",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"fft",
")",
":",
"data",
"[",
"i",
"]",
"=",
"scale",
"*",
"(",
"i",
"*",
"v",
")",
"/",
"NUM_SAMPLES",
"return",
"data"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotWindowHelper.get_source
|
Grab contents of 'doc' and return it
:param doc: The active document
:return:
|
extensions/gedit/gedit2-plugin/shoebotit/__init__.py
|
def get_source(self, doc):
"""
Grab contents of 'doc' and return it
:param doc: The active document
:return:
"""
start_iter = doc.get_start_iter()
end_iter = doc.get_end_iter()
source = doc.get_text(start_iter, end_iter, False)
return source
|
def get_source(self, doc):
"""
Grab contents of 'doc' and return it
:param doc: The active document
:return:
"""
start_iter = doc.get_start_iter()
end_iter = doc.get_end_iter()
source = doc.get_text(start_iter, end_iter, False)
return source
|
[
"Grab",
"contents",
"of",
"doc",
"and",
"return",
"it"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/shoebotit/__init__.py#L186-L196
|
[
"def",
"get_source",
"(",
"self",
",",
"doc",
")",
":",
"start_iter",
"=",
"doc",
".",
"get_start_iter",
"(",
")",
"end_iter",
"=",
"doc",
".",
"get_end_iter",
"(",
")",
"source",
"=",
"doc",
".",
"get_text",
"(",
"start_iter",
",",
"end_iter",
",",
"False",
")",
"return",
"source"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotPlugin._create_view
|
Create the gtk.TextView used for shell output
|
extensions/gedit/gedit2-plugin/shoebotit/__init__.py
|
def _create_view(self, name="shoebot-output"):
""" Create the gtk.TextView used for shell output """
view = gtk.TextView()
view.set_editable(False)
fontdesc = pango.FontDescription("Monospace")
view.modify_font(fontdesc)
view.set_name(name)
buff = view.get_buffer()
buff.create_tag('error', foreground='red')
return view
|
def _create_view(self, name="shoebot-output"):
""" Create the gtk.TextView used for shell output """
view = gtk.TextView()
view.set_editable(False)
fontdesc = pango.FontDescription("Monospace")
view.modify_font(fontdesc)
view.set_name(name)
buff = view.get_buffer()
buff.create_tag('error', foreground='red')
return view
|
[
"Create",
"the",
"gtk",
".",
"TextView",
"used",
"for",
"shell",
"output"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/shoebotit/__init__.py#L295-L306
|
[
"def",
"_create_view",
"(",
"self",
",",
"name",
"=",
"\"shoebot-output\"",
")",
":",
"view",
"=",
"gtk",
".",
"TextView",
"(",
")",
"view",
".",
"set_editable",
"(",
"False",
")",
"fontdesc",
"=",
"pango",
".",
"FontDescription",
"(",
"\"Monospace\"",
")",
"view",
".",
"modify_font",
"(",
"fontdesc",
")",
"view",
".",
"set_name",
"(",
"name",
")",
"buff",
"=",
"view",
".",
"get_buffer",
"(",
")",
"buff",
".",
"create_tag",
"(",
"'error'",
",",
"foreground",
"=",
"'red'",
")",
"return",
"view"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
ShoebotPlugin._create_view
|
Create the gtk.TextView inside a Gtk.ScrolledWindow
:return: container, text_view
|
extensions/gedit/gedit3.12-plugin/shoebotit/__init__.py
|
def _create_view(self, name="shoebot-output"):
"""
Create the gtk.TextView inside a Gtk.ScrolledWindow
:return: container, text_view
"""
text_view = Gtk.TextView()
text_view.set_editable(False)
fontdesc = Pango.FontDescription("Monospace")
text_view.modify_font(fontdesc)
text_view.set_name(name)
buff = text_view.get_buffer()
buff.create_tag('error', foreground='red')
container = Gtk.ScrolledWindow()
container.add(text_view)
container.show_all()
return container, text_view
|
def _create_view(self, name="shoebot-output"):
"""
Create the gtk.TextView inside a Gtk.ScrolledWindow
:return: container, text_view
"""
text_view = Gtk.TextView()
text_view.set_editable(False)
fontdesc = Pango.FontDescription("Monospace")
text_view.modify_font(fontdesc)
text_view.set_name(name)
buff = text_view.get_buffer()
buff.create_tag('error', foreground='red')
container = Gtk.ScrolledWindow()
container.add(text_view)
container.show_all()
return container, text_view
|
[
"Create",
"the",
"gtk",
".",
"TextView",
"inside",
"a",
"Gtk",
".",
"ScrolledWindow",
":",
"return",
":",
"container",
"text_view"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit3.12-plugin/shoebotit/__init__.py#L49-L67
|
[
"def",
"_create_view",
"(",
"self",
",",
"name",
"=",
"\"shoebot-output\"",
")",
":",
"text_view",
"=",
"Gtk",
".",
"TextView",
"(",
")",
"text_view",
".",
"set_editable",
"(",
"False",
")",
"fontdesc",
"=",
"Pango",
".",
"FontDescription",
"(",
"\"Monospace\"",
")",
"text_view",
".",
"modify_font",
"(",
"fontdesc",
")",
"text_view",
".",
"set_name",
"(",
"name",
")",
"buff",
"=",
"text_view",
".",
"get_buffer",
"(",
")",
"buff",
".",
"create_tag",
"(",
"'error'",
",",
"foreground",
"=",
"'red'",
")",
"container",
"=",
"Gtk",
".",
"ScrolledWindow",
"(",
")",
"container",
".",
"add",
"(",
"text_view",
")",
"container",
".",
"show_all",
"(",
")",
"return",
"container",
",",
"text_view"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
openAnything
|
URI, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, readlines).
Just .close() the object when you're done with it.
Examples:
>>> from xml.dom import minidom
>>> sock = openAnything("http://localhost/kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("c:\\inetpub\\wwwroot\\kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("<ref id='conjunction'><text>and</text><text>or</text></ref>")
>>> doc = minidom.parse(sock)
>>> sock.close()
|
shoebot/kgp.py
|
def openAnything(source, searchpaths=None):
"""URI, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, readlines).
Just .close() the object when you're done with it.
Examples:
>>> from xml.dom import minidom
>>> sock = openAnything("http://localhost/kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("c:\\inetpub\\wwwroot\\kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("<ref id='conjunction'><text>and</text><text>or</text></ref>")
>>> doc = minidom.parse(sock)
>>> sock.close()
"""
if hasattr(source, "read"):
return source
if source == "-":
import sys
return sys.stdin
# try to open with urllib (if source is http, ftp, or file URL)
import urllib
try:
return urllib.urlopen(source)
except (IOError, OSError):
pass
# try to open with native open function (if source is pathname)
for path in searchpaths or ['.']:
try:
return open(os.path.join(path, source))
except (IOError, OSError):
pass
# treat source as string
import StringIO
return StringIO.StringIO(str(source))
|
def openAnything(source, searchpaths=None):
"""URI, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, readlines).
Just .close() the object when you're done with it.
Examples:
>>> from xml.dom import minidom
>>> sock = openAnything("http://localhost/kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("c:\\inetpub\\wwwroot\\kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("<ref id='conjunction'><text>and</text><text>or</text></ref>")
>>> doc = minidom.parse(sock)
>>> sock.close()
"""
if hasattr(source, "read"):
return source
if source == "-":
import sys
return sys.stdin
# try to open with urllib (if source is http, ftp, or file URL)
import urllib
try:
return urllib.urlopen(source)
except (IOError, OSError):
pass
# try to open with native open function (if source is pathname)
for path in searchpaths or ['.']:
try:
return open(os.path.join(path, source))
except (IOError, OSError):
pass
# treat source as string
import StringIO
return StringIO.StringIO(str(source))
|
[
"URI",
"filename",
"or",
"string",
"--",
">",
"stream",
"This",
"function",
"lets",
"you",
"define",
"parsers",
"that",
"take",
"any",
"input",
"source",
"(",
"URL",
"pathname",
"to",
"local",
"or",
"network",
"file",
"or",
"actual",
"data",
"as",
"a",
"string",
")",
"and",
"deal",
"with",
"it",
"in",
"a",
"uniform",
"manner",
".",
"Returned",
"object",
"is",
"guaranteed",
"to",
"have",
"all",
"the",
"basic",
"stdio",
"read",
"methods",
"(",
"read",
"readline",
"readlines",
")",
".",
"Just",
".",
"close",
"()",
"the",
"object",
"when",
"you",
"re",
"done",
"with",
"it",
".",
"Examples",
":",
">>>",
"from",
"xml",
".",
"dom",
"import",
"minidom",
">>>",
"sock",
"=",
"openAnything",
"(",
"http",
":",
"//",
"localhost",
"/",
"kant",
".",
"xml",
")",
">>>",
"doc",
"=",
"minidom",
".",
"parse",
"(",
"sock",
")",
">>>",
"sock",
".",
"close",
"()",
">>>",
"sock",
"=",
"openAnything",
"(",
"c",
":",
"\\\\",
"inetpub",
"\\\\",
"wwwroot",
"\\\\",
"kant",
".",
"xml",
")",
">>>",
"doc",
"=",
"minidom",
".",
"parse",
"(",
"sock",
")",
">>>",
"sock",
".",
"close",
"()",
">>>",
"sock",
"=",
"openAnything",
"(",
"<ref",
"id",
"=",
"conjunction",
">",
"<text",
">",
"and<",
"/",
"text",
">",
"<text",
">",
"or<",
"/",
"text",
">",
"<",
"/",
"ref",
">",
")",
">>>",
"doc",
"=",
"minidom",
".",
"parse",
"(",
"sock",
")",
">>>",
"sock",
".",
"close",
"()"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L38-L84
|
[
"def",
"openAnything",
"(",
"source",
",",
"searchpaths",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"\"read\"",
")",
":",
"return",
"source",
"if",
"source",
"==",
"\"-\"",
":",
"import",
"sys",
"return",
"sys",
".",
"stdin",
"# try to open with urllib (if source is http, ftp, or file URL)\r",
"import",
"urllib",
"try",
":",
"return",
"urllib",
".",
"urlopen",
"(",
"source",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"pass",
"# try to open with native open function (if source is pathname)\r",
"for",
"path",
"in",
"searchpaths",
"or",
"[",
"'.'",
"]",
":",
"try",
":",
"return",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"source",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"pass",
"# treat source as string\r",
"import",
"StringIO",
"return",
"StringIO",
".",
"StringIO",
"(",
"str",
"(",
"source",
")",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator._load
|
load XML input source, return parsed XML document
- a URL of a remote XML file ("http://diveintopython.org/kant.xml")
- a filename of a local XML file ("~/diveintopython/common/py/kant.xml")
- standard input ("-")
- the actual XML document, as a string
:param searchpaths: optional searchpaths if file is used.
|
shoebot/kgp.py
|
def _load(self, source, searchpaths=None):
"""load XML input source, return parsed XML document
- a URL of a remote XML file ("http://diveintopython.org/kant.xml")
- a filename of a local XML file ("~/diveintopython/common/py/kant.xml")
- standard input ("-")
- the actual XML document, as a string
:param searchpaths: optional searchpaths if file is used.
"""
sock = openAnything(source, searchpaths=searchpaths)
xmldoc = minidom.parse(sock).documentElement
sock.close()
return xmldoc
|
def _load(self, source, searchpaths=None):
"""load XML input source, return parsed XML document
- a URL of a remote XML file ("http://diveintopython.org/kant.xml")
- a filename of a local XML file ("~/diveintopython/common/py/kant.xml")
- standard input ("-")
- the actual XML document, as a string
:param searchpaths: optional searchpaths if file is used.
"""
sock = openAnything(source, searchpaths=searchpaths)
xmldoc = minidom.parse(sock).documentElement
sock.close()
return xmldoc
|
[
"load",
"XML",
"input",
"source",
"return",
"parsed",
"XML",
"document",
"-",
"a",
"URL",
"of",
"a",
"remote",
"XML",
"file",
"(",
"http",
":",
"//",
"diveintopython",
".",
"org",
"/",
"kant",
".",
"xml",
")",
"-",
"a",
"filename",
"of",
"a",
"local",
"XML",
"file",
"(",
"~",
"/",
"diveintopython",
"/",
"common",
"/",
"py",
"/",
"kant",
".",
"xml",
")",
"-",
"standard",
"input",
"(",
"-",
")",
"-",
"the",
"actual",
"XML",
"document",
"as",
"a",
"string",
":",
"param",
"searchpaths",
":",
"optional",
"searchpaths",
"if",
"file",
"is",
"used",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L96-L109
|
[
"def",
"_load",
"(",
"self",
",",
"source",
",",
"searchpaths",
"=",
"None",
")",
":",
"sock",
"=",
"openAnything",
"(",
"source",
",",
"searchpaths",
"=",
"searchpaths",
")",
"xmldoc",
"=",
"minidom",
".",
"parse",
"(",
"sock",
")",
".",
"documentElement",
"sock",
".",
"close",
"(",
")",
"return",
"xmldoc"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.loadGrammar
|
load context-free grammar
|
shoebot/kgp.py
|
def loadGrammar(self, grammar, searchpaths=None):
"""load context-free grammar"""
self.grammar = self._load(grammar, searchpaths=searchpaths)
self.refs = {}
for ref in self.grammar.getElementsByTagName("ref"):
self.refs[ref.attributes["id"].value] = ref
|
def loadGrammar(self, grammar, searchpaths=None):
"""load context-free grammar"""
self.grammar = self._load(grammar, searchpaths=searchpaths)
self.refs = {}
for ref in self.grammar.getElementsByTagName("ref"):
self.refs[ref.attributes["id"].value] = ref
|
[
"load",
"context",
"-",
"free",
"grammar"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L111-L116
|
[
"def",
"loadGrammar",
"(",
"self",
",",
"grammar",
",",
"searchpaths",
"=",
"None",
")",
":",
"self",
".",
"grammar",
"=",
"self",
".",
"_load",
"(",
"grammar",
",",
"searchpaths",
"=",
"searchpaths",
")",
"self",
".",
"refs",
"=",
"{",
"}",
"for",
"ref",
"in",
"self",
".",
"grammar",
".",
"getElementsByTagName",
"(",
"\"ref\"",
")",
":",
"self",
".",
"refs",
"[",
"ref",
".",
"attributes",
"[",
"\"id\"",
"]",
".",
"value",
"]",
"=",
"ref"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.loadSource
|
load source
|
shoebot/kgp.py
|
def loadSource(self, source, searchpaths=None):
"""load source"""
self.source = self._load(source, searchpaths=searchpaths)
|
def loadSource(self, source, searchpaths=None):
"""load source"""
self.source = self._load(source, searchpaths=searchpaths)
|
[
"load",
"source"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L118-L120
|
[
"def",
"loadSource",
"(",
"self",
",",
"source",
",",
"searchpaths",
"=",
"None",
")",
":",
"self",
".",
"source",
"=",
"self",
".",
"_load",
"(",
"source",
",",
"searchpaths",
"=",
"searchpaths",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.getDefaultSource
|
guess default source of the current grammar
The default source will be one of the <ref>s that is not
cross-referenced. This sounds complicated but it's not.
Example: The default source for kant.xml is
"<xref id='section'/>", because 'section' is the one <ref>
that is not <xref>'d anywhere in the grammar.
In most grammars, the default source will produce the
longest (and most interesting) output.
|
shoebot/kgp.py
|
def getDefaultSource(self):
"""guess default source of the current grammar
The default source will be one of the <ref>s that is not
cross-referenced. This sounds complicated but it's not.
Example: The default source for kant.xml is
"<xref id='section'/>", because 'section' is the one <ref>
that is not <xref>'d anywhere in the grammar.
In most grammars, the default source will produce the
longest (and most interesting) output.
"""
xrefs = {}
for xref in self.grammar.getElementsByTagName("xref"):
xrefs[xref.attributes["id"].value] = 1
xrefs = xrefs.keys()
standaloneXrefs = [e for e in self.refs.keys() if e not in xrefs]
if not standaloneXrefs:
raise NoSourceError, "can't guess source, and no source specified"
return '<xref id="%s"/>' % random.choice(standaloneXrefs)
|
def getDefaultSource(self):
"""guess default source of the current grammar
The default source will be one of the <ref>s that is not
cross-referenced. This sounds complicated but it's not.
Example: The default source for kant.xml is
"<xref id='section'/>", because 'section' is the one <ref>
that is not <xref>'d anywhere in the grammar.
In most grammars, the default source will produce the
longest (and most interesting) output.
"""
xrefs = {}
for xref in self.grammar.getElementsByTagName("xref"):
xrefs[xref.attributes["id"].value] = 1
xrefs = xrefs.keys()
standaloneXrefs = [e for e in self.refs.keys() if e not in xrefs]
if not standaloneXrefs:
raise NoSourceError, "can't guess source, and no source specified"
return '<xref id="%s"/>' % random.choice(standaloneXrefs)
|
[
"guess",
"default",
"source",
"of",
"the",
"current",
"grammar",
"The",
"default",
"source",
"will",
"be",
"one",
"of",
"the",
"<ref",
">",
"s",
"that",
"is",
"not",
"cross",
"-",
"referenced",
".",
"This",
"sounds",
"complicated",
"but",
"it",
"s",
"not",
".",
"Example",
":",
"The",
"default",
"source",
"for",
"kant",
".",
"xml",
"is",
"<xref",
"id",
"=",
"section",
"/",
">",
"because",
"section",
"is",
"the",
"one",
"<ref",
">",
"that",
"is",
"not",
"<xref",
">",
"d",
"anywhere",
"in",
"the",
"grammar",
".",
"In",
"most",
"grammars",
"the",
"default",
"source",
"will",
"produce",
"the",
"longest",
"(",
"and",
"most",
"interesting",
")",
"output",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L122-L140
|
[
"def",
"getDefaultSource",
"(",
"self",
")",
":",
"xrefs",
"=",
"{",
"}",
"for",
"xref",
"in",
"self",
".",
"grammar",
".",
"getElementsByTagName",
"(",
"\"xref\"",
")",
":",
"xrefs",
"[",
"xref",
".",
"attributes",
"[",
"\"id\"",
"]",
".",
"value",
"]",
"=",
"1",
"xrefs",
"=",
"xrefs",
".",
"keys",
"(",
")",
"standaloneXrefs",
"=",
"[",
"e",
"for",
"e",
"in",
"self",
".",
"refs",
".",
"keys",
"(",
")",
"if",
"e",
"not",
"in",
"xrefs",
"]",
"if",
"not",
"standaloneXrefs",
":",
"raise",
"NoSourceError",
",",
"\"can't guess source, and no source specified\"",
"return",
"'<xref id=\"%s\"/>'",
"%",
"random",
".",
"choice",
"(",
"standaloneXrefs",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.refresh
|
reset output buffer, re-parse entire source file, and return output
Since parsing involves a good deal of randomness, this is an
easy way to get new output without having to reload a grammar file
each time.
|
shoebot/kgp.py
|
def refresh(self):
"""reset output buffer, re-parse entire source file, and return output
Since parsing involves a good deal of randomness, this is an
easy way to get new output without having to reload a grammar file
each time.
"""
self.reset()
self.parse(self.source)
return self.output()
|
def refresh(self):
"""reset output buffer, re-parse entire source file, and return output
Since parsing involves a good deal of randomness, this is an
easy way to get new output without having to reload a grammar file
each time.
"""
self.reset()
self.parse(self.source)
return self.output()
|
[
"reset",
"output",
"buffer",
"re",
"-",
"parse",
"entire",
"source",
"file",
"and",
"return",
"output",
"Since",
"parsing",
"involves",
"a",
"good",
"deal",
"of",
"randomness",
"this",
"is",
"an",
"easy",
"way",
"to",
"get",
"new",
"output",
"without",
"having",
"to",
"reload",
"a",
"grammar",
"file",
"each",
"time",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L147-L156
|
[
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"parse",
"(",
"self",
".",
"source",
")",
"return",
"self",
".",
"output",
"(",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.randomChildElement
|
choose a random child element of a node
This is a utility method used by do_xref and do_choice.
|
shoebot/kgp.py
|
def randomChildElement(self, node):
"""choose a random child element of a node
This is a utility method used by do_xref and do_choice.
"""
choices = [e for e in node.childNodes
if e.nodeType == e.ELEMENT_NODE]
chosen = random.choice(choices)
if _debug:
sys.stderr.write('%s available choices: %s\n' % \
(len(choices), [e.toxml() for e in choices]))
sys.stderr.write('Chosen: %s\n' % chosen.toxml())
return chosen
|
def randomChildElement(self, node):
"""choose a random child element of a node
This is a utility method used by do_xref and do_choice.
"""
choices = [e for e in node.childNodes
if e.nodeType == e.ELEMENT_NODE]
chosen = random.choice(choices)
if _debug:
sys.stderr.write('%s available choices: %s\n' % \
(len(choices), [e.toxml() for e in choices]))
sys.stderr.write('Chosen: %s\n' % chosen.toxml())
return chosen
|
[
"choose",
"a",
"random",
"child",
"element",
"of",
"a",
"node",
"This",
"is",
"a",
"utility",
"method",
"used",
"by",
"do_xref",
"and",
"do_choice",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L162-L174
|
[
"def",
"randomChildElement",
"(",
"self",
",",
"node",
")",
":",
"choices",
"=",
"[",
"e",
"for",
"e",
"in",
"node",
".",
"childNodes",
"if",
"e",
".",
"nodeType",
"==",
"e",
".",
"ELEMENT_NODE",
"]",
"chosen",
"=",
"random",
".",
"choice",
"(",
"choices",
")",
"if",
"_debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s available choices: %s\\n'",
"%",
"(",
"len",
"(",
"choices",
")",
",",
"[",
"e",
".",
"toxml",
"(",
")",
"for",
"e",
"in",
"choices",
"]",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Chosen: %s\\n'",
"%",
"chosen",
".",
"toxml",
"(",
")",
")",
"return",
"chosen"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.parse
|
parse a single XML node
A parsed XML document (from minidom.parse) is a tree of nodes
of various types. Each node is represented by an instance of the
corresponding Python class (Element for a tag, Text for
text data, Document for the top-level document). The following
statement constructs the name of a class method based on the type
of node we're parsing ("parse_Element" for an Element node,
"parse_Text" for a Text node, etc.) and then calls the method.
|
shoebot/kgp.py
|
def parse(self, node):
"""parse a single XML node
A parsed XML document (from minidom.parse) is a tree of nodes
of various types. Each node is represented by an instance of the
corresponding Python class (Element for a tag, Text for
text data, Document for the top-level document). The following
statement constructs the name of a class method based on the type
of node we're parsing ("parse_Element" for an Element node,
"parse_Text" for a Text node, etc.) and then calls the method.
"""
parseMethod = getattr(self, "parse_%s" % node.__class__.__name__)
parseMethod(node)
|
def parse(self, node):
"""parse a single XML node
A parsed XML document (from minidom.parse) is a tree of nodes
of various types. Each node is represented by an instance of the
corresponding Python class (Element for a tag, Text for
text data, Document for the top-level document). The following
statement constructs the name of a class method based on the type
of node we're parsing ("parse_Element" for an Element node,
"parse_Text" for a Text node, etc.) and then calls the method.
"""
parseMethod = getattr(self, "parse_%s" % node.__class__.__name__)
parseMethod(node)
|
[
"parse",
"a",
"single",
"XML",
"node",
"A",
"parsed",
"XML",
"document",
"(",
"from",
"minidom",
".",
"parse",
")",
"is",
"a",
"tree",
"of",
"nodes",
"of",
"various",
"types",
".",
"Each",
"node",
"is",
"represented",
"by",
"an",
"instance",
"of",
"the",
"corresponding",
"Python",
"class",
"(",
"Element",
"for",
"a",
"tag",
"Text",
"for",
"text",
"data",
"Document",
"for",
"the",
"top",
"-",
"level",
"document",
")",
".",
"The",
"following",
"statement",
"constructs",
"the",
"name",
"of",
"a",
"class",
"method",
"based",
"on",
"the",
"type",
"of",
"node",
"we",
"re",
"parsing",
"(",
"parse_Element",
"for",
"an",
"Element",
"node",
"parse_Text",
"for",
"a",
"Text",
"node",
"etc",
".",
")",
"and",
"then",
"calls",
"the",
"method",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L176-L188
|
[
"def",
"parse",
"(",
"self",
",",
"node",
")",
":",
"parseMethod",
"=",
"getattr",
"(",
"self",
",",
"\"parse_%s\"",
"%",
"node",
".",
"__class__",
".",
"__name__",
")",
"parseMethod",
"(",
"node",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.parse_Text
|
parse a text node
The text of a text node is usually added to the output buffer
verbatim. The one exception is that <p class='sentence'> sets
a flag to capitalize the first letter of the next word. If
that flag is set, we capitalize the text and reset the flag.
|
shoebot/kgp.py
|
def parse_Text(self, node):
"""parse a text node
The text of a text node is usually added to the output buffer
verbatim. The one exception is that <p class='sentence'> sets
a flag to capitalize the first letter of the next word. If
that flag is set, we capitalize the text and reset the flag.
"""
text = node.data
if self.capitalizeNextWord:
self.pieces.append(text[0].upper())
self.pieces.append(text[1:])
self.capitalizeNextWord = 0
else:
self.pieces.append(text)
|
def parse_Text(self, node):
"""parse a text node
The text of a text node is usually added to the output buffer
verbatim. The one exception is that <p class='sentence'> sets
a flag to capitalize the first letter of the next word. If
that flag is set, we capitalize the text and reset the flag.
"""
text = node.data
if self.capitalizeNextWord:
self.pieces.append(text[0].upper())
self.pieces.append(text[1:])
self.capitalizeNextWord = 0
else:
self.pieces.append(text)
|
[
"parse",
"a",
"text",
"node",
"The",
"text",
"of",
"a",
"text",
"node",
"is",
"usually",
"added",
"to",
"the",
"output",
"buffer",
"verbatim",
".",
"The",
"one",
"exception",
"is",
"that",
"<p",
"class",
"=",
"sentence",
">",
"sets",
"a",
"flag",
"to",
"capitalize",
"the",
"first",
"letter",
"of",
"the",
"next",
"word",
".",
"If",
"that",
"flag",
"is",
"set",
"we",
"capitalize",
"the",
"text",
"and",
"reset",
"the",
"flag",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L199-L213
|
[
"def",
"parse_Text",
"(",
"self",
",",
"node",
")",
":",
"text",
"=",
"node",
".",
"data",
"if",
"self",
".",
"capitalizeNextWord",
":",
"self",
".",
"pieces",
".",
"append",
"(",
"text",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
"self",
".",
"pieces",
".",
"append",
"(",
"text",
"[",
"1",
":",
"]",
")",
"self",
".",
"capitalizeNextWord",
"=",
"0",
"else",
":",
"self",
".",
"pieces",
".",
"append",
"(",
"text",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.parse_Element
|
parse an element
An XML element corresponds to an actual tag in the source:
<xref id='...'>, <p chance='...'>, <choice>, etc.
Each element type is handled in its own method. Like we did in
parse(), we construct a method name based on the name of the
element ("do_xref" for an <xref> tag, etc.) and
call the method.
|
shoebot/kgp.py
|
def parse_Element(self, node):
"""parse an element
An XML element corresponds to an actual tag in the source:
<xref id='...'>, <p chance='...'>, <choice>, etc.
Each element type is handled in its own method. Like we did in
parse(), we construct a method name based on the name of the
element ("do_xref" for an <xref> tag, etc.) and
call the method.
"""
handlerMethod = getattr(self, "do_%s" % node.tagName)
handlerMethod(node)
|
def parse_Element(self, node):
"""parse an element
An XML element corresponds to an actual tag in the source:
<xref id='...'>, <p chance='...'>, <choice>, etc.
Each element type is handled in its own method. Like we did in
parse(), we construct a method name based on the name of the
element ("do_xref" for an <xref> tag, etc.) and
call the method.
"""
handlerMethod = getattr(self, "do_%s" % node.tagName)
handlerMethod(node)
|
[
"parse",
"an",
"element",
"An",
"XML",
"element",
"corresponds",
"to",
"an",
"actual",
"tag",
"in",
"the",
"source",
":",
"<xref",
"id",
"=",
"...",
">",
"<p",
"chance",
"=",
"...",
">",
"<choice",
">",
"etc",
".",
"Each",
"element",
"type",
"is",
"handled",
"in",
"its",
"own",
"method",
".",
"Like",
"we",
"did",
"in",
"parse",
"()",
"we",
"construct",
"a",
"method",
"name",
"based",
"on",
"the",
"name",
"of",
"the",
"element",
"(",
"do_xref",
"for",
"an",
"<xref",
">",
"tag",
"etc",
".",
")",
"and",
"call",
"the",
"method",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L215-L226
|
[
"def",
"parse_Element",
"(",
"self",
",",
"node",
")",
":",
"handlerMethod",
"=",
"getattr",
"(",
"self",
",",
"\"do_%s\"",
"%",
"node",
".",
"tagName",
")",
"handlerMethod",
"(",
"node",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.do_xref
|
handle <xref id='...'> tag
An <xref id='...'> tag is a cross-reference to a <ref id='...'>
tag. <xref id='sentence'/> evaluates to a randomly chosen child of
<ref id='sentence'>.
|
shoebot/kgp.py
|
def do_xref(self, node):
"""handle <xref id='...'> tag
An <xref id='...'> tag is a cross-reference to a <ref id='...'>
tag. <xref id='sentence'/> evaluates to a randomly chosen child of
<ref id='sentence'>.
"""
id = node.attributes["id"].value
self.parse(self.randomChildElement(self.refs[id]))
|
def do_xref(self, node):
"""handle <xref id='...'> tag
An <xref id='...'> tag is a cross-reference to a <ref id='...'>
tag. <xref id='sentence'/> evaluates to a randomly chosen child of
<ref id='sentence'>.
"""
id = node.attributes["id"].value
self.parse(self.randomChildElement(self.refs[id]))
|
[
"handle",
"<xref",
"id",
"=",
"...",
">",
"tag",
"An",
"<xref",
"id",
"=",
"...",
">",
"tag",
"is",
"a",
"cross",
"-",
"reference",
"to",
"a",
"<ref",
"id",
"=",
"...",
">",
"tag",
".",
"<xref",
"id",
"=",
"sentence",
"/",
">",
"evaluates",
"to",
"a",
"randomly",
"chosen",
"child",
"of",
"<ref",
"id",
"=",
"sentence",
">",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L235-L243
|
[
"def",
"do_xref",
"(",
"self",
",",
"node",
")",
":",
"id",
"=",
"node",
".",
"attributes",
"[",
"\"id\"",
"]",
".",
"value",
"self",
".",
"parse",
"(",
"self",
".",
"randomChildElement",
"(",
"self",
".",
"refs",
"[",
"id",
"]",
")",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
KantGenerator.do_p
|
handle <p> tag
The <p> tag is the core of the grammar. It can contain almost
anything: freeform text, <choice> tags, <xref> tags, even other
<p> tags. If a "class='sentence'" attribute is found, a flag
is set and the next word will be capitalized. If a "chance='X'"
attribute is found, there is an X% chance that the tag will be
evaluated (and therefore a (100-X)% chance that it will be
completely ignored)
|
shoebot/kgp.py
|
def do_p(self, node):
"""handle <p> tag
The <p> tag is the core of the grammar. It can contain almost
anything: freeform text, <choice> tags, <xref> tags, even other
<p> tags. If a "class='sentence'" attribute is found, a flag
is set and the next word will be capitalized. If a "chance='X'"
attribute is found, there is an X% chance that the tag will be
evaluated (and therefore a (100-X)% chance that it will be
completely ignored)
"""
keys = node.attributes.keys()
if "class" in keys:
if node.attributes["class"].value == "sentence":
self.capitalizeNextWord = 1
if "chance" in keys:
chance = int(node.attributes["chance"].value)
doit = (chance > random.randrange(100))
else:
doit = 1
if doit:
for child in node.childNodes: self.parse(child)
|
def do_p(self, node):
"""handle <p> tag
The <p> tag is the core of the grammar. It can contain almost
anything: freeform text, <choice> tags, <xref> tags, even other
<p> tags. If a "class='sentence'" attribute is found, a flag
is set and the next word will be capitalized. If a "chance='X'"
attribute is found, there is an X% chance that the tag will be
evaluated (and therefore a (100-X)% chance that it will be
completely ignored)
"""
keys = node.attributes.keys()
if "class" in keys:
if node.attributes["class"].value == "sentence":
self.capitalizeNextWord = 1
if "chance" in keys:
chance = int(node.attributes["chance"].value)
doit = (chance > random.randrange(100))
else:
doit = 1
if doit:
for child in node.childNodes: self.parse(child)
|
[
"handle",
"<p",
">",
"tag",
"The",
"<p",
">",
"tag",
"is",
"the",
"core",
"of",
"the",
"grammar",
".",
"It",
"can",
"contain",
"almost",
"anything",
":",
"freeform",
"text",
"<choice",
">",
"tags",
"<xref",
">",
"tags",
"even",
"other",
"<p",
">",
"tags",
".",
"If",
"a",
"class",
"=",
"sentence",
"attribute",
"is",
"found",
"a",
"flag",
"is",
"set",
"and",
"the",
"next",
"word",
"will",
"be",
"capitalized",
".",
"If",
"a",
"chance",
"=",
"X",
"attribute",
"is",
"found",
"there",
"is",
"an",
"X%",
"chance",
"that",
"the",
"tag",
"will",
"be",
"evaluated",
"(",
"and",
"therefore",
"a",
"(",
"100",
"-",
"X",
")",
"%",
"chance",
"that",
"it",
"will",
"be",
"completely",
"ignored",
")"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L245-L266
|
[
"def",
"do_p",
"(",
"self",
",",
"node",
")",
":",
"keys",
"=",
"node",
".",
"attributes",
".",
"keys",
"(",
")",
"if",
"\"class\"",
"in",
"keys",
":",
"if",
"node",
".",
"attributes",
"[",
"\"class\"",
"]",
".",
"value",
"==",
"\"sentence\"",
":",
"self",
".",
"capitalizeNextWord",
"=",
"1",
"if",
"\"chance\"",
"in",
"keys",
":",
"chance",
"=",
"int",
"(",
"node",
".",
"attributes",
"[",
"\"chance\"",
"]",
".",
"value",
")",
"doit",
"=",
"(",
"chance",
">",
"random",
".",
"randrange",
"(",
"100",
")",
")",
"else",
":",
"doit",
"=",
"1",
"if",
"doit",
":",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"self",
".",
"parse",
"(",
"child",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
replace_entities
|
Replaces HTML special characters by readable characters.
As taken from Leif K-Brooks algorithm on:
http://groups-beta.google.com/group/comp.lang.python
|
lib/web/html.py
|
def replace_entities(ustring, placeholder=" "):
"""Replaces HTML special characters by readable characters.
As taken from Leif K-Brooks algorithm on:
http://groups-beta.google.com/group/comp.lang.python
"""
def _repl_func(match):
try:
if match.group(1): # Numeric character reference
return unichr( int(match.group(2)) )
else:
try: return cp1252[ unichr(int(match.group(3))) ].strip()
except: return unichr( name2codepoint[match.group(3)] )
except:
return placeholder
# Force to Unicode.
if not isinstance(ustring, unicode):
ustring = UnicodeDammit(ustring).unicode
# Don't want some weird unicode character here
# that truncate_spaces() doesn't know of:
ustring = ustring.replace(" ", " ")
# The ^> makes sure nothing inside a tag (i.e. href with query arguments) gets processed.
_entity_re = re.compile(r'&(?:(#)(\d+)|([^;^> ]+));')
return _entity_re.sub(_repl_func, ustring)
|
def replace_entities(ustring, placeholder=" "):
"""Replaces HTML special characters by readable characters.
As taken from Leif K-Brooks algorithm on:
http://groups-beta.google.com/group/comp.lang.python
"""
def _repl_func(match):
try:
if match.group(1): # Numeric character reference
return unichr( int(match.group(2)) )
else:
try: return cp1252[ unichr(int(match.group(3))) ].strip()
except: return unichr( name2codepoint[match.group(3)] )
except:
return placeholder
# Force to Unicode.
if not isinstance(ustring, unicode):
ustring = UnicodeDammit(ustring).unicode
# Don't want some weird unicode character here
# that truncate_spaces() doesn't know of:
ustring = ustring.replace(" ", " ")
# The ^> makes sure nothing inside a tag (i.e. href with query arguments) gets processed.
_entity_re = re.compile(r'&(?:(#)(\d+)|([^;^> ]+));')
return _entity_re.sub(_repl_func, ustring)
|
[
"Replaces",
"HTML",
"special",
"characters",
"by",
"readable",
"characters",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/html.py#L51-L80
|
[
"def",
"replace_entities",
"(",
"ustring",
",",
"placeholder",
"=",
"\" \"",
")",
":",
"def",
"_repl_func",
"(",
"match",
")",
":",
"try",
":",
"if",
"match",
".",
"group",
"(",
"1",
")",
":",
"# Numeric character reference",
"return",
"unichr",
"(",
"int",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"else",
":",
"try",
":",
"return",
"cp1252",
"[",
"unichr",
"(",
"int",
"(",
"match",
".",
"group",
"(",
"3",
")",
")",
")",
"]",
".",
"strip",
"(",
")",
"except",
":",
"return",
"unichr",
"(",
"name2codepoint",
"[",
"match",
".",
"group",
"(",
"3",
")",
"]",
")",
"except",
":",
"return",
"placeholder",
"# Force to Unicode.",
"if",
"not",
"isinstance",
"(",
"ustring",
",",
"unicode",
")",
":",
"ustring",
"=",
"UnicodeDammit",
"(",
"ustring",
")",
".",
"unicode",
"# Don't want some weird unicode character here",
"# that truncate_spaces() doesn't know of:",
"ustring",
"=",
"ustring",
".",
"replace",
"(",
"\" \"",
",",
"\" \"",
")",
"# The ^> makes sure nothing inside a tag (i.e. href with query arguments) gets processed.",
"_entity_re",
"=",
"re",
".",
"compile",
"(",
"r'&(?:(#)(\\d+)|([^;^> ]+));'",
")",
"return",
"_entity_re",
".",
"sub",
"(",
"_repl_func",
",",
"ustring",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
open
|
Returns a connection to a url which you can read().
When the wait amount is exceeded, raises a URLTimeout.
When an error occurs, raises a URLError.
404 errors specifically return a HTTP404NotFound.
|
lib/web/url.py
|
def open(url, wait=10):
""" Returns a connection to a url which you can read().
When the wait amount is exceeded, raises a URLTimeout.
When an error occurs, raises a URLError.
404 errors specifically return a HTTP404NotFound.
"""
# If the url is a URLParser, get any POST parameters.
post = None
if isinstance(url, URLParser) and url.method == "post":
post = urllib.urlencode(url.query)
# If the url is a URLParser (or a YahooResult or something),
# use its string representation.
url = str(url)
# Use urllib instead of urllib2 for local files.
if os.path.exists(url):
return urllib.urlopen(url)
else:
socket.setdefaulttimeout(wait)
try:
#connection = urllib2.urlopen(url, post)
request = urllib2.Request(url, post, {"User-Agent": USER_AGENT, "Referer": REFERER})
if PROXY:
p = urllib2.ProxyHandler({PROXY[1]: PROXY[0]})
o = urllib2.build_opener(p, urllib2.HTTPHandler)
urllib2.install_opener(o)
connection = urllib2.urlopen(request)
except urllib2.HTTPError, e:
if e.code == 401: raise HTTP401Authentication
if e.code == 403: raise HTTP403Forbidden
if e.code == 404: raise HTTP404NotFound
raise HTTPError
except urllib2.URLError, e:
if e.reason[0] == 36: raise URLTimeout
raise URLError
return connection
|
def open(url, wait=10):
""" Returns a connection to a url which you can read().
When the wait amount is exceeded, raises a URLTimeout.
When an error occurs, raises a URLError.
404 errors specifically return a HTTP404NotFound.
"""
# If the url is a URLParser, get any POST parameters.
post = None
if isinstance(url, URLParser) and url.method == "post":
post = urllib.urlencode(url.query)
# If the url is a URLParser (or a YahooResult or something),
# use its string representation.
url = str(url)
# Use urllib instead of urllib2 for local files.
if os.path.exists(url):
return urllib.urlopen(url)
else:
socket.setdefaulttimeout(wait)
try:
#connection = urllib2.urlopen(url, post)
request = urllib2.Request(url, post, {"User-Agent": USER_AGENT, "Referer": REFERER})
if PROXY:
p = urllib2.ProxyHandler({PROXY[1]: PROXY[0]})
o = urllib2.build_opener(p, urllib2.HTTPHandler)
urllib2.install_opener(o)
connection = urllib2.urlopen(request)
except urllib2.HTTPError, e:
if e.code == 401: raise HTTP401Authentication
if e.code == 403: raise HTTP403Forbidden
if e.code == 404: raise HTTP404NotFound
raise HTTPError
except urllib2.URLError, e:
if e.reason[0] == 36: raise URLTimeout
raise URLError
return connection
|
[
"Returns",
"a",
"connection",
"to",
"a",
"url",
"which",
"you",
"can",
"read",
"()",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/url.py#L181-L223
|
[
"def",
"open",
"(",
"url",
",",
"wait",
"=",
"10",
")",
":",
"# If the url is a URLParser, get any POST parameters.",
"post",
"=",
"None",
"if",
"isinstance",
"(",
"url",
",",
"URLParser",
")",
"and",
"url",
".",
"method",
"==",
"\"post\"",
":",
"post",
"=",
"urllib",
".",
"urlencode",
"(",
"url",
".",
"query",
")",
"# If the url is a URLParser (or a YahooResult or something),",
"# use its string representation.",
"url",
"=",
"str",
"(",
"url",
")",
"# Use urllib instead of urllib2 for local files.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"url",
")",
":",
"return",
"urllib",
".",
"urlopen",
"(",
"url",
")",
"else",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"wait",
")",
"try",
":",
"#connection = urllib2.urlopen(url, post)",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"post",
",",
"{",
"\"User-Agent\"",
":",
"USER_AGENT",
",",
"\"Referer\"",
":",
"REFERER",
"}",
")",
"if",
"PROXY",
":",
"p",
"=",
"urllib2",
".",
"ProxyHandler",
"(",
"{",
"PROXY",
"[",
"1",
"]",
":",
"PROXY",
"[",
"0",
"]",
"}",
")",
"o",
"=",
"urllib2",
".",
"build_opener",
"(",
"p",
",",
"urllib2",
".",
"HTTPHandler",
")",
"urllib2",
".",
"install_opener",
"(",
"o",
")",
"connection",
"=",
"urllib2",
".",
"urlopen",
"(",
"request",
")",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"if",
"e",
".",
"code",
"==",
"401",
":",
"raise",
"HTTP401Authentication",
"if",
"e",
".",
"code",
"==",
"403",
":",
"raise",
"HTTP403Forbidden",
"if",
"e",
".",
"code",
"==",
"404",
":",
"raise",
"HTTP404NotFound",
"raise",
"HTTPError",
"except",
"urllib2",
".",
"URLError",
",",
"e",
":",
"if",
"e",
".",
"reason",
"[",
"0",
"]",
"==",
"36",
":",
"raise",
"URLTimeout",
"raise",
"URLError",
"return",
"connection"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
not_found
|
Returns True when the url generates a "404 Not Found" error.
|
lib/web/url.py
|
def not_found(url, wait=10):
""" Returns True when the url generates a "404 Not Found" error.
"""
try: connection = open(url, wait)
except HTTP404NotFound:
return True
except:
return False
return False
|
def not_found(url, wait=10):
""" Returns True when the url generates a "404 Not Found" error.
"""
try: connection = open(url, wait)
except HTTP404NotFound:
return True
except:
return False
return False
|
[
"Returns",
"True",
"when",
"the",
"url",
"generates",
"a",
"404",
"Not",
"Found",
"error",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/url.py#L246-L257
|
[
"def",
"not_found",
"(",
"url",
",",
"wait",
"=",
"10",
")",
":",
"try",
":",
"connection",
"=",
"open",
"(",
"url",
",",
"wait",
")",
"except",
"HTTP404NotFound",
":",
"return",
"True",
"except",
":",
"return",
"False",
"return",
"False"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
is_type
|
Determine the MIME-type of the document behind the url.
MIME is more reliable than simply checking the document extension.
Returns True when the MIME-type starts with anything in the list of types.
|
lib/web/url.py
|
def is_type(url, types=[], wait=10):
""" Determine the MIME-type of the document behind the url.
MIME is more reliable than simply checking the document extension.
Returns True when the MIME-type starts with anything in the list of types.
"""
# Types can also be a single string for convenience.
if isinstance(types, str):
types = [types]
try: connection = open(url, wait)
except:
return False
type = connection.info()["Content-Type"]
for t in types:
if type.startswith(t): return True
return False
|
def is_type(url, types=[], wait=10):
""" Determine the MIME-type of the document behind the url.
MIME is more reliable than simply checking the document extension.
Returns True when the MIME-type starts with anything in the list of types.
"""
# Types can also be a single string for convenience.
if isinstance(types, str):
types = [types]
try: connection = open(url, wait)
except:
return False
type = connection.info()["Content-Type"]
for t in types:
if type.startswith(t): return True
return False
|
[
"Determine",
"the",
"MIME",
"-",
"type",
"of",
"the",
"document",
"behind",
"the",
"url",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/url.py#L267-L288
|
[
"def",
"is_type",
"(",
"url",
",",
"types",
"=",
"[",
"]",
",",
"wait",
"=",
"10",
")",
":",
"# Types can also be a single string for convenience.",
"if",
"isinstance",
"(",
"types",
",",
"str",
")",
":",
"types",
"=",
"[",
"types",
"]",
"try",
":",
"connection",
"=",
"open",
"(",
"url",
",",
"wait",
")",
"except",
":",
"return",
"False",
"type",
"=",
"connection",
".",
"info",
"(",
")",
"[",
"\"Content-Type\"",
"]",
"for",
"t",
"in",
"types",
":",
"if",
"type",
".",
"startswith",
"(",
"t",
")",
":",
"return",
"True",
"return",
"False"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
requirements
|
Build requirements based on flags
:param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere
:param with_examples:
:return:
|
setup.py
|
def requirements(debug=True, with_examples=True, with_pgi=None):
"""
Build requirements based on flags
:param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere
:param with_examples:
:return:
"""
reqs = list(BASE_REQUIREMENTS)
if with_pgi is None:
with_pgi = is_jython
if debug:
print("setup options: ")
print("with_pgi: ", "yes" if with_pgi else "no")
print("with_examples: ", "yes" if with_examples else "no")
if with_pgi:
reqs.append("pgi")
if debug:
print("warning, as of April 2019 typography does not work with pgi")
else:
reqs.append(PYGOBJECT)
if with_examples:
reqs.extend(EXAMPLE_REQUIREMENTS)
if debug:
print("")
print("")
for req in reqs:
print(req)
return reqs
|
def requirements(debug=True, with_examples=True, with_pgi=None):
"""
Build requirements based on flags
:param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere
:param with_examples:
:return:
"""
reqs = list(BASE_REQUIREMENTS)
if with_pgi is None:
with_pgi = is_jython
if debug:
print("setup options: ")
print("with_pgi: ", "yes" if with_pgi else "no")
print("with_examples: ", "yes" if with_examples else "no")
if with_pgi:
reqs.append("pgi")
if debug:
print("warning, as of April 2019 typography does not work with pgi")
else:
reqs.append(PYGOBJECT)
if with_examples:
reqs.extend(EXAMPLE_REQUIREMENTS)
if debug:
print("")
print("")
for req in reqs:
print(req)
return reqs
|
[
"Build",
"requirements",
"based",
"on",
"flags"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/setup.py#L141-L172
|
[
"def",
"requirements",
"(",
"debug",
"=",
"True",
",",
"with_examples",
"=",
"True",
",",
"with_pgi",
"=",
"None",
")",
":",
"reqs",
"=",
"list",
"(",
"BASE_REQUIREMENTS",
")",
"if",
"with_pgi",
"is",
"None",
":",
"with_pgi",
"=",
"is_jython",
"if",
"debug",
":",
"print",
"(",
"\"setup options: \"",
")",
"print",
"(",
"\"with_pgi: \"",
",",
"\"yes\"",
"if",
"with_pgi",
"else",
"\"no\"",
")",
"print",
"(",
"\"with_examples: \"",
",",
"\"yes\"",
"if",
"with_examples",
"else",
"\"no\"",
")",
"if",
"with_pgi",
":",
"reqs",
".",
"append",
"(",
"\"pgi\"",
")",
"if",
"debug",
":",
"print",
"(",
"\"warning, as of April 2019 typography does not work with pgi\"",
")",
"else",
":",
"reqs",
".",
"append",
"(",
"PYGOBJECT",
")",
"if",
"with_examples",
":",
"reqs",
".",
"extend",
"(",
"EXAMPLE_REQUIREMENTS",
")",
"if",
"debug",
":",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"\"",
")",
"for",
"req",
"in",
"reqs",
":",
"print",
"(",
"req",
")",
"return",
"reqs"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.image
|
Draws a image form path, in x,y and resize it to width, height dimensions.
|
shoebot/grammar/nodebox.py
|
def image(self, path, x, y, width=None, height=None, alpha=1.0, data=None, draw=True, **kwargs):
'''Draws a image form path, in x,y and resize it to width, height dimensions.
'''
return self.Image(path, x, y, width, height, alpha, data, **kwargs)
|
def image(self, path, x, y, width=None, height=None, alpha=1.0, data=None, draw=True, **kwargs):
'''Draws a image form path, in x,y and resize it to width, height dimensions.
'''
return self.Image(path, x, y, width, height, alpha, data, **kwargs)
|
[
"Draws",
"a",
"image",
"form",
"path",
"in",
"x",
"y",
"and",
"resize",
"it",
"to",
"width",
"height",
"dimensions",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L75-L78
|
[
"def",
"image",
"(",
"self",
",",
"path",
",",
"x",
",",
"y",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"alpha",
"=",
"1.0",
",",
"data",
"=",
"None",
",",
"draw",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"Image",
"(",
"path",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"alpha",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.rect
|
Draw a rectangle from x, y of width, height.
:param startx: top left x-coordinate
:param starty: top left y-coordinate
:param width: height Size of rectangle.
:roundness: Corner roundness defaults to 0.0 (a right-angle).
:draw: If True draws immediately.
:fill: Optionally pass a fill color.
:return: path representing the rectangle.
|
shoebot/grammar/nodebox.py
|
def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):
'''
Draw a rectangle from x, y of width, height.
:param startx: top left x-coordinate
:param starty: top left y-coordinate
:param width: height Size of rectangle.
:roundness: Corner roundness defaults to 0.0 (a right-angle).
:draw: If True draws immediately.
:fill: Optionally pass a fill color.
:return: path representing the rectangle.
'''
path = self.BezierPath(**kwargs)
path.rect(x, y, width, height, roundness, self.rectmode)
if draw:
path.draw()
return path
|
def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):
'''
Draw a rectangle from x, y of width, height.
:param startx: top left x-coordinate
:param starty: top left y-coordinate
:param width: height Size of rectangle.
:roundness: Corner roundness defaults to 0.0 (a right-angle).
:draw: If True draws immediately.
:fill: Optionally pass a fill color.
:return: path representing the rectangle.
'''
path = self.BezierPath(**kwargs)
path.rect(x, y, width, height, roundness, self.rectmode)
if draw:
path.draw()
return path
|
[
"Draw",
"a",
"rectangle",
"from",
"x",
"y",
"of",
"width",
"height",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L90-L109
|
[
"def",
"rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"roundness",
"=",
"0.0",
",",
"draw",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"BezierPath",
"(",
"*",
"*",
"kwargs",
")",
"path",
".",
"rect",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"roundness",
",",
"self",
".",
"rectmode",
")",
"if",
"draw",
":",
"path",
".",
"draw",
"(",
")",
"return",
"path"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.rectmode
|
Set the current rectmode.
:param mode: CORNER, CENTER, CORNERS
:return: rectmode if mode is None or valid.
|
shoebot/grammar/nodebox.py
|
def rectmode(self, mode=None):
'''
Set the current rectmode.
:param mode: CORNER, CENTER, CORNERS
:return: rectmode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.rectmode = mode
return self.rectmode
elif mode is None:
return self.rectmode
else:
raise ShoebotError(_("rectmode: invalid input"))
|
def rectmode(self, mode=None):
'''
Set the current rectmode.
:param mode: CORNER, CENTER, CORNERS
:return: rectmode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.rectmode = mode
return self.rectmode
elif mode is None:
return self.rectmode
else:
raise ShoebotError(_("rectmode: invalid input"))
|
[
"Set",
"the",
"current",
"rectmode",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L111-L124
|
[
"def",
"rectmode",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"in",
"(",
"self",
".",
"CORNER",
",",
"self",
".",
"CENTER",
",",
"self",
".",
"CORNERS",
")",
":",
"self",
".",
"rectmode",
"=",
"mode",
"return",
"self",
".",
"rectmode",
"elif",
"mode",
"is",
"None",
":",
"return",
"self",
".",
"rectmode",
"else",
":",
"raise",
"ShoebotError",
"(",
"_",
"(",
"\"rectmode: invalid input\"",
")",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.ellipsemode
|
Set the current ellipse drawing mode.
:param mode: CORNER, CENTER, CORNERS
:return: ellipsemode if mode is None or valid.
|
shoebot/grammar/nodebox.py
|
def ellipsemode(self, mode=None):
'''
Set the current ellipse drawing mode.
:param mode: CORNER, CENTER, CORNERS
:return: ellipsemode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.ellipsemode = mode
return self.ellipsemode
elif mode is None:
return self.ellipsemode
else:
raise ShoebotError(_("ellipsemode: invalid input"))
|
def ellipsemode(self, mode=None):
'''
Set the current ellipse drawing mode.
:param mode: CORNER, CENTER, CORNERS
:return: ellipsemode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.ellipsemode = mode
return self.ellipsemode
elif mode is None:
return self.ellipsemode
else:
raise ShoebotError(_("ellipsemode: invalid input"))
|
[
"Set",
"the",
"current",
"ellipse",
"drawing",
"mode",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L126-L139
|
[
"def",
"ellipsemode",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"in",
"(",
"self",
".",
"CORNER",
",",
"self",
".",
"CENTER",
",",
"self",
".",
"CORNERS",
")",
":",
"self",
".",
"ellipsemode",
"=",
"mode",
"return",
"self",
".",
"ellipsemode",
"elif",
"mode",
"is",
"None",
":",
"return",
"self",
".",
"ellipsemode",
"else",
":",
"raise",
"ShoebotError",
"(",
"_",
"(",
"\"ellipsemode: invalid input\"",
")",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.circle
|
Draw a circle
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
:param diameter: Diameter of circle.
:param draw: Draw immediately (defaults to True, set to False to inhibit drawing)
:return: Path object representing circle
|
shoebot/grammar/nodebox.py
|
def circle(self, x, y, diameter, draw=True, **kwargs):
'''Draw a circle
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
:param diameter: Diameter of circle.
:param draw: Draw immediately (defaults to True, set to False to inhibit drawing)
:return: Path object representing circle
'''
return self.ellipse(x, y, diameter, diameter, draw, **kwargs)
|
def circle(self, x, y, diameter, draw=True, **kwargs):
'''Draw a circle
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
:param diameter: Diameter of circle.
:param draw: Draw immediately (defaults to True, set to False to inhibit drawing)
:return: Path object representing circle
'''
return self.ellipse(x, y, diameter, diameter, draw, **kwargs)
|
[
"Draw",
"a",
"circle",
":",
"param",
"x",
":",
"x",
"-",
"coordinate",
"of",
"the",
"top",
"left",
"corner",
":",
"param",
"y",
":",
"y",
"-",
"coordinate",
"of",
"the",
"top",
"left",
"corner",
":",
"param",
"diameter",
":",
"Diameter",
"of",
"circle",
".",
":",
"param",
"draw",
":",
"Draw",
"immediately",
"(",
"defaults",
"to",
"True",
"set",
"to",
"False",
"to",
"inhibit",
"drawing",
")",
":",
"return",
":",
"Path",
"object",
"representing",
"circle"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L157-L165
|
[
"def",
"circle",
"(",
"self",
",",
"x",
",",
"y",
",",
"diameter",
",",
"draw",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"ellipse",
"(",
"x",
",",
"y",
",",
"diameter",
",",
"diameter",
",",
"draw",
",",
"*",
"*",
"kwargs",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.arrow
|
Draw an arrow.
Arrows can be two types: NORMAL or FORTYFIVE.
:param x: top left x-coordinate
:param y: top left y-coordinate
:param width: width of arrow
:param type: NORMAL or FORTYFIVE
:draw: If True draws arrow immediately
:return: Path object representing the arrow.
|
shoebot/grammar/nodebox.py
|
def arrow(self, x, y, width, type=NORMAL, draw=True, **kwargs):
'''Draw an arrow.
Arrows can be two types: NORMAL or FORTYFIVE.
:param x: top left x-coordinate
:param y: top left y-coordinate
:param width: width of arrow
:param type: NORMAL or FORTYFIVE
:draw: If True draws arrow immediately
:return: Path object representing the arrow.
'''
# Taken from Nodebox
path = self.BezierPath(**kwargs)
if type == self.NORMAL:
head = width * .4
tail = width * .2
path.moveto(x, y)
path.lineto(x - head, y + head)
path.lineto(x - head, y + tail)
path.lineto(x - width, y + tail)
path.lineto(x - width, y - tail)
path.lineto(x - head, y - tail)
path.lineto(x - head, y - head)
path.lineto(x, y)
elif type == self.FORTYFIVE:
head = .3
tail = 1 + head
path.moveto(x, y)
path.lineto(x, y + width * (1 - head))
path.lineto(x - width * head, y + width)
path.lineto(x - width * head, y + width * tail * .4)
path.lineto(x - width * tail * .6, y + width)
path.lineto(x - width, y + width * tail * .6)
path.lineto(x - width * tail * .4, y + width * head)
path.lineto(x - width, y + width * head)
path.lineto(x - width * (1 - head), y)
path.lineto(x, y)
else:
raise NameError(_("arrow: available types for arrow() are NORMAL and FORTYFIVE\n"))
if draw:
path.draw()
return path
|
def arrow(self, x, y, width, type=NORMAL, draw=True, **kwargs):
'''Draw an arrow.
Arrows can be two types: NORMAL or FORTYFIVE.
:param x: top left x-coordinate
:param y: top left y-coordinate
:param width: width of arrow
:param type: NORMAL or FORTYFIVE
:draw: If True draws arrow immediately
:return: Path object representing the arrow.
'''
# Taken from Nodebox
path = self.BezierPath(**kwargs)
if type == self.NORMAL:
head = width * .4
tail = width * .2
path.moveto(x, y)
path.lineto(x - head, y + head)
path.lineto(x - head, y + tail)
path.lineto(x - width, y + tail)
path.lineto(x - width, y - tail)
path.lineto(x - head, y - tail)
path.lineto(x - head, y - head)
path.lineto(x, y)
elif type == self.FORTYFIVE:
head = .3
tail = 1 + head
path.moveto(x, y)
path.lineto(x, y + width * (1 - head))
path.lineto(x - width * head, y + width)
path.lineto(x - width * head, y + width * tail * .4)
path.lineto(x - width * tail * .6, y + width)
path.lineto(x - width, y + width * tail * .6)
path.lineto(x - width * tail * .4, y + width * head)
path.lineto(x - width, y + width * head)
path.lineto(x - width * (1 - head), y)
path.lineto(x, y)
else:
raise NameError(_("arrow: available types for arrow() are NORMAL and FORTYFIVE\n"))
if draw:
path.draw()
return path
|
[
"Draw",
"an",
"arrow",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L182-L225
|
[
"def",
"arrow",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"type",
"=",
"NORMAL",
",",
"draw",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Taken from Nodebox",
"path",
"=",
"self",
".",
"BezierPath",
"(",
"*",
"*",
"kwargs",
")",
"if",
"type",
"==",
"self",
".",
"NORMAL",
":",
"head",
"=",
"width",
"*",
".4",
"tail",
"=",
"width",
"*",
".2",
"path",
".",
"moveto",
"(",
"x",
",",
"y",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"head",
",",
"y",
"+",
"head",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"head",
",",
"y",
"+",
"tail",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
",",
"y",
"+",
"tail",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
",",
"y",
"-",
"tail",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"head",
",",
"y",
"-",
"tail",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"head",
",",
"y",
"-",
"head",
")",
"path",
".",
"lineto",
"(",
"x",
",",
"y",
")",
"elif",
"type",
"==",
"self",
".",
"FORTYFIVE",
":",
"head",
"=",
".3",
"tail",
"=",
"1",
"+",
"head",
"path",
".",
"moveto",
"(",
"x",
",",
"y",
")",
"path",
".",
"lineto",
"(",
"x",
",",
"y",
"+",
"width",
"*",
"(",
"1",
"-",
"head",
")",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
"*",
"head",
",",
"y",
"+",
"width",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
"*",
"head",
",",
"y",
"+",
"width",
"*",
"tail",
"*",
".4",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
"*",
"tail",
"*",
".6",
",",
"y",
"+",
"width",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
",",
"y",
"+",
"width",
"*",
"tail",
"*",
".6",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
"*",
"tail",
"*",
".4",
",",
"y",
"+",
"width",
"*",
"head",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
",",
"y",
"+",
"width",
"*",
"head",
")",
"path",
".",
"lineto",
"(",
"x",
"-",
"width",
"*",
"(",
"1",
"-",
"head",
")",
",",
"y",
")",
"path",
".",
"lineto",
"(",
"x",
",",
"y",
")",
"else",
":",
"raise",
"NameError",
"(",
"_",
"(",
"\"arrow: available types for arrow() are NORMAL and FORTYFIVE\\n\"",
")",
")",
"if",
"draw",
":",
"path",
".",
"draw",
"(",
")",
"return",
"path"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.star
|
Draws a star.
|
shoebot/grammar/nodebox.py
|
def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs):
'''Draws a star.
'''
# Taken from Nodebox.
self.beginpath(**kwargs)
self.moveto(startx, starty + outer)
for i in range(1, int(2 * points)):
angle = i * pi / points
x = sin(angle)
y = cos(angle)
if i % 2:
radius = inner
else:
radius = outer
x = startx + radius * x
y = starty + radius * y
self.lineto(x, y)
return self.endpath(draw)
|
def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs):
'''Draws a star.
'''
# Taken from Nodebox.
self.beginpath(**kwargs)
self.moveto(startx, starty + outer)
for i in range(1, int(2 * points)):
angle = i * pi / points
x = sin(angle)
y = cos(angle)
if i % 2:
radius = inner
else:
radius = outer
x = startx + radius * x
y = starty + radius * y
self.lineto(x, y)
return self.endpath(draw)
|
[
"Draws",
"a",
"star",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L227-L246
|
[
"def",
"star",
"(",
"self",
",",
"startx",
",",
"starty",
",",
"points",
"=",
"20",
",",
"outer",
"=",
"100",
",",
"inner",
"=",
"50",
",",
"draw",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Taken from Nodebox.",
"self",
".",
"beginpath",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"moveto",
"(",
"startx",
",",
"starty",
"+",
"outer",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"int",
"(",
"2",
"*",
"points",
")",
")",
":",
"angle",
"=",
"i",
"*",
"pi",
"/",
"points",
"x",
"=",
"sin",
"(",
"angle",
")",
"y",
"=",
"cos",
"(",
"angle",
")",
"if",
"i",
"%",
"2",
":",
"radius",
"=",
"inner",
"else",
":",
"radius",
"=",
"outer",
"x",
"=",
"startx",
"+",
"radius",
"*",
"x",
"y",
"=",
"starty",
"+",
"radius",
"*",
"y",
"self",
".",
"lineto",
"(",
"x",
",",
"y",
")",
"return",
"self",
".",
"endpath",
"(",
"draw",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.drawimage
|
:param image: Image to draw
:param x: optional, x coordinate (default is image.x)
:param y: optional, y coordinate (default is image.y)
:return:
|
shoebot/grammar/nodebox.py
|
def drawimage(self, image, x=None, y=None):
"""
:param image: Image to draw
:param x: optional, x coordinate (default is image.x)
:param y: optional, y coordinate (default is image.y)
:return:
"""
if x is None:
x = image.x
if y is None:
y = image.y
self.image(image.path, image.x, image.y, data=image.data)
|
def drawimage(self, image, x=None, y=None):
"""
:param image: Image to draw
:param x: optional, x coordinate (default is image.x)
:param y: optional, y coordinate (default is image.y)
:return:
"""
if x is None:
x = image.x
if y is None:
y = image.y
self.image(image.path, image.x, image.y, data=image.data)
|
[
":",
"param",
"image",
":",
"Image",
"to",
"draw",
":",
"param",
"x",
":",
"optional",
"x",
"coordinate",
"(",
"default",
"is",
"image",
".",
"x",
")",
":",
"param",
"y",
":",
"optional",
"y",
"coordinate",
"(",
"default",
"is",
"image",
".",
"y",
")",
":",
"return",
":"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L311-L322
|
[
"def",
"drawimage",
"(",
"self",
",",
"image",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"if",
"x",
"is",
"None",
":",
"x",
"=",
"image",
".",
"x",
"if",
"y",
"is",
"None",
":",
"y",
"=",
"image",
".",
"y",
"self",
".",
"image",
"(",
"image",
".",
"path",
",",
"image",
".",
"x",
",",
"image",
".",
"y",
",",
"data",
"=",
"image",
".",
"data",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.relmoveto
|
Move relatively to the last point.
|
shoebot/grammar/nodebox.py
|
def relmoveto(self, x, y):
'''Move relatively to the last point.'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.relmoveto(x, y)
|
def relmoveto(self, x, y):
'''Move relatively to the last point.'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.relmoveto(x, y)
|
[
"Move",
"relatively",
"to",
"the",
"last",
"point",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L327-L331
|
[
"def",
"relmoveto",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"self",
".",
"_path",
"is",
"None",
":",
"raise",
"ShoebotError",
"(",
"_",
"(",
"\"No current path. Use beginpath() first.\"",
")",
")",
"self",
".",
"_path",
".",
"relmoveto",
"(",
"x",
",",
"y",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.rellineto
|
Draw a line using relative coordinates.
|
shoebot/grammar/nodebox.py
|
def rellineto(self, x, y):
'''Draw a line using relative coordinates.'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.rellineto(x, y)
|
def rellineto(self, x, y):
'''Draw a line using relative coordinates.'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.rellineto(x, y)
|
[
"Draw",
"a",
"line",
"using",
"relative",
"coordinates",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L333-L337
|
[
"def",
"rellineto",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"self",
".",
"_path",
"is",
"None",
":",
"raise",
"ShoebotError",
"(",
"_",
"(",
"\"No current path. Use beginpath() first.\"",
")",
")",
"self",
".",
"_path",
".",
"rellineto",
"(",
"x",
",",
"y",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.relcurveto
|
Draws a curve relatively to the last point.
|
shoebot/grammar/nodebox.py
|
def relcurveto(self, h1x, h1y, h2x, h2y, x, y):
'''Draws a curve relatively to the last point.
'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.relcurveto(h1x, h1y, h2x, h2y, x, y)
|
def relcurveto(self, h1x, h1y, h2x, h2y, x, y):
'''Draws a curve relatively to the last point.
'''
if self._path is None:
raise ShoebotError(_("No current path. Use beginpath() first."))
self._path.relcurveto(h1x, h1y, h2x, h2y, x, y)
|
[
"Draws",
"a",
"curve",
"relatively",
"to",
"the",
"last",
"point",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L339-L344
|
[
"def",
"relcurveto",
"(",
"self",
",",
"h1x",
",",
"h1y",
",",
"h2x",
",",
"h2y",
",",
"x",
",",
"y",
")",
":",
"if",
"self",
".",
"_path",
"is",
"None",
":",
"raise",
"ShoebotError",
"(",
"_",
"(",
"\"No current path. Use beginpath() first.\"",
")",
")",
"self",
".",
"_path",
".",
"relcurveto",
"(",
"h1x",
",",
"h1y",
",",
"h2x",
",",
"h2y",
",",
"x",
",",
"y",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.findpath
|
Constructs a path between the given list of points.
Interpolates the list of points and determines
a smooth bezier path betweem them.
The curvature parameter offers some control on
how separate segments are stitched together:
from straight angles to smooth curves.
Curvature is only useful if the path has more than three points.
|
shoebot/grammar/nodebox.py
|
def findpath(self, points, curvature=1.0):
"""Constructs a path between the given list of points.
Interpolates the list of points and determines
a smooth bezier path betweem them.
The curvature parameter offers some control on
how separate segments are stitched together:
from straight angles to smooth curves.
Curvature is only useful if the path has more than three points.
"""
# The list of points consists of Point objects,
# but it shouldn't crash on something straightforward
# as someone supplying a list of (x,y)-tuples.
for i, pt in enumerate(points):
if type(pt) == TupleType:
points[i] = Point(pt[0], pt[1])
if len(points) == 0:
return None
if len(points) == 1:
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
return path
if len(points) == 2:
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
path.lineto(points[1].x, points[1].y)
return path
# Zero curvature means straight lines.
curvature = max(0, min(1, curvature))
if curvature == 0:
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
for i in range(len(points)):
path.lineto(points[i].x, points[i].y)
return path
curvature = 4 + (1.0 - curvature) * 40
dx = {0: 0, len(points) - 1: 0}
dy = {0: 0, len(points) - 1: 0}
bi = {1: -0.25}
ax = {1: (points[2].x - points[0].x - dx[0]) / 4}
ay = {1: (points[2].y - points[0].y - dy[0]) / 4}
for i in range(2, len(points) - 1):
bi[i] = -1 / (curvature + bi[i - 1])
ax[i] = -(points[i + 1].x - points[i - 1].x - ax[i - 1]) * bi[i]
ay[i] = -(points[i + 1].y - points[i - 1].y - ay[i - 1]) * bi[i]
r = range(1, len(points) - 1)
r.reverse()
for i in r:
dx[i] = ax[i] + dx[i + 1] * bi[i]
dy[i] = ay[i] + dy[i + 1] * bi[i]
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
for i in range(len(points) - 1):
path.curveto(points[i].x + dx[i],
points[i].y + dy[i],
points[i + 1].x - dx[i + 1],
points[i + 1].y - dy[i + 1],
points[i + 1].x,
points[i + 1].y)
return path
|
def findpath(self, points, curvature=1.0):
"""Constructs a path between the given list of points.
Interpolates the list of points and determines
a smooth bezier path betweem them.
The curvature parameter offers some control on
how separate segments are stitched together:
from straight angles to smooth curves.
Curvature is only useful if the path has more than three points.
"""
# The list of points consists of Point objects,
# but it shouldn't crash on something straightforward
# as someone supplying a list of (x,y)-tuples.
for i, pt in enumerate(points):
if type(pt) == TupleType:
points[i] = Point(pt[0], pt[1])
if len(points) == 0:
return None
if len(points) == 1:
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
return path
if len(points) == 2:
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
path.lineto(points[1].x, points[1].y)
return path
# Zero curvature means straight lines.
curvature = max(0, min(1, curvature))
if curvature == 0:
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
for i in range(len(points)):
path.lineto(points[i].x, points[i].y)
return path
curvature = 4 + (1.0 - curvature) * 40
dx = {0: 0, len(points) - 1: 0}
dy = {0: 0, len(points) - 1: 0}
bi = {1: -0.25}
ax = {1: (points[2].x - points[0].x - dx[0]) / 4}
ay = {1: (points[2].y - points[0].y - dy[0]) / 4}
for i in range(2, len(points) - 1):
bi[i] = -1 / (curvature + bi[i - 1])
ax[i] = -(points[i + 1].x - points[i - 1].x - ax[i - 1]) * bi[i]
ay[i] = -(points[i + 1].y - points[i - 1].y - ay[i - 1]) * bi[i]
r = range(1, len(points) - 1)
r.reverse()
for i in r:
dx[i] = ax[i] + dx[i + 1] * bi[i]
dy[i] = ay[i] + dy[i + 1] * bi[i]
path = self.BezierPath(None)
path.moveto(points[0].x, points[0].y)
for i in range(len(points) - 1):
path.curveto(points[i].x + dx[i],
points[i].y + dy[i],
points[i + 1].x - dx[i + 1],
points[i + 1].y - dy[i + 1],
points[i + 1].x,
points[i + 1].y)
return path
|
[
"Constructs",
"a",
"path",
"between",
"the",
"given",
"list",
"of",
"points",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L346-L418
|
[
"def",
"findpath",
"(",
"self",
",",
"points",
",",
"curvature",
"=",
"1.0",
")",
":",
"# The list of points consists of Point objects,",
"# but it shouldn't crash on something straightforward",
"# as someone supplying a list of (x,y)-tuples.",
"for",
"i",
",",
"pt",
"in",
"enumerate",
"(",
"points",
")",
":",
"if",
"type",
"(",
"pt",
")",
"==",
"TupleType",
":",
"points",
"[",
"i",
"]",
"=",
"Point",
"(",
"pt",
"[",
"0",
"]",
",",
"pt",
"[",
"1",
"]",
")",
"if",
"len",
"(",
"points",
")",
"==",
"0",
":",
"return",
"None",
"if",
"len",
"(",
"points",
")",
"==",
"1",
":",
"path",
"=",
"self",
".",
"BezierPath",
"(",
"None",
")",
"path",
".",
"moveto",
"(",
"points",
"[",
"0",
"]",
".",
"x",
",",
"points",
"[",
"0",
"]",
".",
"y",
")",
"return",
"path",
"if",
"len",
"(",
"points",
")",
"==",
"2",
":",
"path",
"=",
"self",
".",
"BezierPath",
"(",
"None",
")",
"path",
".",
"moveto",
"(",
"points",
"[",
"0",
"]",
".",
"x",
",",
"points",
"[",
"0",
"]",
".",
"y",
")",
"path",
".",
"lineto",
"(",
"points",
"[",
"1",
"]",
".",
"x",
",",
"points",
"[",
"1",
"]",
".",
"y",
")",
"return",
"path",
"# Zero curvature means straight lines.",
"curvature",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"1",
",",
"curvature",
")",
")",
"if",
"curvature",
"==",
"0",
":",
"path",
"=",
"self",
".",
"BezierPath",
"(",
"None",
")",
"path",
".",
"moveto",
"(",
"points",
"[",
"0",
"]",
".",
"x",
",",
"points",
"[",
"0",
"]",
".",
"y",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"points",
")",
")",
":",
"path",
".",
"lineto",
"(",
"points",
"[",
"i",
"]",
".",
"x",
",",
"points",
"[",
"i",
"]",
".",
"y",
")",
"return",
"path",
"curvature",
"=",
"4",
"+",
"(",
"1.0",
"-",
"curvature",
")",
"*",
"40",
"dx",
"=",
"{",
"0",
":",
"0",
",",
"len",
"(",
"points",
")",
"-",
"1",
":",
"0",
"}",
"dy",
"=",
"{",
"0",
":",
"0",
",",
"len",
"(",
"points",
")",
"-",
"1",
":",
"0",
"}",
"bi",
"=",
"{",
"1",
":",
"-",
"0.25",
"}",
"ax",
"=",
"{",
"1",
":",
"(",
"points",
"[",
"2",
"]",
".",
"x",
"-",
"points",
"[",
"0",
"]",
".",
"x",
"-",
"dx",
"[",
"0",
"]",
")",
"/",
"4",
"}",
"ay",
"=",
"{",
"1",
":",
"(",
"points",
"[",
"2",
"]",
".",
"y",
"-",
"points",
"[",
"0",
"]",
".",
"y",
"-",
"dy",
"[",
"0",
"]",
")",
"/",
"4",
"}",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"len",
"(",
"points",
")",
"-",
"1",
")",
":",
"bi",
"[",
"i",
"]",
"=",
"-",
"1",
"/",
"(",
"curvature",
"+",
"bi",
"[",
"i",
"-",
"1",
"]",
")",
"ax",
"[",
"i",
"]",
"=",
"-",
"(",
"points",
"[",
"i",
"+",
"1",
"]",
".",
"x",
"-",
"points",
"[",
"i",
"-",
"1",
"]",
".",
"x",
"-",
"ax",
"[",
"i",
"-",
"1",
"]",
")",
"*",
"bi",
"[",
"i",
"]",
"ay",
"[",
"i",
"]",
"=",
"-",
"(",
"points",
"[",
"i",
"+",
"1",
"]",
".",
"y",
"-",
"points",
"[",
"i",
"-",
"1",
"]",
".",
"y",
"-",
"ay",
"[",
"i",
"-",
"1",
"]",
")",
"*",
"bi",
"[",
"i",
"]",
"r",
"=",
"range",
"(",
"1",
",",
"len",
"(",
"points",
")",
"-",
"1",
")",
"r",
".",
"reverse",
"(",
")",
"for",
"i",
"in",
"r",
":",
"dx",
"[",
"i",
"]",
"=",
"ax",
"[",
"i",
"]",
"+",
"dx",
"[",
"i",
"+",
"1",
"]",
"*",
"bi",
"[",
"i",
"]",
"dy",
"[",
"i",
"]",
"=",
"ay",
"[",
"i",
"]",
"+",
"dy",
"[",
"i",
"+",
"1",
"]",
"*",
"bi",
"[",
"i",
"]",
"path",
"=",
"self",
".",
"BezierPath",
"(",
"None",
")",
"path",
".",
"moveto",
"(",
"points",
"[",
"0",
"]",
".",
"x",
",",
"points",
"[",
"0",
"]",
".",
"y",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"points",
")",
"-",
"1",
")",
":",
"path",
".",
"curveto",
"(",
"points",
"[",
"i",
"]",
".",
"x",
"+",
"dx",
"[",
"i",
"]",
",",
"points",
"[",
"i",
"]",
".",
"y",
"+",
"dy",
"[",
"i",
"]",
",",
"points",
"[",
"i",
"+",
"1",
"]",
".",
"x",
"-",
"dx",
"[",
"i",
"+",
"1",
"]",
",",
"points",
"[",
"i",
"+",
"1",
"]",
".",
"y",
"-",
"dy",
"[",
"i",
"+",
"1",
"]",
",",
"points",
"[",
"i",
"+",
"1",
"]",
".",
"x",
",",
"points",
"[",
"i",
"+",
"1",
"]",
".",
"y",
")",
"return",
"path"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.transform
|
Set the current transform mode.
:param mode: CENTER or CORNER
|
shoebot/grammar/nodebox.py
|
def transform(self, mode=None):
'''
Set the current transform mode.
:param mode: CENTER or CORNER'''
if mode:
self._canvas.mode = mode
return self._canvas.mode
|
def transform(self, mode=None):
'''
Set the current transform mode.
:param mode: CENTER or CORNER'''
if mode:
self._canvas.mode = mode
return self._canvas.mode
|
[
"Set",
"the",
"current",
"transform",
"mode",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L432-L439
|
[
"def",
"transform",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
":",
"self",
".",
"_canvas",
".",
"mode",
"=",
"mode",
"return",
"self",
".",
"_canvas",
".",
"mode"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.translate
|
Translate the current position by (xt, yt) and
optionally set the transform mode.
:param xt: Amount to move horizontally
:param yt: Amount to move vertically
:mode: Set the transform mode to CENTER or CORNER
|
shoebot/grammar/nodebox.py
|
def translate(self, xt, yt, mode=None):
'''
Translate the current position by (xt, yt) and
optionally set the transform mode.
:param xt: Amount to move horizontally
:param yt: Amount to move vertically
:mode: Set the transform mode to CENTER or CORNER
'''
self._canvas.translate(xt, yt)
if mode:
self._canvas.mode = mode
|
def translate(self, xt, yt, mode=None):
'''
Translate the current position by (xt, yt) and
optionally set the transform mode.
:param xt: Amount to move horizontally
:param yt: Amount to move vertically
:mode: Set the transform mode to CENTER or CORNER
'''
self._canvas.translate(xt, yt)
if mode:
self._canvas.mode = mode
|
[
"Translate",
"the",
"current",
"position",
"by",
"(",
"xt",
"yt",
")",
"and",
"optionally",
"set",
"the",
"transform",
"mode",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L441-L452
|
[
"def",
"translate",
"(",
"self",
",",
"xt",
",",
"yt",
",",
"mode",
"=",
"None",
")",
":",
"self",
".",
"_canvas",
".",
"translate",
"(",
"xt",
",",
"yt",
")",
"if",
"mode",
":",
"self",
".",
"_canvas",
".",
"mode",
"=",
"mode"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.scale
|
Set a scale at which to draw objects.
1.0 draws objects at their natural size
:param x: Scale on the horizontal plane
:param y: Scale on the vertical plane
|
shoebot/grammar/nodebox.py
|
def scale(self, x=1, y=None):
'''
Set a scale at which to draw objects.
1.0 draws objects at their natural size
:param x: Scale on the horizontal plane
:param y: Scale on the vertical plane
'''
if not y:
y = x
if x == 0:
# Cairo borks on zero values
x = 1
if y == 0:
y = 1
self._canvas.scale(x, y)
|
def scale(self, x=1, y=None):
'''
Set a scale at which to draw objects.
1.0 draws objects at their natural size
:param x: Scale on the horizontal plane
:param y: Scale on the vertical plane
'''
if not y:
y = x
if x == 0:
# Cairo borks on zero values
x = 1
if y == 0:
y = 1
self._canvas.scale(x, y)
|
[
"Set",
"a",
"scale",
"at",
"which",
"to",
"draw",
"objects",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L468-L484
|
[
"def",
"scale",
"(",
"self",
",",
"x",
"=",
"1",
",",
"y",
"=",
"None",
")",
":",
"if",
"not",
"y",
":",
"y",
"=",
"x",
"if",
"x",
"==",
"0",
":",
"# Cairo borks on zero values",
"x",
"=",
"1",
"if",
"y",
"==",
"0",
":",
"y",
"=",
"1",
"self",
".",
"_canvas",
".",
"scale",
"(",
"x",
",",
"y",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.fill
|
Sets a fill color, applying it to new paths.
:param args: color in supported format
|
shoebot/grammar/nodebox.py
|
def fill(self, *args):
'''Sets a fill color, applying it to new paths.
:param args: color in supported format
'''
if args is not None:
self._canvas.fillcolor = self.color(*args)
return self._canvas.fillcolor
|
def fill(self, *args):
'''Sets a fill color, applying it to new paths.
:param args: color in supported format
'''
if args is not None:
self._canvas.fillcolor = self.color(*args)
return self._canvas.fillcolor
|
[
"Sets",
"a",
"fill",
"color",
"applying",
"it",
"to",
"new",
"paths",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L541-L548
|
[
"def",
"fill",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"fillcolor",
"=",
"self",
".",
"color",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_canvas",
".",
"fillcolor"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.stroke
|
Set a stroke color, applying it to new paths.
:param args: color in supported format
|
shoebot/grammar/nodebox.py
|
def stroke(self, *args):
'''Set a stroke color, applying it to new paths.
:param args: color in supported format
'''
if args is not None:
self._canvas.strokecolor = self.color(*args)
return self._canvas.strokecolor
|
def stroke(self, *args):
'''Set a stroke color, applying it to new paths.
:param args: color in supported format
'''
if args is not None:
self._canvas.strokecolor = self.color(*args)
return self._canvas.strokecolor
|
[
"Set",
"a",
"stroke",
"color",
"applying",
"it",
"to",
"new",
"paths",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L554-L561
|
[
"def",
"stroke",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"strokecolor",
"=",
"self",
".",
"color",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_canvas",
".",
"strokecolor"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.nostroke
|
Stop applying strokes to new paths.
:return: stroke color before nostroke was called.
|
shoebot/grammar/nodebox.py
|
def nostroke(self):
''' Stop applying strokes to new paths.
:return: stroke color before nostroke was called.
'''
c = self._canvas.strokecolor
self._canvas.strokecolor = None
return c
|
def nostroke(self):
''' Stop applying strokes to new paths.
:return: stroke color before nostroke was called.
'''
c = self._canvas.strokecolor
self._canvas.strokecolor = None
return c
|
[
"Stop",
"applying",
"strokes",
"to",
"new",
"paths",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L563-L570
|
[
"def",
"nostroke",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_canvas",
".",
"strokecolor",
"self",
".",
"_canvas",
".",
"strokecolor",
"=",
"None",
"return",
"c"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.strokewidth
|
Set the stroke width.
:param w: Stroke width.
:return: If no width was specified then current width is returned.
|
shoebot/grammar/nodebox.py
|
def strokewidth(self, w=None):
'''Set the stroke width.
:param w: Stroke width.
:return: If no width was specified then current width is returned.
'''
if w is not None:
self._canvas.strokewidth = w
else:
return self._canvas.strokewidth
|
def strokewidth(self, w=None):
'''Set the stroke width.
:param w: Stroke width.
:return: If no width was specified then current width is returned.
'''
if w is not None:
self._canvas.strokewidth = w
else:
return self._canvas.strokewidth
|
[
"Set",
"the",
"stroke",
"width",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L572-L581
|
[
"def",
"strokewidth",
"(",
"self",
",",
"w",
"=",
"None",
")",
":",
"if",
"w",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"strokewidth",
"=",
"w",
"else",
":",
"return",
"self",
".",
"_canvas",
".",
"strokewidth"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.font
|
Set the font to be used with new text instances.
:param fontpath: path to truetype or opentype font.
:param fontsize: size of font
:return: current current fontpath (if fontpath param not set)
Accepts TrueType and OpenType files. Depends on FreeType being
installed.
|
shoebot/grammar/nodebox.py
|
def font(self, fontpath=None, fontsize=None):
'''Set the font to be used with new text instances.
:param fontpath: path to truetype or opentype font.
:param fontsize: size of font
:return: current current fontpath (if fontpath param not set)
Accepts TrueType and OpenType files. Depends on FreeType being
installed.'''
if fontpath is not None:
self._canvas.fontfile = fontpath
else:
return self._canvas.fontfile
if fontsize is not None:
self._canvas.fontsize = fontsize
|
def font(self, fontpath=None, fontsize=None):
'''Set the font to be used with new text instances.
:param fontpath: path to truetype or opentype font.
:param fontsize: size of font
:return: current current fontpath (if fontpath param not set)
Accepts TrueType and OpenType files. Depends on FreeType being
installed.'''
if fontpath is not None:
self._canvas.fontfile = fontpath
else:
return self._canvas.fontfile
if fontsize is not None:
self._canvas.fontsize = fontsize
|
[
"Set",
"the",
"font",
"to",
"be",
"used",
"with",
"new",
"text",
"instances",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L592-L606
|
[
"def",
"font",
"(",
"self",
",",
"fontpath",
"=",
"None",
",",
"fontsize",
"=",
"None",
")",
":",
"if",
"fontpath",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"fontfile",
"=",
"fontpath",
"else",
":",
"return",
"self",
".",
"_canvas",
".",
"fontfile",
"if",
"fontsize",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"fontsize",
"=",
"fontsize"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.fontsize
|
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
|
shoebot/grammar/nodebox.py
|
def fontsize(self, fontsize=None):
'''
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
'''
if fontsize is not None:
self._canvas.fontsize = fontsize
else:
return self._canvas.fontsize
|
def fontsize(self, fontsize=None):
'''
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
'''
if fontsize is not None:
self._canvas.fontsize = fontsize
else:
return self._canvas.fontsize
|
[
"Set",
"or",
"return",
"size",
"of",
"current",
"font",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L608-L618
|
[
"def",
"fontsize",
"(",
"self",
",",
"fontsize",
"=",
"None",
")",
":",
"if",
"fontsize",
"is",
"not",
"None",
":",
"self",
".",
"_canvas",
".",
"fontsize",
"=",
"fontsize",
"else",
":",
"return",
"self",
".",
"_canvas",
".",
"fontsize"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.text
|
Draws a string of text according to current font settings.
:param txt: Text to output
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
:param width: text width
:param height: text height
:param outline: If True draws outline text (defaults to False)
:param draw: Set to False to inhibit immediate drawing (defaults to True)
:return: Path object representing the text.
|
shoebot/grammar/nodebox.py
|
def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs):
'''
Draws a string of text according to current font settings.
:param txt: Text to output
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
:param width: text width
:param height: text height
:param outline: If True draws outline text (defaults to False)
:param draw: Set to False to inhibit immediate drawing (defaults to True)
:return: Path object representing the text.
'''
txt = self.Text(txt, x, y, width, height, outline=outline, ctx=None, **kwargs)
if outline:
path = txt.path
if draw:
path.draw()
return path
else:
return txt
|
def text(self, txt, x, y, width=None, height=1000000, outline=False, draw=True, **kwargs):
'''
Draws a string of text according to current font settings.
:param txt: Text to output
:param x: x-coordinate of the top left corner
:param y: y-coordinate of the top left corner
:param width: text width
:param height: text height
:param outline: If True draws outline text (defaults to False)
:param draw: Set to False to inhibit immediate drawing (defaults to True)
:return: Path object representing the text.
'''
txt = self.Text(txt, x, y, width, height, outline=outline, ctx=None, **kwargs)
if outline:
path = txt.path
if draw:
path.draw()
return path
else:
return txt
|
[
"Draws",
"a",
"string",
"of",
"text",
"according",
"to",
"current",
"font",
"settings",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L620-L640
|
[
"def",
"text",
"(",
"self",
",",
"txt",
",",
"x",
",",
"y",
",",
"width",
"=",
"None",
",",
"height",
"=",
"1000000",
",",
"outline",
"=",
"False",
",",
"draw",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"txt",
"=",
"self",
".",
"Text",
"(",
"txt",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"outline",
"=",
"outline",
",",
"ctx",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"if",
"outline",
":",
"path",
"=",
"txt",
".",
"path",
"if",
"draw",
":",
"path",
".",
"draw",
"(",
")",
"return",
"path",
"else",
":",
"return",
"txt"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
NodeBot.textheight
|
Returns the height of a string of text according to the current
font settings.
:param txt: string to measure
:param width: width of a line of text in a block
|
shoebot/grammar/nodebox.py
|
def textheight(self, txt, width=None):
'''Returns the height of a string of text according to the current
font settings.
:param txt: string to measure
:param width: width of a line of text in a block
'''
w = width
return self.textmetrics(txt, width=w)[1]
|
def textheight(self, txt, width=None):
'''Returns the height of a string of text according to the current
font settings.
:param txt: string to measure
:param width: width of a line of text in a block
'''
w = width
return self.textmetrics(txt, width=w)[1]
|
[
"Returns",
"the",
"height",
"of",
"a",
"string",
"of",
"text",
"according",
"to",
"the",
"current",
"font",
"settings",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/grammar/nodebox.py#L680-L688
|
[
"def",
"textheight",
"(",
"self",
",",
"txt",
",",
"width",
"=",
"None",
")",
":",
"w",
"=",
"width",
"return",
"self",
".",
"textmetrics",
"(",
"txt",
",",
"width",
"=",
"w",
")",
"[",
"1",
"]"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
graph_background
|
Graph background color.
|
lib/graph/style.py
|
def graph_background(s):
""" Graph background color.
"""
if s.background == None:
s._ctx.background(None)
else:
s._ctx.background(s.background)
if s.depth:
try:
clr = colors.color(s.background).darker(0.2)
p = s._ctx.rect(0, 0, s._ctx.WIDTH, s._ctx.HEIGHT, draw=False)
colors.gradientfill(p, clr, clr.lighter(0.35))
colors.shadow(dx=0, dy=0, blur=2, alpha=0.935, clr=s.background)
except:
pass
|
def graph_background(s):
""" Graph background color.
"""
if s.background == None:
s._ctx.background(None)
else:
s._ctx.background(s.background)
if s.depth:
try:
clr = colors.color(s.background).darker(0.2)
p = s._ctx.rect(0, 0, s._ctx.WIDTH, s._ctx.HEIGHT, draw=False)
colors.gradientfill(p, clr, clr.lighter(0.35))
colors.shadow(dx=0, dy=0, blur=2, alpha=0.935, clr=s.background)
except:
pass
|
[
"Graph",
"background",
"color",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L183-L200
|
[
"def",
"graph_background",
"(",
"s",
")",
":",
"if",
"s",
".",
"background",
"==",
"None",
":",
"s",
".",
"_ctx",
".",
"background",
"(",
"None",
")",
"else",
":",
"s",
".",
"_ctx",
".",
"background",
"(",
"s",
".",
"background",
")",
"if",
"s",
".",
"depth",
":",
"try",
":",
"clr",
"=",
"colors",
".",
"color",
"(",
"s",
".",
"background",
")",
".",
"darker",
"(",
"0.2",
")",
"p",
"=",
"s",
".",
"_ctx",
".",
"rect",
"(",
"0",
",",
"0",
",",
"s",
".",
"_ctx",
".",
"WIDTH",
",",
"s",
".",
"_ctx",
".",
"HEIGHT",
",",
"draw",
"=",
"False",
")",
"colors",
".",
"gradientfill",
"(",
"p",
",",
"clr",
",",
"clr",
".",
"lighter",
"(",
"0.35",
")",
")",
"colors",
".",
"shadow",
"(",
"dx",
"=",
"0",
",",
"dy",
"=",
"0",
",",
"blur",
"=",
"2",
",",
"alpha",
"=",
"0.935",
",",
"clr",
"=",
"s",
".",
"background",
")",
"except",
":",
"pass"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
graph_traffic
|
Visualization of traffic-intensive nodes (based on their centrality).
|
lib/graph/style.py
|
def graph_traffic(s, node, alpha=1.0):
""" Visualization of traffic-intensive nodes (based on their centrality).
"""
r = node.__class__(None).r
r += (node.weight+0.5) * r * 5
s._ctx.nostroke()
if s.traffic:
s._ctx.fill(
s.traffic.r,
s.traffic.g,
s.traffic.b,
s.traffic.a * alpha
)
s._ctx.oval(node.x-r, node.y-r, r*2, r*2)
|
def graph_traffic(s, node, alpha=1.0):
""" Visualization of traffic-intensive nodes (based on their centrality).
"""
r = node.__class__(None).r
r += (node.weight+0.5) * r * 5
s._ctx.nostroke()
if s.traffic:
s._ctx.fill(
s.traffic.r,
s.traffic.g,
s.traffic.b,
s.traffic.a * alpha
)
s._ctx.oval(node.x-r, node.y-r, r*2, r*2)
|
[
"Visualization",
"of",
"traffic",
"-",
"intensive",
"nodes",
"(",
"based",
"on",
"their",
"centrality",
")",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L204-L219
|
[
"def",
"graph_traffic",
"(",
"s",
",",
"node",
",",
"alpha",
"=",
"1.0",
")",
":",
"r",
"=",
"node",
".",
"__class__",
"(",
"None",
")",
".",
"r",
"r",
"+=",
"(",
"node",
".",
"weight",
"+",
"0.5",
")",
"*",
"r",
"*",
"5",
"s",
".",
"_ctx",
".",
"nostroke",
"(",
")",
"if",
"s",
".",
"traffic",
":",
"s",
".",
"_ctx",
".",
"fill",
"(",
"s",
".",
"traffic",
".",
"r",
",",
"s",
".",
"traffic",
".",
"g",
",",
"s",
".",
"traffic",
".",
"b",
",",
"s",
".",
"traffic",
".",
"a",
"*",
"alpha",
")",
"s",
".",
"_ctx",
".",
"oval",
"(",
"node",
".",
"x",
"-",
"r",
",",
"node",
".",
"y",
"-",
"r",
",",
"r",
"*",
"2",
",",
"r",
"*",
"2",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
node
|
Visualization of a default node.
|
lib/graph/style.py
|
def node(s, node, alpha=1.0):
""" Visualization of a default node.
"""
if s.depth:
try: colors.shadow(dx=5, dy=5, blur=10, alpha=0.5*alpha)
except: pass
s._ctx.nofill()
s._ctx.nostroke()
if s.fill:
s._ctx.fill(
s.fill.r,
s.fill.g,
s.fill.b,
s.fill.a * alpha
)
if s.stroke:
s._ctx.strokewidth(s.strokewidth)
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a * alpha * 3
)
r = node.r
s._ctx.oval(node.x-r, node.y-r, r*2, r*2)
|
def node(s, node, alpha=1.0):
""" Visualization of a default node.
"""
if s.depth:
try: colors.shadow(dx=5, dy=5, blur=10, alpha=0.5*alpha)
except: pass
s._ctx.nofill()
s._ctx.nostroke()
if s.fill:
s._ctx.fill(
s.fill.r,
s.fill.g,
s.fill.b,
s.fill.a * alpha
)
if s.stroke:
s._ctx.strokewidth(s.strokewidth)
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a * alpha * 3
)
r = node.r
s._ctx.oval(node.x-r, node.y-r, r*2, r*2)
|
[
"Visualization",
"of",
"a",
"default",
"node",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L223-L250
|
[
"def",
"node",
"(",
"s",
",",
"node",
",",
"alpha",
"=",
"1.0",
")",
":",
"if",
"s",
".",
"depth",
":",
"try",
":",
"colors",
".",
"shadow",
"(",
"dx",
"=",
"5",
",",
"dy",
"=",
"5",
",",
"blur",
"=",
"10",
",",
"alpha",
"=",
"0.5",
"*",
"alpha",
")",
"except",
":",
"pass",
"s",
".",
"_ctx",
".",
"nofill",
"(",
")",
"s",
".",
"_ctx",
".",
"nostroke",
"(",
")",
"if",
"s",
".",
"fill",
":",
"s",
".",
"_ctx",
".",
"fill",
"(",
"s",
".",
"fill",
".",
"r",
",",
"s",
".",
"fill",
".",
"g",
",",
"s",
".",
"fill",
".",
"b",
",",
"s",
".",
"fill",
".",
"a",
"*",
"alpha",
")",
"if",
"s",
".",
"stroke",
":",
"s",
".",
"_ctx",
".",
"strokewidth",
"(",
"s",
".",
"strokewidth",
")",
"s",
".",
"_ctx",
".",
"stroke",
"(",
"s",
".",
"stroke",
".",
"r",
",",
"s",
".",
"stroke",
".",
"g",
",",
"s",
".",
"stroke",
".",
"b",
",",
"s",
".",
"stroke",
".",
"a",
"*",
"alpha",
"*",
"3",
")",
"r",
"=",
"node",
".",
"r",
"s",
".",
"_ctx",
".",
"oval",
"(",
"node",
".",
"x",
"-",
"r",
",",
"node",
".",
"y",
"-",
"r",
",",
"r",
"*",
"2",
",",
"r",
"*",
"2",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
node_label
|
Visualization of a node's id.
|
lib/graph/style.py
|
def node_label(s, node, alpha=1.0):
""" Visualization of a node's id.
"""
if s.text:
#s._ctx.lineheight(1)
s._ctx.font(s.font)
s._ctx.fontsize(s.fontsize)
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
s.text.a * alpha
)
# Cache an outlined label text and translate it.
# This enhances the speed and avoids wiggling text.
try: p = node._textpath
except:
txt = node.label
try: txt = unicode(txt)
except:
try: txt = txt.decode("utf-8")
except:
pass
# Abbreviation.
#root = node.graph.root
#if txt != root and txt[-len(root):] == root:
# txt = txt[:len(txt)-len(root)]+root[0]+"."
dx, dy = 0, 0
if s.align == 2: #CENTER
dx = -s._ctx.textwidth(txt, s.textwidth) / 2
dy = s._ctx.textheight(txt) / 2
node._textpath = s._ctx.textpath(txt, dx, dy, width=s.textwidth)
p = node._textpath
if s.depth:
try: __colors.shadow(dx=2, dy=4, blur=5, alpha=0.3*alpha)
except: pass
s._ctx.push()
s._ctx.translate(node.x, node.y)
s._ctx.scale(alpha)
s._ctx.drawpath(p.copy())
s._ctx.pop()
|
def node_label(s, node, alpha=1.0):
""" Visualization of a node's id.
"""
if s.text:
#s._ctx.lineheight(1)
s._ctx.font(s.font)
s._ctx.fontsize(s.fontsize)
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
s.text.a * alpha
)
# Cache an outlined label text and translate it.
# This enhances the speed and avoids wiggling text.
try: p = node._textpath
except:
txt = node.label
try: txt = unicode(txt)
except:
try: txt = txt.decode("utf-8")
except:
pass
# Abbreviation.
#root = node.graph.root
#if txt != root and txt[-len(root):] == root:
# txt = txt[:len(txt)-len(root)]+root[0]+"."
dx, dy = 0, 0
if s.align == 2: #CENTER
dx = -s._ctx.textwidth(txt, s.textwidth) / 2
dy = s._ctx.textheight(txt) / 2
node._textpath = s._ctx.textpath(txt, dx, dy, width=s.textwidth)
p = node._textpath
if s.depth:
try: __colors.shadow(dx=2, dy=4, blur=5, alpha=0.3*alpha)
except: pass
s._ctx.push()
s._ctx.translate(node.x, node.y)
s._ctx.scale(alpha)
s._ctx.drawpath(p.copy())
s._ctx.pop()
|
[
"Visualization",
"of",
"a",
"node",
"s",
"id",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L254-L300
|
[
"def",
"node_label",
"(",
"s",
",",
"node",
",",
"alpha",
"=",
"1.0",
")",
":",
"if",
"s",
".",
"text",
":",
"#s._ctx.lineheight(1) ",
"s",
".",
"_ctx",
".",
"font",
"(",
"s",
".",
"font",
")",
"s",
".",
"_ctx",
".",
"fontsize",
"(",
"s",
".",
"fontsize",
")",
"s",
".",
"_ctx",
".",
"nostroke",
"(",
")",
"s",
".",
"_ctx",
".",
"fill",
"(",
"s",
".",
"text",
".",
"r",
",",
"s",
".",
"text",
".",
"g",
",",
"s",
".",
"text",
".",
"b",
",",
"s",
".",
"text",
".",
"a",
"*",
"alpha",
")",
"# Cache an outlined label text and translate it.",
"# This enhances the speed and avoids wiggling text.",
"try",
":",
"p",
"=",
"node",
".",
"_textpath",
"except",
":",
"txt",
"=",
"node",
".",
"label",
"try",
":",
"txt",
"=",
"unicode",
"(",
"txt",
")",
"except",
":",
"try",
":",
"txt",
"=",
"txt",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
":",
"pass",
"# Abbreviation.",
"#root = node.graph.root",
"#if txt != root and txt[-len(root):] == root: ",
"# txt = txt[:len(txt)-len(root)]+root[0]+\".\"",
"dx",
",",
"dy",
"=",
"0",
",",
"0",
"if",
"s",
".",
"align",
"==",
"2",
":",
"#CENTER",
"dx",
"=",
"-",
"s",
".",
"_ctx",
".",
"textwidth",
"(",
"txt",
",",
"s",
".",
"textwidth",
")",
"/",
"2",
"dy",
"=",
"s",
".",
"_ctx",
".",
"textheight",
"(",
"txt",
")",
"/",
"2",
"node",
".",
"_textpath",
"=",
"s",
".",
"_ctx",
".",
"textpath",
"(",
"txt",
",",
"dx",
",",
"dy",
",",
"width",
"=",
"s",
".",
"textwidth",
")",
"p",
"=",
"node",
".",
"_textpath",
"if",
"s",
".",
"depth",
":",
"try",
":",
"__colors",
".",
"shadow",
"(",
"dx",
"=",
"2",
",",
"dy",
"=",
"4",
",",
"blur",
"=",
"5",
",",
"alpha",
"=",
"0.3",
"*",
"alpha",
")",
"except",
":",
"pass",
"s",
".",
"_ctx",
".",
"push",
"(",
")",
"s",
".",
"_ctx",
".",
"translate",
"(",
"node",
".",
"x",
",",
"node",
".",
"y",
")",
"s",
".",
"_ctx",
".",
"scale",
"(",
"alpha",
")",
"s",
".",
"_ctx",
".",
"drawpath",
"(",
"p",
".",
"copy",
"(",
")",
")",
"s",
".",
"_ctx",
".",
"pop",
"(",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
edges
|
Visualization of the edges in a network.
|
lib/graph/style.py
|
def edges(s, edges, alpha=1.0, weighted=False, directed=False):
""" Visualization of the edges in a network.
"""
p = s._ctx.BezierPath()
if directed and s.stroke:
pd = s._ctx.BezierPath()
if weighted and s.fill:
pw = [s._ctx.BezierPath() for i in range(11)]
# Draw the edges in a single BezierPath for speed.
# Weighted edges are divided into ten BezierPaths,
# depending on their weight rounded between 0 and 10.
if len(edges) == 0: return
for e in edges:
try: s2 = e.node1.graph.styles[e.node1.style]
except: s2 = s
if s2.edge:
s2.edge(s2, p, e, alpha)
if directed and s.stroke:
s2.edge_arrow(s2, pd, e, radius=10)
if weighted and s.fill:
s2.edge(s2, pw[int(e.weight*10)], e, alpha)
s._ctx.autoclosepath(False)
s._ctx.nofill()
s._ctx.nostroke()
# All weighted edges use the default fill.
if weighted and s.fill:
r = e.node1.__class__(None).r
s._ctx.stroke(
s.fill.r,
s.fill.g,
s.fill.b,
s.fill.a * 0.65 * alpha
)
for w in range(1, len(pw)):
s._ctx.strokewidth(r*w*0.1)
s._ctx.drawpath(pw[w].copy())
# All edges use the default stroke.
if s.stroke:
s._ctx.strokewidth(s.strokewidth)
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a * 0.65 * alpha
)
s._ctx.drawpath(p.copy())
if directed and s.stroke:
#clr = s._ctx.stroke().copy()
clr=s._ctx.color(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a * 0.65 * alpha
)
clr.a *= 1.3
s._ctx.stroke(clr)
s._ctx.drawpath(pd.copy())
for e in edges:
try: s2 = self.styles[e.node1.style]
except: s2 = s
if s2.edge_label:
s2.edge_label(s2, e, alpha)
|
def edges(s, edges, alpha=1.0, weighted=False, directed=False):
""" Visualization of the edges in a network.
"""
p = s._ctx.BezierPath()
if directed and s.stroke:
pd = s._ctx.BezierPath()
if weighted and s.fill:
pw = [s._ctx.BezierPath() for i in range(11)]
# Draw the edges in a single BezierPath for speed.
# Weighted edges are divided into ten BezierPaths,
# depending on their weight rounded between 0 and 10.
if len(edges) == 0: return
for e in edges:
try: s2 = e.node1.graph.styles[e.node1.style]
except: s2 = s
if s2.edge:
s2.edge(s2, p, e, alpha)
if directed and s.stroke:
s2.edge_arrow(s2, pd, e, radius=10)
if weighted and s.fill:
s2.edge(s2, pw[int(e.weight*10)], e, alpha)
s._ctx.autoclosepath(False)
s._ctx.nofill()
s._ctx.nostroke()
# All weighted edges use the default fill.
if weighted and s.fill:
r = e.node1.__class__(None).r
s._ctx.stroke(
s.fill.r,
s.fill.g,
s.fill.b,
s.fill.a * 0.65 * alpha
)
for w in range(1, len(pw)):
s._ctx.strokewidth(r*w*0.1)
s._ctx.drawpath(pw[w].copy())
# All edges use the default stroke.
if s.stroke:
s._ctx.strokewidth(s.strokewidth)
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a * 0.65 * alpha
)
s._ctx.drawpath(p.copy())
if directed and s.stroke:
#clr = s._ctx.stroke().copy()
clr=s._ctx.color(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a * 0.65 * alpha
)
clr.a *= 1.3
s._ctx.stroke(clr)
s._ctx.drawpath(pd.copy())
for e in edges:
try: s2 = self.styles[e.node1.style]
except: s2 = s
if s2.edge_label:
s2.edge_label(s2, e, alpha)
|
[
"Visualization",
"of",
"the",
"edges",
"in",
"a",
"network",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L304-L381
|
[
"def",
"edges",
"(",
"s",
",",
"edges",
",",
"alpha",
"=",
"1.0",
",",
"weighted",
"=",
"False",
",",
"directed",
"=",
"False",
")",
":",
"p",
"=",
"s",
".",
"_ctx",
".",
"BezierPath",
"(",
")",
"if",
"directed",
"and",
"s",
".",
"stroke",
":",
"pd",
"=",
"s",
".",
"_ctx",
".",
"BezierPath",
"(",
")",
"if",
"weighted",
"and",
"s",
".",
"fill",
":",
"pw",
"=",
"[",
"s",
".",
"_ctx",
".",
"BezierPath",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"11",
")",
"]",
"# Draw the edges in a single BezierPath for speed.",
"# Weighted edges are divided into ten BezierPaths,",
"# depending on their weight rounded between 0 and 10.",
"if",
"len",
"(",
"edges",
")",
"==",
"0",
":",
"return",
"for",
"e",
"in",
"edges",
":",
"try",
":",
"s2",
"=",
"e",
".",
"node1",
".",
"graph",
".",
"styles",
"[",
"e",
".",
"node1",
".",
"style",
"]",
"except",
":",
"s2",
"=",
"s",
"if",
"s2",
".",
"edge",
":",
"s2",
".",
"edge",
"(",
"s2",
",",
"p",
",",
"e",
",",
"alpha",
")",
"if",
"directed",
"and",
"s",
".",
"stroke",
":",
"s2",
".",
"edge_arrow",
"(",
"s2",
",",
"pd",
",",
"e",
",",
"radius",
"=",
"10",
")",
"if",
"weighted",
"and",
"s",
".",
"fill",
":",
"s2",
".",
"edge",
"(",
"s2",
",",
"pw",
"[",
"int",
"(",
"e",
".",
"weight",
"*",
"10",
")",
"]",
",",
"e",
",",
"alpha",
")",
"s",
".",
"_ctx",
".",
"autoclosepath",
"(",
"False",
")",
"s",
".",
"_ctx",
".",
"nofill",
"(",
")",
"s",
".",
"_ctx",
".",
"nostroke",
"(",
")",
"# All weighted edges use the default fill.",
"if",
"weighted",
"and",
"s",
".",
"fill",
":",
"r",
"=",
"e",
".",
"node1",
".",
"__class__",
"(",
"None",
")",
".",
"r",
"s",
".",
"_ctx",
".",
"stroke",
"(",
"s",
".",
"fill",
".",
"r",
",",
"s",
".",
"fill",
".",
"g",
",",
"s",
".",
"fill",
".",
"b",
",",
"s",
".",
"fill",
".",
"a",
"*",
"0.65",
"*",
"alpha",
")",
"for",
"w",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"pw",
")",
")",
":",
"s",
".",
"_ctx",
".",
"strokewidth",
"(",
"r",
"*",
"w",
"*",
"0.1",
")",
"s",
".",
"_ctx",
".",
"drawpath",
"(",
"pw",
"[",
"w",
"]",
".",
"copy",
"(",
")",
")",
"# All edges use the default stroke.",
"if",
"s",
".",
"stroke",
":",
"s",
".",
"_ctx",
".",
"strokewidth",
"(",
"s",
".",
"strokewidth",
")",
"s",
".",
"_ctx",
".",
"stroke",
"(",
"s",
".",
"stroke",
".",
"r",
",",
"s",
".",
"stroke",
".",
"g",
",",
"s",
".",
"stroke",
".",
"b",
",",
"s",
".",
"stroke",
".",
"a",
"*",
"0.65",
"*",
"alpha",
")",
"s",
".",
"_ctx",
".",
"drawpath",
"(",
"p",
".",
"copy",
"(",
")",
")",
"if",
"directed",
"and",
"s",
".",
"stroke",
":",
"#clr = s._ctx.stroke().copy()",
"clr",
"=",
"s",
".",
"_ctx",
".",
"color",
"(",
"s",
".",
"stroke",
".",
"r",
",",
"s",
".",
"stroke",
".",
"g",
",",
"s",
".",
"stroke",
".",
"b",
",",
"s",
".",
"stroke",
".",
"a",
"*",
"0.65",
"*",
"alpha",
")",
"clr",
".",
"a",
"*=",
"1.3",
"s",
".",
"_ctx",
".",
"stroke",
"(",
"clr",
")",
"s",
".",
"_ctx",
".",
"drawpath",
"(",
"pd",
".",
"copy",
"(",
")",
")",
"for",
"e",
"in",
"edges",
":",
"try",
":",
"s2",
"=",
"self",
".",
"styles",
"[",
"e",
".",
"node1",
".",
"style",
"]",
"except",
":",
"s2",
"=",
"s",
"if",
"s2",
".",
"edge_label",
":",
"s2",
".",
"edge_label",
"(",
"s2",
",",
"e",
",",
"alpha",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
edge
|
Visualization of a single edge between two nodes.
|
lib/graph/style.py
|
def edge(s, path, edge, alpha=1.0):
""" Visualization of a single edge between two nodes.
"""
path.moveto(edge.node1.x, edge.node1.y)
if edge.node2.style == BACK:
path.curveto(
edge.node1.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
)
else:
path.lineto(
edge.node2.x,
edge.node2.y
)
|
def edge(s, path, edge, alpha=1.0):
""" Visualization of a single edge between two nodes.
"""
path.moveto(edge.node1.x, edge.node1.y)
if edge.node2.style == BACK:
path.curveto(
edge.node1.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
)
else:
path.lineto(
edge.node2.x,
edge.node2.y
)
|
[
"Visualization",
"of",
"a",
"single",
"edge",
"between",
"two",
"nodes",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L385-L404
|
[
"def",
"edge",
"(",
"s",
",",
"path",
",",
"edge",
",",
"alpha",
"=",
"1.0",
")",
":",
"path",
".",
"moveto",
"(",
"edge",
".",
"node1",
".",
"x",
",",
"edge",
".",
"node1",
".",
"y",
")",
"if",
"edge",
".",
"node2",
".",
"style",
"==",
"BACK",
":",
"path",
".",
"curveto",
"(",
"edge",
".",
"node1",
".",
"x",
",",
"edge",
".",
"node2",
".",
"y",
",",
"edge",
".",
"node2",
".",
"x",
",",
"edge",
".",
"node2",
".",
"y",
",",
"edge",
".",
"node2",
".",
"x",
",",
"edge",
".",
"node2",
".",
"y",
",",
")",
"else",
":",
"path",
".",
"lineto",
"(",
"edge",
".",
"node2",
".",
"x",
",",
"edge",
".",
"node2",
".",
"y",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
edge_label
|
Visualization of the label accompanying an edge.
|
lib/graph/style.py
|
def edge_label(s, edge, alpha=1.0):
""" Visualization of the label accompanying an edge.
"""
if s.text and edge.label != "":
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
s.text.a * alpha*0.75
)
s._ctx.lineheight(1)
s._ctx.font(s.font)
s._ctx.fontsize(s.fontsize*0.75)
# Cache an outlined label text and translate it.
# This enhances the speed and avoids wiggling text.
try: p = edge._textpath
except:
try: txt = unicode(edge.label)
except:
try: txt = edge.label.decode("utf-8")
except:
pass
edge._textpath = s._ctx.textpath(txt, s._ctx.textwidth(" "), 0, width=s.textwidth)
p = edge._textpath
# Position the label centrally along the edge line.
a = degrees( atan2(edge.node2.y-edge.node1.y, edge.node2.x-edge.node1.x) )
d = sqrt((edge.node2.x-edge.node1.x)**2 +(edge.node2.y-edge.node1.y)**2)
d = abs(d-s._ctx.textwidth(edge.label)) * 0.5
s._ctx.push()
s._ctx.transform(CORNER)
s._ctx.translate(edge.node1.x, edge.node1.y)
s._ctx.rotate(-a)
s._ctx.translate(d, s.fontsize*1.0)
s._ctx.scale(alpha)
# Flip labels on the left hand side so they are legible.
if 90 < a%360 < 270:
s._ctx.translate(s._ctx.textwidth(edge.label), -s.fontsize*2.0)
s._ctx.transform(CENTER)
s._ctx.rotate(180)
s._ctx.transform(CORNER)
s._ctx.drawpath(p.copy())
s._ctx.pop()
|
def edge_label(s, edge, alpha=1.0):
""" Visualization of the label accompanying an edge.
"""
if s.text and edge.label != "":
s._ctx.nostroke()
s._ctx.fill(
s.text.r,
s.text.g,
s.text.b,
s.text.a * alpha*0.75
)
s._ctx.lineheight(1)
s._ctx.font(s.font)
s._ctx.fontsize(s.fontsize*0.75)
# Cache an outlined label text and translate it.
# This enhances the speed and avoids wiggling text.
try: p = edge._textpath
except:
try: txt = unicode(edge.label)
except:
try: txt = edge.label.decode("utf-8")
except:
pass
edge._textpath = s._ctx.textpath(txt, s._ctx.textwidth(" "), 0, width=s.textwidth)
p = edge._textpath
# Position the label centrally along the edge line.
a = degrees( atan2(edge.node2.y-edge.node1.y, edge.node2.x-edge.node1.x) )
d = sqrt((edge.node2.x-edge.node1.x)**2 +(edge.node2.y-edge.node1.y)**2)
d = abs(d-s._ctx.textwidth(edge.label)) * 0.5
s._ctx.push()
s._ctx.transform(CORNER)
s._ctx.translate(edge.node1.x, edge.node1.y)
s._ctx.rotate(-a)
s._ctx.translate(d, s.fontsize*1.0)
s._ctx.scale(alpha)
# Flip labels on the left hand side so they are legible.
if 90 < a%360 < 270:
s._ctx.translate(s._ctx.textwidth(edge.label), -s.fontsize*2.0)
s._ctx.transform(CENTER)
s._ctx.rotate(180)
s._ctx.transform(CORNER)
s._ctx.drawpath(p.copy())
s._ctx.pop()
|
[
"Visualization",
"of",
"the",
"label",
"accompanying",
"an",
"edge",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L439-L488
|
[
"def",
"edge_label",
"(",
"s",
",",
"edge",
",",
"alpha",
"=",
"1.0",
")",
":",
"if",
"s",
".",
"text",
"and",
"edge",
".",
"label",
"!=",
"\"\"",
":",
"s",
".",
"_ctx",
".",
"nostroke",
"(",
")",
"s",
".",
"_ctx",
".",
"fill",
"(",
"s",
".",
"text",
".",
"r",
",",
"s",
".",
"text",
".",
"g",
",",
"s",
".",
"text",
".",
"b",
",",
"s",
".",
"text",
".",
"a",
"*",
"alpha",
"*",
"0.75",
")",
"s",
".",
"_ctx",
".",
"lineheight",
"(",
"1",
")",
"s",
".",
"_ctx",
".",
"font",
"(",
"s",
".",
"font",
")",
"s",
".",
"_ctx",
".",
"fontsize",
"(",
"s",
".",
"fontsize",
"*",
"0.75",
")",
"# Cache an outlined label text and translate it.",
"# This enhances the speed and avoids wiggling text.",
"try",
":",
"p",
"=",
"edge",
".",
"_textpath",
"except",
":",
"try",
":",
"txt",
"=",
"unicode",
"(",
"edge",
".",
"label",
")",
"except",
":",
"try",
":",
"txt",
"=",
"edge",
".",
"label",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
":",
"pass",
"edge",
".",
"_textpath",
"=",
"s",
".",
"_ctx",
".",
"textpath",
"(",
"txt",
",",
"s",
".",
"_ctx",
".",
"textwidth",
"(",
"\" \"",
")",
",",
"0",
",",
"width",
"=",
"s",
".",
"textwidth",
")",
"p",
"=",
"edge",
".",
"_textpath",
"# Position the label centrally along the edge line.",
"a",
"=",
"degrees",
"(",
"atan2",
"(",
"edge",
".",
"node2",
".",
"y",
"-",
"edge",
".",
"node1",
".",
"y",
",",
"edge",
".",
"node2",
".",
"x",
"-",
"edge",
".",
"node1",
".",
"x",
")",
")",
"d",
"=",
"sqrt",
"(",
"(",
"edge",
".",
"node2",
".",
"x",
"-",
"edge",
".",
"node1",
".",
"x",
")",
"**",
"2",
"+",
"(",
"edge",
".",
"node2",
".",
"y",
"-",
"edge",
".",
"node1",
".",
"y",
")",
"**",
"2",
")",
"d",
"=",
"abs",
"(",
"d",
"-",
"s",
".",
"_ctx",
".",
"textwidth",
"(",
"edge",
".",
"label",
")",
")",
"*",
"0.5",
"s",
".",
"_ctx",
".",
"push",
"(",
")",
"s",
".",
"_ctx",
".",
"transform",
"(",
"CORNER",
")",
"s",
".",
"_ctx",
".",
"translate",
"(",
"edge",
".",
"node1",
".",
"x",
",",
"edge",
".",
"node1",
".",
"y",
")",
"s",
".",
"_ctx",
".",
"rotate",
"(",
"-",
"a",
")",
"s",
".",
"_ctx",
".",
"translate",
"(",
"d",
",",
"s",
".",
"fontsize",
"*",
"1.0",
")",
"s",
".",
"_ctx",
".",
"scale",
"(",
"alpha",
")",
"# Flip labels on the left hand side so they are legible.",
"if",
"90",
"<",
"a",
"%",
"360",
"<",
"270",
":",
"s",
".",
"_ctx",
".",
"translate",
"(",
"s",
".",
"_ctx",
".",
"textwidth",
"(",
"edge",
".",
"label",
")",
",",
"-",
"s",
".",
"fontsize",
"*",
"2.0",
")",
"s",
".",
"_ctx",
".",
"transform",
"(",
"CENTER",
")",
"s",
".",
"_ctx",
".",
"rotate",
"(",
"180",
")",
"s",
".",
"_ctx",
".",
"transform",
"(",
"CORNER",
")",
"s",
".",
"_ctx",
".",
"drawpath",
"(",
"p",
".",
"copy",
"(",
")",
")",
"s",
".",
"_ctx",
".",
"pop",
"(",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
path
|
Visualization of a shortest path between two nodes.
|
lib/graph/style.py
|
def path(s, graph, path):
""" Visualization of a shortest path between two nodes.
"""
def end(n):
r = n.r * 0.35
s._ctx.oval(n.x-r, n.y-r, r*2, r*2)
if path and len(path) > 1 and s.stroke:
s._ctx.nofill()
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a
)
if s.name != DEFAULT:
s._ctx.strokewidth(s.strokewidth)
else:
s._ctx.strokewidth(s.strokewidth*2)
first = True
for id in path:
n = graph[id]
if first:
first = False
s._ctx.beginpath(n.x, n.y)
end(n)
else:
s._ctx.lineto(n.x, n.y)
s._ctx.endpath()
end(n)
|
def path(s, graph, path):
""" Visualization of a shortest path between two nodes.
"""
def end(n):
r = n.r * 0.35
s._ctx.oval(n.x-r, n.y-r, r*2, r*2)
if path and len(path) > 1 and s.stroke:
s._ctx.nofill()
s._ctx.stroke(
s.stroke.r,
s.stroke.g,
s.stroke.b,
s.stroke.a
)
if s.name != DEFAULT:
s._ctx.strokewidth(s.strokewidth)
else:
s._ctx.strokewidth(s.strokewidth*2)
first = True
for id in path:
n = graph[id]
if first:
first = False
s._ctx.beginpath(n.x, n.y)
end(n)
else:
s._ctx.lineto(n.x, n.y)
s._ctx.endpath()
end(n)
|
[
"Visualization",
"of",
"a",
"shortest",
"path",
"between",
"two",
"nodes",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L492-L525
|
[
"def",
"path",
"(",
"s",
",",
"graph",
",",
"path",
")",
":",
"def",
"end",
"(",
"n",
")",
":",
"r",
"=",
"n",
".",
"r",
"*",
"0.35",
"s",
".",
"_ctx",
".",
"oval",
"(",
"n",
".",
"x",
"-",
"r",
",",
"n",
".",
"y",
"-",
"r",
",",
"r",
"*",
"2",
",",
"r",
"*",
"2",
")",
"if",
"path",
"and",
"len",
"(",
"path",
")",
">",
"1",
"and",
"s",
".",
"stroke",
":",
"s",
".",
"_ctx",
".",
"nofill",
"(",
")",
"s",
".",
"_ctx",
".",
"stroke",
"(",
"s",
".",
"stroke",
".",
"r",
",",
"s",
".",
"stroke",
".",
"g",
",",
"s",
".",
"stroke",
".",
"b",
",",
"s",
".",
"stroke",
".",
"a",
")",
"if",
"s",
".",
"name",
"!=",
"DEFAULT",
":",
"s",
".",
"_ctx",
".",
"strokewidth",
"(",
"s",
".",
"strokewidth",
")",
"else",
":",
"s",
".",
"_ctx",
".",
"strokewidth",
"(",
"s",
".",
"strokewidth",
"*",
"2",
")",
"first",
"=",
"True",
"for",
"id",
"in",
"path",
":",
"n",
"=",
"graph",
"[",
"id",
"]",
"if",
"first",
":",
"first",
"=",
"False",
"s",
".",
"_ctx",
".",
"beginpath",
"(",
"n",
".",
"x",
",",
"n",
".",
"y",
")",
"end",
"(",
"n",
")",
"else",
":",
"s",
".",
"_ctx",
".",
"lineto",
"(",
"n",
".",
"x",
",",
"n",
".",
"y",
")",
"s",
".",
"_ctx",
".",
"endpath",
"(",
")",
"end",
"(",
"n",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
styles.create
|
Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
|
lib/graph/style.py
|
def create(self, stylename, **kwargs):
""" Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
"""
if stylename == "default":
self[stylename] = style(stylename, self._ctx, **kwargs)
return self[stylename]
k = kwargs.get("template", "default")
s = self[stylename] = self[k].copy(stylename)
for attr in kwargs:
if s.__dict__.has_key(attr):
s.__dict__[attr] = kwargs[attr]
return s
|
def create(self, stylename, **kwargs):
""" Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
"""
if stylename == "default":
self[stylename] = style(stylename, self._ctx, **kwargs)
return self[stylename]
k = kwargs.get("template", "default")
s = self[stylename] = self[k].copy(stylename)
for attr in kwargs:
if s.__dict__.has_key(attr):
s.__dict__[attr] = kwargs[attr]
return s
|
[
"Creates",
"a",
"new",
"style",
"which",
"inherits",
"from",
"the",
"default",
"style",
"or",
"any",
"other",
"style",
"which",
"name",
"is",
"supplied",
"to",
"the",
"optional",
"template",
"parameter",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L29-L41
|
[
"def",
"create",
"(",
"self",
",",
"stylename",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"stylename",
"==",
"\"default\"",
":",
"self",
"[",
"stylename",
"]",
"=",
"style",
"(",
"stylename",
",",
"self",
".",
"_ctx",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
"[",
"stylename",
"]",
"k",
"=",
"kwargs",
".",
"get",
"(",
"\"template\"",
",",
"\"default\"",
")",
"s",
"=",
"self",
"[",
"stylename",
"]",
"=",
"self",
"[",
"k",
"]",
".",
"copy",
"(",
"stylename",
")",
"for",
"attr",
"in",
"kwargs",
":",
"if",
"s",
".",
"__dict__",
".",
"has_key",
"(",
"attr",
")",
":",
"s",
".",
"__dict__",
"[",
"attr",
"]",
"=",
"kwargs",
"[",
"attr",
"]",
"return",
"s"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
styles.copy
|
Returns a copy of all styles and a copy of the styleguide.
|
lib/graph/style.py
|
def copy(self, graph):
""" Returns a copy of all styles and a copy of the styleguide.
"""
s = styles(graph)
s.guide = self.guide.copy(graph)
dict.__init__(s, [(v.name, v.copy()) for v in self.values()])
return s
|
def copy(self, graph):
""" Returns a copy of all styles and a copy of the styleguide.
"""
s = styles(graph)
s.guide = self.guide.copy(graph)
dict.__init__(s, [(v.name, v.copy()) for v in self.values()])
return s
|
[
"Returns",
"a",
"copy",
"of",
"all",
"styles",
"and",
"a",
"copy",
"of",
"the",
"styleguide",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L64-L70
|
[
"def",
"copy",
"(",
"self",
",",
"graph",
")",
":",
"s",
"=",
"styles",
"(",
"graph",
")",
"s",
".",
"guide",
"=",
"self",
".",
"guide",
".",
"copy",
"(",
"graph",
")",
"dict",
".",
"__init__",
"(",
"s",
",",
"[",
"(",
"v",
".",
"name",
",",
"v",
".",
"copy",
"(",
")",
")",
"for",
"v",
"in",
"self",
".",
"values",
"(",
")",
"]",
")",
"return",
"s"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
styleguide.apply
|
Check the rules for each node in the graph and apply the style.
|
lib/graph/style.py
|
def apply(self):
""" Check the rules for each node in the graph and apply the style.
"""
sorted = self.order + self.keys()
unique = []; [unique.append(x) for x in sorted if x not in unique]
for node in self.graph.nodes:
for s in unique:
if self.has_key(s) and self[s](self.graph, node):
node.style = s
|
def apply(self):
""" Check the rules for each node in the graph and apply the style.
"""
sorted = self.order + self.keys()
unique = []; [unique.append(x) for x in sorted if x not in unique]
for node in self.graph.nodes:
for s in unique:
if self.has_key(s) and self[s](self.graph, node):
node.style = s
|
[
"Check",
"the",
"rules",
"for",
"each",
"node",
"in",
"the",
"graph",
"and",
"apply",
"the",
"style",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L94-L102
|
[
"def",
"apply",
"(",
"self",
")",
":",
"sorted",
"=",
"self",
".",
"order",
"+",
"self",
".",
"keys",
"(",
")",
"unique",
"=",
"[",
"]",
"[",
"unique",
".",
"append",
"(",
"x",
")",
"for",
"x",
"in",
"sorted",
"if",
"x",
"not",
"in",
"unique",
"]",
"for",
"node",
"in",
"self",
".",
"graph",
".",
"nodes",
":",
"for",
"s",
"in",
"unique",
":",
"if",
"self",
".",
"has_key",
"(",
"s",
")",
"and",
"self",
"[",
"s",
"]",
"(",
"self",
".",
"graph",
",",
"node",
")",
":",
"node",
".",
"style",
"=",
"s"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
styleguide.copy
|
Returns a copy of the styleguide for the given graph.
|
lib/graph/style.py
|
def copy(self, graph):
""" Returns a copy of the styleguide for the given graph.
"""
g = styleguide(graph)
g.order = self.order
dict.__init__(g, [(k, v) for k, v in self.iteritems()])
return g
|
def copy(self, graph):
""" Returns a copy of the styleguide for the given graph.
"""
g = styleguide(graph)
g.order = self.order
dict.__init__(g, [(k, v) for k, v in self.iteritems()])
return g
|
[
"Returns",
"a",
"copy",
"of",
"the",
"styleguide",
"for",
"the",
"given",
"graph",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/style.py#L104-L110
|
[
"def",
"copy",
"(",
"self",
",",
"graph",
")",
":",
"g",
"=",
"styleguide",
"(",
"graph",
")",
"g",
".",
"order",
"=",
"self",
".",
"order",
"dict",
".",
"__init__",
"(",
"g",
",",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iteritems",
"(",
")",
"]",
")",
"return",
"g"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
JSONDecoder.raw_decode
|
Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
|
lib/web/simplejson/decoder.py
|
def raw_decode(self, s, **kw):
"""
Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
kw.setdefault('context', self)
try:
obj, end = self._scanner.iterscan(s, **kw).next()
except StopIteration:
raise ValueError("No JSON object could be decoded")
return obj, end
|
def raw_decode(self, s, **kw):
"""
Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
kw.setdefault('context', self)
try:
obj, end = self._scanner.iterscan(s, **kw).next()
except StopIteration:
raise ValueError("No JSON object could be decoded")
return obj, end
|
[
"Decode",
"a",
"JSON",
"document",
"from",
"s",
"(",
"a",
"str",
"or",
"unicode",
"beginning",
"with",
"a",
"JSON",
"document",
")",
"and",
"return",
"a",
"2",
"-",
"tuple",
"of",
"the",
"Python",
"representation",
"and",
"the",
"index",
"in",
"s",
"where",
"the",
"document",
"ended",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/simplejson/decoder.py#L327-L341
|
[
"def",
"raw_decode",
"(",
"self",
",",
"s",
",",
"*",
"*",
"kw",
")",
":",
"kw",
".",
"setdefault",
"(",
"'context'",
",",
"self",
")",
"try",
":",
"obj",
",",
"end",
"=",
"self",
".",
"_scanner",
".",
"iterscan",
"(",
"s",
",",
"*",
"*",
"kw",
")",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"raise",
"ValueError",
"(",
"\"No JSON object could be decoded\"",
")",
"return",
"obj",
",",
"end"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
Tracking.open_socket
|
Opens the socket and binds to the given host and port. Uses
SO_REUSEADDR to be as robust as possible.
|
lib/tuio/__init__.py
|
def open_socket(self):
"""
Opens the socket and binds to the given host and port. Uses
SO_REUSEADDR to be as robust as possible.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setblocking(0)
self.socket.bind((self.host, self.port))
|
def open_socket(self):
"""
Opens the socket and binds to the given host and port. Uses
SO_REUSEADDR to be as robust as possible.
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setblocking(0)
self.socket.bind((self.host, self.port))
|
[
"Opens",
"the",
"socket",
"and",
"binds",
"to",
"the",
"given",
"host",
"and",
"port",
".",
"Uses",
"SO_REUSEADDR",
"to",
"be",
"as",
"robust",
"as",
"possible",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L33-L41
|
[
"def",
"open_socket",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"self",
".",
"socket",
".",
"setblocking",
"(",
"0",
")",
"self",
".",
"socket",
".",
"bind",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
Tracking.load_profiles
|
Loads all possible TUIO profiles and returns a dictionary with the
profile addresses as keys and an instance of a profile as the value
|
lib/tuio/__init__.py
|
def load_profiles(self):
"""
Loads all possible TUIO profiles and returns a dictionary with the
profile addresses as keys and an instance of a profile as the value
"""
_profiles = {}
for name, klass in inspect.getmembers(profiles):
if inspect.isclass(klass) and name.endswith('Profile') and name != 'TuioProfile':
# Adding profile to the self.profiles dictionary
profile = klass()
_profiles[profile.address] = profile
# setting convenient variable to access objects of profile
try:
setattr(self, profile.list_label, profile.objs)
except AttributeError:
continue
# Mapping callback method to every profile
self.manager.add(self.callback, profile.address)
return _profiles
|
def load_profiles(self):
"""
Loads all possible TUIO profiles and returns a dictionary with the
profile addresses as keys and an instance of a profile as the value
"""
_profiles = {}
for name, klass in inspect.getmembers(profiles):
if inspect.isclass(klass) and name.endswith('Profile') and name != 'TuioProfile':
# Adding profile to the self.profiles dictionary
profile = klass()
_profiles[profile.address] = profile
# setting convenient variable to access objects of profile
try:
setattr(self, profile.list_label, profile.objs)
except AttributeError:
continue
# Mapping callback method to every profile
self.manager.add(self.callback, profile.address)
return _profiles
|
[
"Loads",
"all",
"possible",
"TUIO",
"profiles",
"and",
"returns",
"a",
"dictionary",
"with",
"the",
"profile",
"addresses",
"as",
"keys",
"and",
"an",
"instance",
"of",
"a",
"profile",
"as",
"the",
"value"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L57-L75
|
[
"def",
"load_profiles",
"(",
"self",
")",
":",
"_profiles",
"=",
"{",
"}",
"for",
"name",
",",
"klass",
"in",
"inspect",
".",
"getmembers",
"(",
"profiles",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"klass",
")",
"and",
"name",
".",
"endswith",
"(",
"'Profile'",
")",
"and",
"name",
"!=",
"'TuioProfile'",
":",
"# Adding profile to the self.profiles dictionary",
"profile",
"=",
"klass",
"(",
")",
"_profiles",
"[",
"profile",
".",
"address",
"]",
"=",
"profile",
"# setting convenient variable to access objects of profile",
"try",
":",
"setattr",
"(",
"self",
",",
"profile",
".",
"list_label",
",",
"profile",
".",
"objs",
")",
"except",
"AttributeError",
":",
"continue",
"# Mapping callback method to every profile",
"self",
".",
"manager",
".",
"add",
"(",
"self",
".",
"callback",
",",
"profile",
".",
"address",
")",
"return",
"_profiles"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
Tracking.update
|
Tells the connection manager to receive the next 1024 byte of messages
to analyze.
|
lib/tuio/__init__.py
|
def update(self):
"""
Tells the connection manager to receive the next 1024 byte of messages
to analyze.
"""
try:
self.manager.handle(self.socket.recv(1024))
except socket.error:
pass
|
def update(self):
"""
Tells the connection manager to receive the next 1024 byte of messages
to analyze.
"""
try:
self.manager.handle(self.socket.recv(1024))
except socket.error:
pass
|
[
"Tells",
"the",
"connection",
"manager",
"to",
"receive",
"the",
"next",
"1024",
"byte",
"of",
"messages",
"to",
"analyze",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L86-L94
|
[
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"manager",
".",
"handle",
"(",
"self",
".",
"socket",
".",
"recv",
"(",
"1024",
")",
")",
"except",
"socket",
".",
"error",
":",
"pass"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
Tracking.callback
|
Gets called by the CallbackManager if a new message was received
|
lib/tuio/__init__.py
|
def callback(self, *incoming):
"""
Gets called by the CallbackManager if a new message was received
"""
message = incoming[0]
if message:
address, command = message[0], message[2]
profile = self.get_profile(address)
if profile is not None:
try:
getattr(profile, command)(self, message)
except AttributeError:
pass
|
def callback(self, *incoming):
"""
Gets called by the CallbackManager if a new message was received
"""
message = incoming[0]
if message:
address, command = message[0], message[2]
profile = self.get_profile(address)
if profile is not None:
try:
getattr(profile, command)(self, message)
except AttributeError:
pass
|
[
"Gets",
"called",
"by",
"the",
"CallbackManager",
"if",
"a",
"new",
"message",
"was",
"received"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/tuio/__init__.py#L96-L108
|
[
"def",
"callback",
"(",
"self",
",",
"*",
"incoming",
")",
":",
"message",
"=",
"incoming",
"[",
"0",
"]",
"if",
"message",
":",
"address",
",",
"command",
"=",
"message",
"[",
"0",
"]",
",",
"message",
"[",
"2",
"]",
"profile",
"=",
"self",
".",
"get_profile",
"(",
"address",
")",
"if",
"profile",
"is",
"not",
"None",
":",
"try",
":",
"getattr",
"(",
"profile",
",",
"command",
")",
"(",
"self",
",",
"message",
")",
"except",
"AttributeError",
":",
"pass"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
copytree
|
copytree that works even if folder already exists
|
extensions/gedit/gedit2-plugin/install.py
|
def copytree(src, dst, symlinks=False, ignore=None):
"""
copytree that works even if folder already exists
"""
# http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
|
def copytree(src, dst, symlinks=False, ignore=None):
"""
copytree that works even if folder already exists
"""
# http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
|
[
"copytree",
"that",
"works",
"even",
"if",
"folder",
"already",
"exists"
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/gedit/gedit2-plugin/install.py#L28-L56
|
[
"def",
"copytree",
"(",
"src",
",",
"dst",
",",
"symlinks",
"=",
"False",
",",
"ignore",
"=",
"None",
")",
":",
"# http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst",
")",
":",
"os",
".",
"makedirs",
"(",
"dst",
")",
"shutil",
".",
"copystat",
"(",
"src",
",",
"dst",
")",
"lst",
"=",
"os",
".",
"listdir",
"(",
"src",
")",
"if",
"ignore",
":",
"excl",
"=",
"ignore",
"(",
"src",
",",
"lst",
")",
"lst",
"=",
"[",
"x",
"for",
"x",
"in",
"lst",
"if",
"x",
"not",
"in",
"excl",
"]",
"for",
"item",
"in",
"lst",
":",
"s",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src",
",",
"item",
")",
"d",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"item",
")",
"if",
"symlinks",
"and",
"os",
".",
"path",
".",
"islink",
"(",
"s",
")",
":",
"if",
"os",
".",
"path",
".",
"lexists",
"(",
"d",
")",
":",
"os",
".",
"remove",
"(",
"d",
")",
"os",
".",
"symlink",
"(",
"os",
".",
"readlink",
"(",
"s",
")",
",",
"d",
")",
"try",
":",
"st",
"=",
"os",
".",
"lstat",
"(",
"s",
")",
"mode",
"=",
"stat",
".",
"S_IMODE",
"(",
"st",
".",
"st_mode",
")",
"os",
".",
"lchmod",
"(",
"d",
",",
"mode",
")",
"except",
":",
"pass",
"# lchmod not available",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"s",
")",
":",
"copytree",
"(",
"s",
",",
"d",
",",
"symlinks",
",",
"ignore",
")",
"else",
":",
"shutil",
".",
"copy2",
"(",
"s",
",",
"d",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
dumps
|
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
|
lib/web/simplejson/__init__.py
|
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
**kw).encode(obj)
|
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
**kw).encode(obj)
|
[
"Serialize",
"obj",
"to",
"a",
"JSON",
"formatted",
"str",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/simplejson/__init__.py#L188-L241
|
[
"def",
"dumps",
"(",
"obj",
",",
"skipkeys",
"=",
"False",
",",
"ensure_ascii",
"=",
"True",
",",
"check_circular",
"=",
"True",
",",
"allow_nan",
"=",
"True",
",",
"cls",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"# cached encoder",
"if",
"(",
"skipkeys",
"is",
"False",
"and",
"ensure_ascii",
"is",
"True",
"and",
"check_circular",
"is",
"True",
"and",
"allow_nan",
"is",
"True",
"and",
"cls",
"is",
"None",
"and",
"indent",
"is",
"None",
"and",
"separators",
"is",
"None",
"and",
"encoding",
"==",
"'utf-8'",
"and",
"default",
"is",
"None",
"and",
"not",
"kw",
")",
":",
"return",
"_default_encoder",
".",
"encode",
"(",
"obj",
")",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"JSONEncoder",
"return",
"cls",
"(",
"skipkeys",
"=",
"skipkeys",
",",
"ensure_ascii",
"=",
"ensure_ascii",
",",
"check_circular",
"=",
"check_circular",
",",
"allow_nan",
"=",
"allow_nan",
",",
"indent",
"=",
"indent",
",",
"separators",
"=",
"separators",
",",
"encoding",
"=",
"encoding",
",",
"default",
"=",
"default",
",",
"*",
"*",
"kw",
")",
".",
"encode",
"(",
"obj",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
valid
|
search
|
Returns a Google web query formatted as a GoogleSearch list object.
|
lib/web/google.py
|
def search(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google web query formatted as a GoogleSearch list object.
"""
service = GOOGLE_SEARCH
return GoogleSearch(q, start, service, "", wait, asynchronous, cached)
|
def search(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google web query formatted as a GoogleSearch list object.
"""
service = GOOGLE_SEARCH
return GoogleSearch(q, start, service, "", wait, asynchronous, cached)
|
[
"Returns",
"a",
"Google",
"web",
"query",
"formatted",
"as",
"a",
"GoogleSearch",
"list",
"object",
"."
] |
shoebot/shoebot
|
python
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/google.py#L212-L218
|
[
"def",
"search",
"(",
"q",
",",
"start",
"=",
"0",
",",
"wait",
"=",
"10",
",",
"asynchronous",
"=",
"False",
",",
"cached",
"=",
"False",
")",
":",
"service",
"=",
"GOOGLE_SEARCH",
"return",
"GoogleSearch",
"(",
"q",
",",
"start",
",",
"service",
",",
"\"\"",
",",
"wait",
",",
"asynchronous",
",",
"cached",
")"
] |
d554c1765c1899fa25727c9fc6805d221585562b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.