id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
10,700 | tonioo/sievelib | sievelib/parser.py | Lexer.scan | def scan(self, text):
"""Analyse some data
Analyse the passed content. Each time a token is recognized, a
2-uple containing its name and parsed value is raised (via
yield).
On error, a ParseError exception is raised.
:param text: a binary string containing the data to parse
"""
self.pos = 0
self.text = text
while self.pos < len(text):
m = self.wsregexp.match(text, self.pos)
if m is not None:
self.pos = m.end()
continue
m = self.regexp.match(text, self.pos)
if m is None:
raise ParseError("unknown token %s" % text[self.pos:])
self.pos = m.end()
yield (m.lastgroup, m.group(m.lastgroup)) | python | def scan(self, text):
self.pos = 0
self.text = text
while self.pos < len(text):
m = self.wsregexp.match(text, self.pos)
if m is not None:
self.pos = m.end()
continue
m = self.regexp.match(text, self.pos)
if m is None:
raise ParseError("unknown token %s" % text[self.pos:])
self.pos = m.end()
yield (m.lastgroup, m.group(m.lastgroup)) | [
"def",
"scan",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"pos",
"=",
"0",
"self",
".",
"text",
"=",
"text",
"while",
"self",
".",
"pos",
"<",
"len",
"(",
"text",
")",
":",
"m",
"=",
"self",
".",
"wsregexp",
".",
"match",
"(",
"text",
"... | Analyse some data
Analyse the passed content. Each time a token is recognized, a
2-uple containing its name and parsed value is raised (via
yield).
On error, a ParseError exception is raised.
:param text: a binary string containing the data to parse | [
"Analyse",
"some",
"data"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L63-L87 |
10,701 | tonioo/sievelib | sievelib/parser.py | Parser.__reset_parser | def __reset_parser(self):
"""Reset parser's internal variables
Restore the parser to an initial state. Useful when creating a
new parser or reusing an existing one.
"""
self.result = []
self.hash_comments = []
self.__cstate = None
self.__curcommand = None
self.__curstringlist = None
self.__expected = None
self.__opened_blocks = 0
RequireCommand.loaded_extensions = [] | python | def __reset_parser(self):
self.result = []
self.hash_comments = []
self.__cstate = None
self.__curcommand = None
self.__curstringlist = None
self.__expected = None
self.__opened_blocks = 0
RequireCommand.loaded_extensions = [] | [
"def",
"__reset_parser",
"(",
"self",
")",
":",
"self",
".",
"result",
"=",
"[",
"]",
"self",
".",
"hash_comments",
"=",
"[",
"]",
"self",
".",
"__cstate",
"=",
"None",
"self",
".",
"__curcommand",
"=",
"None",
"self",
".",
"__curstringlist",
"=",
"Non... | Reset parser's internal variables
Restore the parser to an initial state. Useful when creating a
new parser or reusing an existing one. | [
"Reset",
"parser",
"s",
"internal",
"variables"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L124-L138 |
10,702 | tonioo/sievelib | sievelib/parser.py | Parser.__up | def __up(self, onlyrecord=False):
"""Return to the current command's parent
This method should be called each time a command is
complete. In case of a top level command (no parent), it is
recorded into a specific list for further usage.
:param onlyrecord: tell to only record the new command into its parent.
"""
if self.__curcommand.must_follow is not None:
if not self.__curcommand.parent:
prevcmd = self.result[-1] if len(self.result) else None
else:
prevcmd = self.__curcommand.parent.children[-2] \
if len(self.__curcommand.parent.children) >= 2 else None
if prevcmd is None or prevcmd.name not in self.__curcommand.must_follow:
raise ParseError("the %s command must follow an %s command" %
(self.__curcommand.name,
" or ".join(self.__curcommand.must_follow)))
if not self.__curcommand.parent:
# collect current amount of hash comments for later
# parsing into names and desciptions
self.__curcommand.hash_comments = self.hash_comments
self.hash_comments = []
self.result += [self.__curcommand]
if not onlyrecord:
while self.__curcommand:
self.__curcommand = self.__curcommand.parent
# Make sure to detect all done tests (including 'not' ones).
condition = (
self.__curcommand and
self.__curcommand.get_type() == "test" and
self.__curcommand.iscomplete()
)
if condition:
continue
break | python | def __up(self, onlyrecord=False):
if self.__curcommand.must_follow is not None:
if not self.__curcommand.parent:
prevcmd = self.result[-1] if len(self.result) else None
else:
prevcmd = self.__curcommand.parent.children[-2] \
if len(self.__curcommand.parent.children) >= 2 else None
if prevcmd is None or prevcmd.name not in self.__curcommand.must_follow:
raise ParseError("the %s command must follow an %s command" %
(self.__curcommand.name,
" or ".join(self.__curcommand.must_follow)))
if not self.__curcommand.parent:
# collect current amount of hash comments for later
# parsing into names and desciptions
self.__curcommand.hash_comments = self.hash_comments
self.hash_comments = []
self.result += [self.__curcommand]
if not onlyrecord:
while self.__curcommand:
self.__curcommand = self.__curcommand.parent
# Make sure to detect all done tests (including 'not' ones).
condition = (
self.__curcommand and
self.__curcommand.get_type() == "test" and
self.__curcommand.iscomplete()
)
if condition:
continue
break | [
"def",
"__up",
"(",
"self",
",",
"onlyrecord",
"=",
"False",
")",
":",
"if",
"self",
".",
"__curcommand",
".",
"must_follow",
"is",
"not",
"None",
":",
"if",
"not",
"self",
".",
"__curcommand",
".",
"parent",
":",
"prevcmd",
"=",
"self",
".",
"result",... | Return to the current command's parent
This method should be called each time a command is
complete. In case of a top level command (no parent), it is
recorded into a specific list for further usage.
:param onlyrecord: tell to only record the new command into its parent. | [
"Return",
"to",
"the",
"current",
"command",
"s",
"parent"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L148-L186 |
10,703 | tonioo/sievelib | sievelib/parser.py | Parser.__stringlist | def __stringlist(self, ttype, tvalue):
"""Specific method to parse the 'string-list' type
Syntax:
string-list = "[" string *("," string) "]" / string
; if there is only a single string, the brackets
; are optional
"""
if ttype == "string":
self.__curstringlist += [tvalue.decode("utf-8")]
self.__set_expected("comma", "right_bracket")
return True
if ttype == "comma":
self.__set_expected("string")
return True
if ttype == "right_bracket":
self.__curcommand.check_next_arg("stringlist", self.__curstringlist)
self.__cstate = self.__arguments
return self.__check_command_completion()
return False | python | def __stringlist(self, ttype, tvalue):
if ttype == "string":
self.__curstringlist += [tvalue.decode("utf-8")]
self.__set_expected("comma", "right_bracket")
return True
if ttype == "comma":
self.__set_expected("string")
return True
if ttype == "right_bracket":
self.__curcommand.check_next_arg("stringlist", self.__curstringlist)
self.__cstate = self.__arguments
return self.__check_command_completion()
return False | [
"def",
"__stringlist",
"(",
"self",
",",
"ttype",
",",
"tvalue",
")",
":",
"if",
"ttype",
"==",
"\"string\"",
":",
"self",
".",
"__curstringlist",
"+=",
"[",
"tvalue",
".",
"decode",
"(",
"\"utf-8\"",
")",
"]",
"self",
".",
"__set_expected",
"(",
"\"comm... | Specific method to parse the 'string-list' type
Syntax:
string-list = "[" string *("," string) "]" / string
; if there is only a single string, the brackets
; are optional | [
"Specific",
"method",
"to",
"parse",
"the",
"string",
"-",
"list",
"type"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L230-L249 |
10,704 | tonioo/sievelib | sievelib/parser.py | Parser.__argument | def __argument(self, ttype, tvalue):
"""Argument parsing method
This method acts as an entry point for 'argument' parsing.
Syntax:
string-list / number / tag
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is encountered, True otherwise
"""
if ttype in ["multiline", "string"]:
return self.__curcommand.check_next_arg("string", tvalue.decode("utf-8"))
if ttype in ["number", "tag"]:
return self.__curcommand.check_next_arg(ttype, tvalue.decode("ascii"))
if ttype == "left_bracket":
self.__cstate = self.__stringlist
self.__curstringlist = []
self.__set_expected("string")
return True
condition = (
ttype in ["left_cbracket", "comma"] and
self.__curcommand.non_deterministic_args
)
if condition:
self.__curcommand.reassign_arguments()
# rewind lexer
self.lexer.pos -= 1
return True
return False | python | def __argument(self, ttype, tvalue):
if ttype in ["multiline", "string"]:
return self.__curcommand.check_next_arg("string", tvalue.decode("utf-8"))
if ttype in ["number", "tag"]:
return self.__curcommand.check_next_arg(ttype, tvalue.decode("ascii"))
if ttype == "left_bracket":
self.__cstate = self.__stringlist
self.__curstringlist = []
self.__set_expected("string")
return True
condition = (
ttype in ["left_cbracket", "comma"] and
self.__curcommand.non_deterministic_args
)
if condition:
self.__curcommand.reassign_arguments()
# rewind lexer
self.lexer.pos -= 1
return True
return False | [
"def",
"__argument",
"(",
"self",
",",
"ttype",
",",
"tvalue",
")",
":",
"if",
"ttype",
"in",
"[",
"\"multiline\"",
",",
"\"string\"",
"]",
":",
"return",
"self",
".",
"__curcommand",
".",
"check_next_arg",
"(",
"\"string\"",
",",
"tvalue",
".",
"decode",
... | Argument parsing method
This method acts as an entry point for 'argument' parsing.
Syntax:
string-list / number / tag
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is encountered, True otherwise | [
"Argument",
"parsing",
"method"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L251-L285 |
10,705 | tonioo/sievelib | sievelib/parser.py | Parser.__arguments | def __arguments(self, ttype, tvalue):
"""Arguments parsing method
Entry point for command arguments parsing. The parser must
call this method for each parsed command (either a control,
action or test).
Syntax:
*argument [ test / test-list ]
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is encountered, True otherwise
"""
if ttype == "identifier":
test = get_command_instance(tvalue.decode("ascii"), self.__curcommand)
self.__curcommand.check_next_arg("test", test)
self.__expected = test.get_expected_first()
self.__curcommand = test
return self.__check_command_completion(testsemicolon=False)
if ttype == "left_parenthesis":
self.__set_expected("identifier")
return True
if ttype == "comma":
self.__set_expected("identifier")
return True
if ttype == "right_parenthesis":
self.__up()
return True
if self.__argument(ttype, tvalue):
return self.__check_command_completion(testsemicolon=False)
return False | python | def __arguments(self, ttype, tvalue):
if ttype == "identifier":
test = get_command_instance(tvalue.decode("ascii"), self.__curcommand)
self.__curcommand.check_next_arg("test", test)
self.__expected = test.get_expected_first()
self.__curcommand = test
return self.__check_command_completion(testsemicolon=False)
if ttype == "left_parenthesis":
self.__set_expected("identifier")
return True
if ttype == "comma":
self.__set_expected("identifier")
return True
if ttype == "right_parenthesis":
self.__up()
return True
if self.__argument(ttype, tvalue):
return self.__check_command_completion(testsemicolon=False)
return False | [
"def",
"__arguments",
"(",
"self",
",",
"ttype",
",",
"tvalue",
")",
":",
"if",
"ttype",
"==",
"\"identifier\"",
":",
"test",
"=",
"get_command_instance",
"(",
"tvalue",
".",
"decode",
"(",
"\"ascii\"",
")",
",",
"self",
".",
"__curcommand",
")",
"self",
... | Arguments parsing method
Entry point for command arguments parsing. The parser must
call this method for each parsed command (either a control,
action or test).
Syntax:
*argument [ test / test-list ]
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is encountered, True otherwise | [
"Arguments",
"parsing",
"method"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L287-L323 |
10,706 | tonioo/sievelib | sievelib/parser.py | Parser.__command | def __command(self, ttype, tvalue):
"""Command parsing method
Entry point for command parsing. Here is expected behaviour:
* Handle command beginning if detected,
* Call the appropriate sub-method (specified by __cstate) to
handle the body,
* Handle command ending or block opening if detected.
Syntax:
identifier arguments (";" / block)
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is encountered, True otherwise
"""
if self.__cstate is None:
if ttype == "right_cbracket":
self.__up()
self.__opened_blocks -= 1
self.__cstate = None
return True
if ttype != "identifier":
return False
command = get_command_instance(
tvalue.decode("ascii"), self.__curcommand)
if command.get_type() == "test":
raise ParseError(
"%s may not appear as a first command" % command.name)
if command.get_type() == "control" and command.accept_children \
and command.has_arguments():
self.__set_expected("identifier")
if self.__curcommand is not None:
if not self.__curcommand.addchild(command):
raise ParseError("%s unexpected after a %s" %
(tvalue, self.__curcommand.name))
self.__curcommand = command
self.__cstate = self.__arguments
return True
if self.__cstate(ttype, tvalue):
return True
if ttype == "left_cbracket":
self.__opened_blocks += 1
self.__cstate = None
return True
if ttype == "semicolon":
self.__cstate = None
if not self.__check_command_completion(testsemicolon=False):
return False
self.__curcommand.complete_cb()
self.__up()
return True
return False | python | def __command(self, ttype, tvalue):
if self.__cstate is None:
if ttype == "right_cbracket":
self.__up()
self.__opened_blocks -= 1
self.__cstate = None
return True
if ttype != "identifier":
return False
command = get_command_instance(
tvalue.decode("ascii"), self.__curcommand)
if command.get_type() == "test":
raise ParseError(
"%s may not appear as a first command" % command.name)
if command.get_type() == "control" and command.accept_children \
and command.has_arguments():
self.__set_expected("identifier")
if self.__curcommand is not None:
if not self.__curcommand.addchild(command):
raise ParseError("%s unexpected after a %s" %
(tvalue, self.__curcommand.name))
self.__curcommand = command
self.__cstate = self.__arguments
return True
if self.__cstate(ttype, tvalue):
return True
if ttype == "left_cbracket":
self.__opened_blocks += 1
self.__cstate = None
return True
if ttype == "semicolon":
self.__cstate = None
if not self.__check_command_completion(testsemicolon=False):
return False
self.__curcommand.complete_cb()
self.__up()
return True
return False | [
"def",
"__command",
"(",
"self",
",",
"ttype",
",",
"tvalue",
")",
":",
"if",
"self",
".",
"__cstate",
"is",
"None",
":",
"if",
"ttype",
"==",
"\"right_cbracket\"",
":",
"self",
".",
"__up",
"(",
")",
"self",
".",
"__opened_blocks",
"-=",
"1",
"self",
... | Command parsing method
Entry point for command parsing. Here is expected behaviour:
* Handle command beginning if detected,
* Call the appropriate sub-method (specified by __cstate) to
handle the body,
* Handle command ending or block opening if detected.
Syntax:
identifier arguments (";" / block)
:param ttype: current token type
:param tvalue: current token value
:return: False if an error is encountered, True otherwise | [
"Command",
"parsing",
"method"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L325-L382 |
10,707 | tonioo/sievelib | sievelib/parser.py | Parser.parse | def parse(self, text):
"""The parser entry point.
Parse the provided text to check for its validity.
On success, the parsing tree is available into the result
attribute. It is a list of sievecommands.Command objects (see
the module documentation for specific information).
On error, an string containing the explicit reason is
available into the error attribute.
:param text: a string containing the data to parse
:return: True on success (no error detected), False otherwise
"""
if isinstance(text, text_type):
text = text.encode("utf-8")
self.__reset_parser()
try:
for ttype, tvalue in self.lexer.scan(text):
if ttype == "hash_comment":
self.hash_comments += [tvalue.strip()]
continue
if ttype == "bracket_comment":
continue
if self.__expected is not None:
if ttype not in self.__expected:
if self.lexer.pos < len(text):
msg = (
"%s found while %s expected near '%s'"
% (ttype, "|".join(self.__expected),
text[self.lexer.pos])
)
else:
msg = (
"%s found while %s expected at end of file"
% (ttype, "|".join(self.__expected))
)
raise ParseError(msg)
self.__expected = None
if not self.__command(ttype, tvalue):
msg = (
"unexpected token '%s' found near '%s'"
% (tvalue.decode(), text.decode()[self.lexer.pos])
)
raise ParseError(msg)
if self.__opened_blocks:
self.__set_expected("right_cbracket")
if self.__expected is not None:
raise ParseError("end of script reached while %s expected" %
"|".join(self.__expected))
except (ParseError, CommandError) as e:
self.error = "line %d: %s" % (self.lexer.curlineno(), str(e))
return False
return True | python | def parse(self, text):
if isinstance(text, text_type):
text = text.encode("utf-8")
self.__reset_parser()
try:
for ttype, tvalue in self.lexer.scan(text):
if ttype == "hash_comment":
self.hash_comments += [tvalue.strip()]
continue
if ttype == "bracket_comment":
continue
if self.__expected is not None:
if ttype not in self.__expected:
if self.lexer.pos < len(text):
msg = (
"%s found while %s expected near '%s'"
% (ttype, "|".join(self.__expected),
text[self.lexer.pos])
)
else:
msg = (
"%s found while %s expected at end of file"
% (ttype, "|".join(self.__expected))
)
raise ParseError(msg)
self.__expected = None
if not self.__command(ttype, tvalue):
msg = (
"unexpected token '%s' found near '%s'"
% (tvalue.decode(), text.decode()[self.lexer.pos])
)
raise ParseError(msg)
if self.__opened_blocks:
self.__set_expected("right_cbracket")
if self.__expected is not None:
raise ParseError("end of script reached while %s expected" %
"|".join(self.__expected))
except (ParseError, CommandError) as e:
self.error = "line %d: %s" % (self.lexer.curlineno(), str(e))
return False
return True | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"text_type",
")",
":",
"text",
"=",
"text",
".",
"encode",
"(",
"\"utf-8\"",
")",
"self",
".",
"__reset_parser",
"(",
")",
"try",
":",
"for",
"ttype",
",",
"t... | The parser entry point.
Parse the provided text to check for its validity.
On success, the parsing tree is available into the result
attribute. It is a list of sievecommands.Command objects (see
the module documentation for specific information).
On error, an string containing the explicit reason is
available into the error attribute.
:param text: a string containing the data to parse
:return: True on success (no error detected), False otherwise | [
"The",
"parser",
"entry",
"point",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L384-L441 |
10,708 | tonioo/sievelib | sievelib/parser.py | Parser.parse_file | def parse_file(self, name):
"""Parse the content of a file.
See 'parse' method for information.
:param name: the pathname of the file to parse
:return: True on success (no error detected), False otherwise
"""
with open(name, "rb") as fp:
return self.parse(fp.read()) | python | def parse_file(self, name):
with open(name, "rb") as fp:
return self.parse(fp.read()) | [
"def",
"parse_file",
"(",
"self",
",",
"name",
")",
":",
"with",
"open",
"(",
"name",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"return",
"self",
".",
"parse",
"(",
"fp",
".",
"read",
"(",
")",
")"
] | Parse the content of a file.
See 'parse' method for information.
:param name: the pathname of the file to parse
:return: True on success (no error detected), False otherwise | [
"Parse",
"the",
"content",
"of",
"a",
"file",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L443-L452 |
10,709 | tonioo/sievelib | sievelib/parser.py | Parser.dump | def dump(self, target=sys.stdout):
"""Dump the parsing tree.
This method displays the parsing tree on the standard output.
"""
for r in self.result:
r.dump(target=target) | python | def dump(self, target=sys.stdout):
for r in self.result:
r.dump(target=target) | [
"def",
"dump",
"(",
"self",
",",
"target",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"r",
"in",
"self",
".",
"result",
":",
"r",
".",
"dump",
"(",
"target",
"=",
"target",
")"
] | Dump the parsing tree.
This method displays the parsing tree on the standard output. | [
"Dump",
"the",
"parsing",
"tree",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L454-L460 |
10,710 | tonioo/sievelib | sievelib/commands.py | get_command_instance | def get_command_instance(name, parent=None, checkexists=True):
"""Try to guess and create the appropriate command instance
Given a command name (encountered by the parser), construct the
associated class name and, if known, return a new instance.
If the command is not known or has not been loaded using require,
an UnknownCommand exception is raised.
:param name: the command's name
:param parent: the eventual parent command
:return: a new class instance
"""
cname = "%sCommand" % name.lower().capitalize()
gl = globals()
condition = (
cname not in gl or
(checkexists and gl[cname].extension and
gl[cname].extension not in RequireCommand.loaded_extensions)
)
if condition:
raise UnknownCommand(name)
return gl[cname](parent) | python | def get_command_instance(name, parent=None, checkexists=True):
cname = "%sCommand" % name.lower().capitalize()
gl = globals()
condition = (
cname not in gl or
(checkexists and gl[cname].extension and
gl[cname].extension not in RequireCommand.loaded_extensions)
)
if condition:
raise UnknownCommand(name)
return gl[cname](parent) | [
"def",
"get_command_instance",
"(",
"name",
",",
"parent",
"=",
"None",
",",
"checkexists",
"=",
"True",
")",
":",
"cname",
"=",
"\"%sCommand\"",
"%",
"name",
".",
"lower",
"(",
")",
".",
"capitalize",
"(",
")",
"gl",
"=",
"globals",
"(",
")",
"conditi... | Try to guess and create the appropriate command instance
Given a command name (encountered by the parser), construct the
associated class name and, if known, return a new instance.
If the command is not known or has not been loaded using require,
an UnknownCommand exception is raised.
:param name: the command's name
:param parent: the eventual parent command
:return: a new class instance | [
"Try",
"to",
"guess",
"and",
"create",
"the",
"appropriate",
"command",
"instance"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L1086-L1108 |
10,711 | tonioo/sievelib | sievelib/commands.py | Command.tosieve | def tosieve(self, indentlevel=0, target=sys.stdout):
"""Generate the sieve syntax corresponding to this command
Recursive method.
:param indentlevel: current indentation level
:param target: opened file pointer where the content will be printed
"""
self.__print(self.name, indentlevel, nocr=True, target=target)
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
target.write(" ")
value = self.arguments[arg["name"]]
atype = arg["type"]
if "tag" in atype:
target.write(value)
if arg["name"] in self.extra_arguments:
value = self.extra_arguments[arg["name"]]
atype = arg["extra_arg"]["type"]
target.write(" ")
else:
continue
if type(value) == list:
if self.__get_arg_type(arg["name"]) == ["testlist"]:
target.write("(")
for t in value:
t.tosieve(target=target)
if value.index(t) != len(value) - 1:
target.write(", ")
target.write(")")
else:
target.write(
"[{}]".format(", ".join(
['"%s"' % v.strip('"') for v in value])
)
)
continue
if isinstance(value, Command):
value.tosieve(indentlevel, target=target)
continue
if "string" in atype:
target.write(value)
if not value.startswith('"') and not value.startswith("["):
target.write("\n")
else:
target.write(value)
if not self.accept_children:
if self.get_type() != "test":
target.write(";\n")
return
if self.get_type() != "control":
return
target.write(" {\n")
for ch in self.children:
ch.tosieve(indentlevel + 4, target=target)
self.__print("}", indentlevel, target=target) | python | def tosieve(self, indentlevel=0, target=sys.stdout):
self.__print(self.name, indentlevel, nocr=True, target=target)
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
target.write(" ")
value = self.arguments[arg["name"]]
atype = arg["type"]
if "tag" in atype:
target.write(value)
if arg["name"] in self.extra_arguments:
value = self.extra_arguments[arg["name"]]
atype = arg["extra_arg"]["type"]
target.write(" ")
else:
continue
if type(value) == list:
if self.__get_arg_type(arg["name"]) == ["testlist"]:
target.write("(")
for t in value:
t.tosieve(target=target)
if value.index(t) != len(value) - 1:
target.write(", ")
target.write(")")
else:
target.write(
"[{}]".format(", ".join(
['"%s"' % v.strip('"') for v in value])
)
)
continue
if isinstance(value, Command):
value.tosieve(indentlevel, target=target)
continue
if "string" in atype:
target.write(value)
if not value.startswith('"') and not value.startswith("["):
target.write("\n")
else:
target.write(value)
if not self.accept_children:
if self.get_type() != "test":
target.write(";\n")
return
if self.get_type() != "control":
return
target.write(" {\n")
for ch in self.children:
ch.tosieve(indentlevel + 4, target=target)
self.__print("}", indentlevel, target=target) | [
"def",
"tosieve",
"(",
"self",
",",
"indentlevel",
"=",
"0",
",",
"target",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"__print",
"(",
"self",
".",
"name",
",",
"indentlevel",
",",
"nocr",
"=",
"True",
",",
"target",
"=",
"target",
")",
"if"... | Generate the sieve syntax corresponding to this command
Recursive method.
:param indentlevel: current indentation level
:param target: opened file pointer where the content will be printed | [
"Generate",
"the",
"sieve",
"syntax",
"corresponding",
"to",
"this",
"command"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L157-L217 |
10,712 | tonioo/sievelib | sievelib/commands.py | Command.dump | def dump(self, indentlevel=0, target=sys.stdout):
"""Display the command
Pretty printing of this command and its eventual arguments and
children. (recursively)
:param indentlevel: integer that indicates indentation level to apply
"""
self.__print(self, indentlevel, target=target)
indentlevel += 4
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
value = self.arguments[arg["name"]]
atype = arg["type"]
if "tag" in atype:
self.__print(str(value), indentlevel, target=target)
if arg["name"] in self.extra_arguments:
value = self.extra_arguments[arg["name"]]
atype = arg["extra_arg"]["type"]
else:
continue
if type(value) == list:
if self.__get_arg_type(arg["name"]) == ["testlist"]:
for t in value:
t.dump(indentlevel, target)
else:
self.__print("[" + (",".join(value)) + "]",
indentlevel, target=target)
continue
if isinstance(value, Command):
value.dump(indentlevel, target)
continue
self.__print(str(value), indentlevel, target=target)
for ch in self.children:
ch.dump(indentlevel, target) | python | def dump(self, indentlevel=0, target=sys.stdout):
self.__print(self, indentlevel, target=target)
indentlevel += 4
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
value = self.arguments[arg["name"]]
atype = arg["type"]
if "tag" in atype:
self.__print(str(value), indentlevel, target=target)
if arg["name"] in self.extra_arguments:
value = self.extra_arguments[arg["name"]]
atype = arg["extra_arg"]["type"]
else:
continue
if type(value) == list:
if self.__get_arg_type(arg["name"]) == ["testlist"]:
for t in value:
t.dump(indentlevel, target)
else:
self.__print("[" + (",".join(value)) + "]",
indentlevel, target=target)
continue
if isinstance(value, Command):
value.dump(indentlevel, target)
continue
self.__print(str(value), indentlevel, target=target)
for ch in self.children:
ch.dump(indentlevel, target) | [
"def",
"dump",
"(",
"self",
",",
"indentlevel",
"=",
"0",
",",
"target",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"__print",
"(",
"self",
",",
"indentlevel",
",",
"target",
"=",
"target",
")",
"indentlevel",
"+=",
"4",
"if",
"self",
".",
"... | Display the command
Pretty printing of this command and its eventual arguments and
children. (recursively)
:param indentlevel: integer that indicates indentation level to apply | [
"Display",
"the",
"command"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L258-L294 |
10,713 | tonioo/sievelib | sievelib/commands.py | Command.walk | def walk(self):
"""Walk through commands."""
yield self
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
value = self.arguments[arg["name"]]
if type(value) == list:
if self.__get_arg_type(arg["name"]) == ["testlist"]:
for t in value:
for node in t.walk():
yield node
if isinstance(value, Command):
for node in value.walk():
yield node
for ch in self.children:
for node in ch.walk():
yield node | python | def walk(self):
yield self
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
value = self.arguments[arg["name"]]
if type(value) == list:
if self.__get_arg_type(arg["name"]) == ["testlist"]:
for t in value:
for node in t.walk():
yield node
if isinstance(value, Command):
for node in value.walk():
yield node
for ch in self.children:
for node in ch.walk():
yield node | [
"def",
"walk",
"(",
"self",
")",
":",
"yield",
"self",
"if",
"self",
".",
"has_arguments",
"(",
")",
":",
"for",
"arg",
"in",
"self",
".",
"args_definition",
":",
"if",
"not",
"arg",
"[",
"\"name\"",
"]",
"in",
"self",
".",
"arguments",
":",
"continu... | Walk through commands. | [
"Walk",
"through",
"commands",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L296-L314 |
10,714 | tonioo/sievelib | sievelib/commands.py | Command.addchild | def addchild(self, child):
"""Add a new child to the command
A child corresponds to a command located into a block (this
command's block). It can be either an action or a control.
:param child: the new child
:return: True on succes, False otherwise
"""
if not self.accept_children:
return False
self.children += [child]
return True | python | def addchild(self, child):
if not self.accept_children:
return False
self.children += [child]
return True | [
"def",
"addchild",
"(",
"self",
",",
"child",
")",
":",
"if",
"not",
"self",
".",
"accept_children",
":",
"return",
"False",
"self",
".",
"children",
"+=",
"[",
"child",
"]",
"return",
"True"
] | Add a new child to the command
A child corresponds to a command located into a block (this
command's block). It can be either an action or a control.
:param child: the new child
:return: True on succes, False otherwise | [
"Add",
"a",
"new",
"child",
"to",
"the",
"command"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L316-L328 |
10,715 | tonioo/sievelib | sievelib/commands.py | Command.iscomplete | def iscomplete(self, atype=None, avalue=None):
"""Check if the command is complete
Check if all required arguments have been encountered. For
commands that allow an undefined number of arguments, this
method always returns False.
:return: True if command is complete, False otherwise
"""
if self.variable_args_nb:
return False
if self.required_args == -1:
self.required_args = 0
for arg in self.args_definition:
if arg.get("required", False):
self.required_args += 1
return (
(not self.curarg or
"extra_arg" not in self.curarg or
("valid_for" in self.curarg["extra_arg"] and
atype and atype in self.curarg["extra_arg"]["type"] and
avalue not in self.curarg["extra_arg"]["valid_for"])) and
(self.rargs_cnt == self.required_args)
) | python | def iscomplete(self, atype=None, avalue=None):
if self.variable_args_nb:
return False
if self.required_args == -1:
self.required_args = 0
for arg in self.args_definition:
if arg.get("required", False):
self.required_args += 1
return (
(not self.curarg or
"extra_arg" not in self.curarg or
("valid_for" in self.curarg["extra_arg"] and
atype and atype in self.curarg["extra_arg"]["type"] and
avalue not in self.curarg["extra_arg"]["valid_for"])) and
(self.rargs_cnt == self.required_args)
) | [
"def",
"iscomplete",
"(",
"self",
",",
"atype",
"=",
"None",
",",
"avalue",
"=",
"None",
")",
":",
"if",
"self",
".",
"variable_args_nb",
":",
"return",
"False",
"if",
"self",
".",
"required_args",
"==",
"-",
"1",
":",
"self",
".",
"required_args",
"="... | Check if the command is complete
Check if all required arguments have been encountered. For
commands that allow an undefined number of arguments, this
method always returns False.
:return: True if command is complete, False otherwise | [
"Check",
"if",
"the",
"command",
"is",
"complete"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L330-L353 |
10,716 | tonioo/sievelib | sievelib/commands.py | Command.__is_valid_value_for_arg | def __is_valid_value_for_arg(self, arg, value, check_extension=True):
"""Check if value is allowed for arg
Some commands only allow a limited set of values. The method
always returns True for methods that do not provide such a
set.
:param arg: the argument's name
:param value: the value to check
:param check_extension: check if value requires an extension
:return: True on succes, False otherwise
"""
if "values" not in arg and "extension_values" not in arg:
return True
if "values" in arg and value.lower() in arg["values"]:
return True
if "extension_values" in arg:
extension = arg["extension_values"].get(value.lower())
if extension:
condition = (
check_extension and
extension not in RequireCommand.loaded_extensions
)
if condition:
raise ExtensionNotLoaded(extension)
return True
return False | python | def __is_valid_value_for_arg(self, arg, value, check_extension=True):
if "values" not in arg and "extension_values" not in arg:
return True
if "values" in arg and value.lower() in arg["values"]:
return True
if "extension_values" in arg:
extension = arg["extension_values"].get(value.lower())
if extension:
condition = (
check_extension and
extension not in RequireCommand.loaded_extensions
)
if condition:
raise ExtensionNotLoaded(extension)
return True
return False | [
"def",
"__is_valid_value_for_arg",
"(",
"self",
",",
"arg",
",",
"value",
",",
"check_extension",
"=",
"True",
")",
":",
"if",
"\"values\"",
"not",
"in",
"arg",
"and",
"\"extension_values\"",
"not",
"in",
"arg",
":",
"return",
"True",
"if",
"\"values\"",
"in... | Check if value is allowed for arg
Some commands only allow a limited set of values. The method
always returns True for methods that do not provide such a
set.
:param arg: the argument's name
:param value: the value to check
:param check_extension: check if value requires an extension
:return: True on succes, False otherwise | [
"Check",
"if",
"value",
"is",
"allowed",
"for",
"arg"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L361-L387 |
10,717 | tonioo/sievelib | sievelib/commands.py | Command.__is_valid_type | def __is_valid_type(self, typ, typlist):
""" Check if type is valid based on input type list
"string" is special because it can be used for stringlist
:param typ: the type to check
:param typlist: the list of type to check
:return: True on success, False otherwise
"""
typ_is_str = typ == "string"
str_list_in_typlist = "stringlist" in typlist
return typ in typlist or (typ_is_str and str_list_in_typlist) | python | def __is_valid_type(self, typ, typlist):
typ_is_str = typ == "string"
str_list_in_typlist = "stringlist" in typlist
return typ in typlist or (typ_is_str and str_list_in_typlist) | [
"def",
"__is_valid_type",
"(",
"self",
",",
"typ",
",",
"typlist",
")",
":",
"typ_is_str",
"=",
"typ",
"==",
"\"string\"",
"str_list_in_typlist",
"=",
"\"stringlist\"",
"in",
"typlist",
"return",
"typ",
"in",
"typlist",
"or",
"(",
"typ_is_str",
"and",
"str_lis... | Check if type is valid based on input type list
"string" is special because it can be used for stringlist
:param typ: the type to check
:param typlist: the list of type to check
:return: True on success, False otherwise | [
"Check",
"if",
"type",
"is",
"valid",
"based",
"on",
"input",
"type",
"list",
"string",
"is",
"special",
"because",
"it",
"can",
"be",
"used",
"for",
"stringlist"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L389-L400 |
10,718 | tonioo/sievelib | sievelib/commands.py | Command.check_next_arg | def check_next_arg(self, atype, avalue, add=True, check_extension=True):
"""Argument validity checking
This method is usually used by the parser to check if detected
argument is allowed for this command.
We make a distinction between required and optional
arguments. Optional (or tagged) arguments can be provided
unordered but not the required ones.
A special handling is also done for arguments that require an
argument (example: the :comparator argument expects a string
argument).
The "testlist" type is checked separately as we can't know in
advance how many arguments will be provided.
If the argument is incorrect, the method raises the
appropriate exception, or return False to let the parser
handle the exception.
:param atype: the argument's type
:param avalue: the argument's value
:param add: indicates if this argument should be recorded on success
:param check_extension: raise ExtensionNotLoaded if extension not
loaded
:return: True on success, False otherwise
"""
if not self.has_arguments():
return False
if self.iscomplete(atype, avalue):
return False
if self.curarg is not None and "extra_arg" in self.curarg:
condition = (
atype in self.curarg["extra_arg"]["type"] and
("values" not in self.curarg["extra_arg"] or
avalue in self.curarg["extra_arg"]["values"])
)
if condition:
if add:
self.extra_arguments[self.curarg["name"]] = avalue
self.curarg = None
return True
raise BadValue(self.curarg["name"], avalue)
failed = False
pos = self.nextargpos
while pos < len(self.args_definition):
curarg = self.args_definition[pos]
if curarg.get("required", False):
if curarg["type"] == ["testlist"]:
if atype != "test":
failed = True
elif add:
if not curarg["name"] in self.arguments:
self.arguments[curarg["name"]] = []
self.arguments[curarg["name"]] += [avalue]
elif not self.__is_valid_type(atype, curarg["type"]) or \
not self.__is_valid_value_for_arg(
curarg, avalue, check_extension):
failed = True
else:
self.curarg = curarg
self.rargs_cnt += 1
self.nextargpos = pos + 1
if add:
self.arguments[curarg["name"]] = avalue
break
condition = (
atype in curarg["type"] and
self.__is_valid_value_for_arg(curarg, avalue, check_extension)
)
if condition:
ext = curarg.get("extension")
condition = (
check_extension and ext and
ext not in RequireCommand.loaded_extensions)
if condition:
raise ExtensionNotLoaded(ext)
condition = (
"extra_arg" in curarg and
("valid_for" not in curarg["extra_arg"] or
avalue in curarg["extra_arg"]["valid_for"])
)
if condition:
self.curarg = curarg
if add:
self.arguments[curarg["name"]] = avalue
break
pos += 1
if failed:
raise BadArgument(self.name, avalue,
self.args_definition[pos]["type"])
return True | python | def check_next_arg(self, atype, avalue, add=True, check_extension=True):
if not self.has_arguments():
return False
if self.iscomplete(atype, avalue):
return False
if self.curarg is not None and "extra_arg" in self.curarg:
condition = (
atype in self.curarg["extra_arg"]["type"] and
("values" not in self.curarg["extra_arg"] or
avalue in self.curarg["extra_arg"]["values"])
)
if condition:
if add:
self.extra_arguments[self.curarg["name"]] = avalue
self.curarg = None
return True
raise BadValue(self.curarg["name"], avalue)
failed = False
pos = self.nextargpos
while pos < len(self.args_definition):
curarg = self.args_definition[pos]
if curarg.get("required", False):
if curarg["type"] == ["testlist"]:
if atype != "test":
failed = True
elif add:
if not curarg["name"] in self.arguments:
self.arguments[curarg["name"]] = []
self.arguments[curarg["name"]] += [avalue]
elif not self.__is_valid_type(atype, curarg["type"]) or \
not self.__is_valid_value_for_arg(
curarg, avalue, check_extension):
failed = True
else:
self.curarg = curarg
self.rargs_cnt += 1
self.nextargpos = pos + 1
if add:
self.arguments[curarg["name"]] = avalue
break
condition = (
atype in curarg["type"] and
self.__is_valid_value_for_arg(curarg, avalue, check_extension)
)
if condition:
ext = curarg.get("extension")
condition = (
check_extension and ext and
ext not in RequireCommand.loaded_extensions)
if condition:
raise ExtensionNotLoaded(ext)
condition = (
"extra_arg" in curarg and
("valid_for" not in curarg["extra_arg"] or
avalue in curarg["extra_arg"]["valid_for"])
)
if condition:
self.curarg = curarg
if add:
self.arguments[curarg["name"]] = avalue
break
pos += 1
if failed:
raise BadArgument(self.name, avalue,
self.args_definition[pos]["type"])
return True | [
"def",
"check_next_arg",
"(",
"self",
",",
"atype",
",",
"avalue",
",",
"add",
"=",
"True",
",",
"check_extension",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"has_arguments",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"iscomplete",
"("... | Argument validity checking
This method is usually used by the parser to check if detected
argument is allowed for this command.
We make a distinction between required and optional
arguments. Optional (or tagged) arguments can be provided
unordered but not the required ones.
A special handling is also done for arguments that require an
argument (example: the :comparator argument expects a string
argument).
The "testlist" type is checked separately as we can't know in
advance how many arguments will be provided.
If the argument is incorrect, the method raises the
appropriate exception, or return False to let the parser
handle the exception.
:param atype: the argument's type
:param avalue: the argument's value
:param add: indicates if this argument should be recorded on success
:param check_extension: raise ExtensionNotLoaded if extension not
loaded
:return: True on success, False otherwise | [
"Argument",
"validity",
"checking"
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L402-L499 |
10,719 | tonioo/sievelib | sievelib/commands.py | HasflagCommand.reassign_arguments | def reassign_arguments(self):
"""Deal with optional stringlist before a required one."""
condition = (
"variable-list" in self.arguments and
"list-of-flags" not in self.arguments
)
if condition:
self.arguments["list-of-flags"] = (
self.arguments.pop("variable-list"))
self.rargs_cnt = 1 | python | def reassign_arguments(self):
condition = (
"variable-list" in self.arguments and
"list-of-flags" not in self.arguments
)
if condition:
self.arguments["list-of-flags"] = (
self.arguments.pop("variable-list"))
self.rargs_cnt = 1 | [
"def",
"reassign_arguments",
"(",
"self",
")",
":",
"condition",
"=",
"(",
"\"variable-list\"",
"in",
"self",
".",
"arguments",
"and",
"\"list-of-flags\"",
"not",
"in",
"self",
".",
"arguments",
")",
"if",
"condition",
":",
"self",
".",
"arguments",
"[",
"\"... | Deal with optional stringlist before a required one. | [
"Deal",
"with",
"optional",
"stringlist",
"before",
"a",
"required",
"one",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L929-L938 |
10,720 | tonioo/sievelib | sievelib/tools.py | to_bytes | def to_bytes(s, encoding="utf-8"):
"""Convert a string to bytes."""
if isinstance(s, six.binary_type):
return s
if six.PY3:
return bytes(s, encoding)
return s.encode(encoding) | python | def to_bytes(s, encoding="utf-8"):
if isinstance(s, six.binary_type):
return s
if six.PY3:
return bytes(s, encoding)
return s.encode(encoding) | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"s",
"if",
"six",
".",
"PY3",
":",
"return",
"bytes",
"(",
"s",
",",
"encoding",
")",
"retur... | Convert a string to bytes. | [
"Convert",
"a",
"string",
"to",
"bytes",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/tools.py#L6-L12 |
10,721 | tonioo/sievelib | sievelib/tools.py | to_list | def to_list(stringlist, unquote=True):
"""Convert a string representing a list to real list."""
stringlist = stringlist[1:-1]
return [
string.strip('"') if unquote else string
for string in stringlist.split(",")
] | python | def to_list(stringlist, unquote=True):
stringlist = stringlist[1:-1]
return [
string.strip('"') if unquote else string
for string in stringlist.split(",")
] | [
"def",
"to_list",
"(",
"stringlist",
",",
"unquote",
"=",
"True",
")",
":",
"stringlist",
"=",
"stringlist",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"[",
"string",
".",
"strip",
"(",
"'\"'",
")",
"if",
"unquote",
"else",
"string",
"for",
"string",
"i... | Convert a string representing a list to real list. | [
"Convert",
"a",
"string",
"representing",
"a",
"list",
"to",
"real",
"list",
"."
] | 88822d1f1daf30ef3dd9ac74911301b0773ef3c8 | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/tools.py#L15-L21 |
10,722 | mozilla/puente | puente/utils.py | monkeypatch_i18n | def monkeypatch_i18n():
"""Alleviates problems with extraction for trans blocks
Jinja2 has a ``babel_extract`` function which sets up a Jinja2
environment to parse Jinja2 templates to extract strings for
translation. That's awesome! Yay! However, when it goes to
set up the environment, it checks to see if the environment
has InternationalizationExtension in it and if not, adds it.
https://github.com/mitsuhiko/jinja2/blob/2.8/jinja2/ext.py#L587
That stomps on our PuenteI18nExtension so trans blocks don't get
whitespace collapsed and we end up with msgids that are different
between extraction and rendering. Argh!
Two possible ways to deal with this:
1. Rename our block from "trans" to something else like
"blocktrans" or "transam".
This means everyone has to make sweeping changes to their
templates plus we adjust gettext, too, so now we're talking
about two different extensions.
2. Have people include both InternationalizationExtension
before PuenteI18nExtension even though it gets stomped on.
This will look wrong in settings and someone will want to
"fix" it thus breaking extractino subtly, so I'm loathe to
force everyone to do this.
3. Stomp on the InternationalizationExtension variable in
``jinja2.ext`` just before message extraction.
This is easy and hopefully the underlying issue will go away
soon.
For now, we're going to do number 3. Why? Because I'm hoping
Jinja2 will fix the trans tag so it collapses whitespace if
you tell it to. Then we don't have to do what we're doing and
all these problems go away.
We can remove this monkeypatch when one of the following is true:
1. we remove our whitespace collapsing code because Jinja2 trans
tag supports whitespace collapsing
2. Jinja2's ``babel_extract`` stops adding
InternationalizationExtension to the environment if it's
not there
"""
import jinja2.ext
from puente.ext import PuenteI18nExtension
jinja2.ext.InternationalizationExtension = PuenteI18nExtension
jinja2.ext.i18n = PuenteI18nExtension | python | def monkeypatch_i18n():
import jinja2.ext
from puente.ext import PuenteI18nExtension
jinja2.ext.InternationalizationExtension = PuenteI18nExtension
jinja2.ext.i18n = PuenteI18nExtension | [
"def",
"monkeypatch_i18n",
"(",
")",
":",
"import",
"jinja2",
".",
"ext",
"from",
"puente",
".",
"ext",
"import",
"PuenteI18nExtension",
"jinja2",
".",
"ext",
".",
"InternationalizationExtension",
"=",
"PuenteI18nExtension",
"jinja2",
".",
"ext",
".",
"i18n",
"=... | Alleviates problems with extraction for trans blocks
Jinja2 has a ``babel_extract`` function which sets up a Jinja2
environment to parse Jinja2 templates to extract strings for
translation. That's awesome! Yay! However, when it goes to
set up the environment, it checks to see if the environment
has InternationalizationExtension in it and if not, adds it.
https://github.com/mitsuhiko/jinja2/blob/2.8/jinja2/ext.py#L587
That stomps on our PuenteI18nExtension so trans blocks don't get
whitespace collapsed and we end up with msgids that are different
between extraction and rendering. Argh!
Two possible ways to deal with this:
1. Rename our block from "trans" to something else like
"blocktrans" or "transam".
This means everyone has to make sweeping changes to their
templates plus we adjust gettext, too, so now we're talking
about two different extensions.
2. Have people include both InternationalizationExtension
before PuenteI18nExtension even though it gets stomped on.
This will look wrong in settings and someone will want to
"fix" it thus breaking extractino subtly, so I'm loathe to
force everyone to do this.
3. Stomp on the InternationalizationExtension variable in
``jinja2.ext`` just before message extraction.
This is easy and hopefully the underlying issue will go away
soon.
For now, we're going to do number 3. Why? Because I'm hoping
Jinja2 will fix the trans tag so it collapses whitespace if
you tell it to. Then we don't have to do what we're doing and
all these problems go away.
We can remove this monkeypatch when one of the following is true:
1. we remove our whitespace collapsing code because Jinja2 trans
tag supports whitespace collapsing
2. Jinja2's ``babel_extract`` stops adding
InternationalizationExtension to the environment if it's
not there | [
"Alleviates",
"problems",
"with",
"extraction",
"for",
"trans",
"blocks"
] | 4379a7717d28a2490d47939800f5d6e695b70def | https://github.com/mozilla/puente/blob/4379a7717d28a2490d47939800f5d6e695b70def/puente/utils.py#L4-L60 |
10,723 | mozilla/puente | puente/utils.py | generate_keywords | def generate_keywords(additional_keywords=None):
"""Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
'gettext': None,
'ngettext': (1, 2),
'ugettext': None,
'ungettext': (1, 2),
'dgettext': (2,),
'dngettext': (2, 3),
'N_': None,
'pgettext': ((1, 'c'), 2)
}
If you wanted to add a new one ``_frank`` that was like
gettext, then you'd do this::
generate_keywords({'_frank': None})
If you wanted to add a new one ``upgettext`` that was like
gettext, then you'd do this::
generate_keywords({'upgettext': ((1, 'c'), 2)})
"""
# Shallow copy
keywords = dict(BABEL_KEYWORDS)
keywords.update({
'_lazy': None,
'gettext_lazy': None,
'ugettext_lazy': None,
'gettext_noop': None,
'ugettext_noop': None,
'ngettext_lazy': (1, 2),
'ungettext_lazy': (1, 2),
'npgettext': ((1, 'c'), 2, 3),
'pgettext_lazy': ((1, 'c'), 2),
'npgettext_lazy': ((1, 'c'), 2, 3),
})
# Add specified keywords
if additional_keywords:
for key, val in additional_keywords.items():
keywords[key] = val
return keywords | python | def generate_keywords(additional_keywords=None):
# Shallow copy
keywords = dict(BABEL_KEYWORDS)
keywords.update({
'_lazy': None,
'gettext_lazy': None,
'ugettext_lazy': None,
'gettext_noop': None,
'ugettext_noop': None,
'ngettext_lazy': (1, 2),
'ungettext_lazy': (1, 2),
'npgettext': ((1, 'c'), 2, 3),
'pgettext_lazy': ((1, 'c'), 2),
'npgettext_lazy': ((1, 'c'), 2, 3),
})
# Add specified keywords
if additional_keywords:
for key, val in additional_keywords.items():
keywords[key] = val
return keywords | [
"def",
"generate_keywords",
"(",
"additional_keywords",
"=",
"None",
")",
":",
"# Shallow copy",
"keywords",
"=",
"dict",
"(",
"BABEL_KEYWORDS",
")",
"keywords",
".",
"update",
"(",
"{",
"'_lazy'",
":",
"None",
",",
"'gettext_lazy'",
":",
"None",
",",
"'ugette... | Generates gettext keywords list
:arg additional_keywords: dict of keyword -> value
:returns: dict of keyword -> values for Babel extraction
Here's what Babel has for DEFAULT_KEYWORDS::
DEFAULT_KEYWORDS = {
'_': None,
'gettext': None,
'ngettext': (1, 2),
'ugettext': None,
'ungettext': (1, 2),
'dgettext': (2,),
'dngettext': (2, 3),
'N_': None,
'pgettext': ((1, 'c'), 2)
}
If you wanted to add a new one ``_frank`` that was like
gettext, then you'd do this::
generate_keywords({'_frank': None})
If you wanted to add a new one ``upgettext`` that was like
gettext, then you'd do this::
generate_keywords({'upgettext': ((1, 'c'), 2)}) | [
"Generates",
"gettext",
"keywords",
"list"
] | 4379a7717d28a2490d47939800f5d6e695b70def | https://github.com/mozilla/puente/blob/4379a7717d28a2490d47939800f5d6e695b70def/puente/utils.py#L63-L117 |
10,724 | mozilla/puente | puente/utils.py | collapse_whitespace | def collapse_whitespace(message):
"""Collapses consecutive whitespace into a single space"""
return u' '.join(map(lambda s: s.strip(),
filter(None, message.strip().splitlines()))) | python | def collapse_whitespace(message):
return u' '.join(map(lambda s: s.strip(),
filter(None, message.strip().splitlines()))) | [
"def",
"collapse_whitespace",
"(",
"message",
")",
":",
"return",
"u' '",
".",
"join",
"(",
"map",
"(",
"lambda",
"s",
":",
"s",
".",
"strip",
"(",
")",
",",
"filter",
"(",
"None",
",",
"message",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")"... | Collapses consecutive whitespace into a single space | [
"Collapses",
"consecutive",
"whitespace",
"into",
"a",
"single",
"space"
] | 4379a7717d28a2490d47939800f5d6e695b70def | https://github.com/mozilla/puente/blob/4379a7717d28a2490d47939800f5d6e695b70def/puente/utils.py#L120-L123 |
10,725 | mozilla/puente | puente/commands.py | generate_options_map | def generate_options_map():
"""Generate an ``options_map` to pass to ``extract_from_dir``
This is the options_map that's used to generate a Jinja2 environment. We
want to generate and environment for extraction that's the same as the
environment we use for rendering.
This allows developers to explicitly set a ``JINJA2_CONFIG`` in settings.
If that's not there, then this will pull the relevant bits from the first
Jinja2 backend listed in ``TEMPLATES``.
"""
try:
return settings.PUENTE['JINJA2_CONFIG']
except KeyError:
pass
# If using Django 1.8+, we can skim the TEMPLATES for a backend that we
# know about and extract the settings from that.
for tmpl_config in getattr(settings, 'TEMPLATES', []):
try:
backend = tmpl_config['BACKEND']
except KeyError:
continue
if backend == 'django_jinja.backend.Jinja2':
extensions = tmpl_config.get('OPTIONS', {}).get('extensions', [])
return {
'**.*': {
'extensions': ','.join(extensions),
'silent': 'False',
}
}
# If this is Django 1.7 and Jingo, try to grab extensions from
# JINJA_CONFIG.
if getattr(settings, 'JINJA_CONFIG'):
jinja_config = settings.JINJA_CONFIG
if callable(jinja_config):
jinja_config = jinja_config()
return {
'**.*': {
'extensions': ','.join(jinja_config['extensions']),
'silent': 'False',
}
}
raise CommandError(
'No valid jinja2 config found in settings. See configuration '
'documentation.'
) | python | def generate_options_map():
try:
return settings.PUENTE['JINJA2_CONFIG']
except KeyError:
pass
# If using Django 1.8+, we can skim the TEMPLATES for a backend that we
# know about and extract the settings from that.
for tmpl_config in getattr(settings, 'TEMPLATES', []):
try:
backend = tmpl_config['BACKEND']
except KeyError:
continue
if backend == 'django_jinja.backend.Jinja2':
extensions = tmpl_config.get('OPTIONS', {}).get('extensions', [])
return {
'**.*': {
'extensions': ','.join(extensions),
'silent': 'False',
}
}
# If this is Django 1.7 and Jingo, try to grab extensions from
# JINJA_CONFIG.
if getattr(settings, 'JINJA_CONFIG'):
jinja_config = settings.JINJA_CONFIG
if callable(jinja_config):
jinja_config = jinja_config()
return {
'**.*': {
'extensions': ','.join(jinja_config['extensions']),
'silent': 'False',
}
}
raise CommandError(
'No valid jinja2 config found in settings. See configuration '
'documentation.'
) | [
"def",
"generate_options_map",
"(",
")",
":",
"try",
":",
"return",
"settings",
".",
"PUENTE",
"[",
"'JINJA2_CONFIG'",
"]",
"except",
"KeyError",
":",
"pass",
"# If using Django 1.8+, we can skim the TEMPLATES for a backend that we",
"# know about and extract the settings from ... | Generate an ``options_map` to pass to ``extract_from_dir``
This is the options_map that's used to generate a Jinja2 environment. We
want to generate and environment for extraction that's the same as the
environment we use for rendering.
This allows developers to explicitly set a ``JINJA2_CONFIG`` in settings.
If that's not there, then this will pull the relevant bits from the first
Jinja2 backend listed in ``TEMPLATES``. | [
"Generate",
"an",
"options_map",
"to",
"pass",
"to",
"extract_from_dir"
] | 4379a7717d28a2490d47939800f5d6e695b70def | https://github.com/mozilla/puente/blob/4379a7717d28a2490d47939800f5d6e695b70def/puente/commands.py#L14-L64 |
10,726 | mozilla/puente | puente/commands.py | extract_command | def extract_command(outputdir, domain_methods, text_domain, keywords,
comment_tags, base_dir, project, version,
msgid_bugs_address):
"""Extracts strings into .pot files
:arg domain: domains to generate strings for or 'all' for all domains
:arg outputdir: output dir for .pot files; usually
locale/templates/LC_MESSAGES/
:arg domain_methods: DOMAIN_METHODS setting
:arg text_domain: TEXT_DOMAIN settings
:arg keywords: KEYWORDS setting
:arg comment_tags: COMMENT_TAGS setting
:arg base_dir: BASE_DIR setting
:arg project: PROJECT setting
:arg version: VERSION setting
:arg msgid_bugs_address: MSGID_BUGS_ADDRESS setting
"""
# Must monkeypatch first to fix i18n extensions stomping issues!
monkeypatch_i18n()
# Create the outputdir if it doesn't exist
outputdir = os.path.abspath(outputdir)
if not os.path.isdir(outputdir):
print('Creating output dir %s ...' % outputdir)
os.makedirs(outputdir)
domains = domain_methods.keys()
def callback(filename, method, options):
if method != 'ignore':
print(' %s' % filename)
# Extract string for each domain
for domain in domains:
print('Extracting all strings in domain %s...' % domain)
methods = domain_methods[domain]
catalog = Catalog(
header_comment='',
project=project,
version=version,
msgid_bugs_address=msgid_bugs_address,
charset='utf-8',
)
extracted = extract_from_dir(
base_dir,
method_map=methods,
options_map=generate_options_map(),
keywords=keywords,
comment_tags=comment_tags,
callback=callback,
)
for filename, lineno, msg, cmts, ctxt in extracted:
catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts,
context=ctxt)
with open(os.path.join(outputdir, '%s.pot' % domain), 'wb') as fp:
write_po(fp, catalog, width=80)
print('Done') | python | def extract_command(outputdir, domain_methods, text_domain, keywords,
comment_tags, base_dir, project, version,
msgid_bugs_address):
# Must monkeypatch first to fix i18n extensions stomping issues!
monkeypatch_i18n()
# Create the outputdir if it doesn't exist
outputdir = os.path.abspath(outputdir)
if not os.path.isdir(outputdir):
print('Creating output dir %s ...' % outputdir)
os.makedirs(outputdir)
domains = domain_methods.keys()
def callback(filename, method, options):
if method != 'ignore':
print(' %s' % filename)
# Extract string for each domain
for domain in domains:
print('Extracting all strings in domain %s...' % domain)
methods = domain_methods[domain]
catalog = Catalog(
header_comment='',
project=project,
version=version,
msgid_bugs_address=msgid_bugs_address,
charset='utf-8',
)
extracted = extract_from_dir(
base_dir,
method_map=methods,
options_map=generate_options_map(),
keywords=keywords,
comment_tags=comment_tags,
callback=callback,
)
for filename, lineno, msg, cmts, ctxt in extracted:
catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts,
context=ctxt)
with open(os.path.join(outputdir, '%s.pot' % domain), 'wb') as fp:
write_po(fp, catalog, width=80)
print('Done') | [
"def",
"extract_command",
"(",
"outputdir",
",",
"domain_methods",
",",
"text_domain",
",",
"keywords",
",",
"comment_tags",
",",
"base_dir",
",",
"project",
",",
"version",
",",
"msgid_bugs_address",
")",
":",
"# Must monkeypatch first to fix i18n extensions stomping iss... | Extracts strings into .pot files
:arg domain: domains to generate strings for or 'all' for all domains
:arg outputdir: output dir for .pot files; usually
locale/templates/LC_MESSAGES/
:arg domain_methods: DOMAIN_METHODS setting
:arg text_domain: TEXT_DOMAIN settings
:arg keywords: KEYWORDS setting
:arg comment_tags: COMMENT_TAGS setting
:arg base_dir: BASE_DIR setting
:arg project: PROJECT setting
:arg version: VERSION setting
:arg msgid_bugs_address: MSGID_BUGS_ADDRESS setting | [
"Extracts",
"strings",
"into",
".",
"pot",
"files"
] | 4379a7717d28a2490d47939800f5d6e695b70def | https://github.com/mozilla/puente/blob/4379a7717d28a2490d47939800f5d6e695b70def/puente/commands.py#L67-L129 |
10,727 | mozilla/puente | puente/commands.py | _msgmerge | def _msgmerge(po_path, pot_file, backup):
"""Merge an existing .po file with new translations.
:arg po_path: path to the .po file
:arg pot_file: a file-like object for the related templates
:arg backup: whether or not to create backup .po files
"""
pot_file.seek(0)
command = [
'msgmerge',
'--update',
'--width=200',
'--backup=%s' % ('simple' if backup else 'off'),
po_path,
'-'
]
p3 = Popen(command, stdin=pot_file)
p3.communicate() | python | def _msgmerge(po_path, pot_file, backup):
pot_file.seek(0)
command = [
'msgmerge',
'--update',
'--width=200',
'--backup=%s' % ('simple' if backup else 'off'),
po_path,
'-'
]
p3 = Popen(command, stdin=pot_file)
p3.communicate() | [
"def",
"_msgmerge",
"(",
"po_path",
",",
"pot_file",
",",
"backup",
")",
":",
"pot_file",
".",
"seek",
"(",
"0",
")",
"command",
"=",
"[",
"'msgmerge'",
",",
"'--update'",
",",
"'--width=200'",
",",
"'--backup=%s'",
"%",
"(",
"'simple'",
"if",
"backup",
... | Merge an existing .po file with new translations.
:arg po_path: path to the .po file
:arg pot_file: a file-like object for the related templates
:arg backup: whether or not to create backup .po files | [
"Merge",
"an",
"existing",
".",
"po",
"file",
"with",
"new",
"translations",
"."
] | 4379a7717d28a2490d47939800f5d6e695b70def | https://github.com/mozilla/puente/blob/4379a7717d28a2490d47939800f5d6e695b70def/puente/commands.py#L216-L233 |
10,728 | elsampsa/valkka-live | valkka/mvision/multiprocess.py | QValkkaShmemProcess.preRun_ | def preRun_(self):
"""Create the shared memory client immediately after fork
"""
self.report("preRun_")
super().preRun_()
self.client = ShmemRGBClient(
name=self.shmem_name,
n_ringbuffer=self.n_buffer, # size of ring buffer
width=self.image_dimensions[0],
height=self.image_dimensions[1],
# client timeouts if nothing has been received in 1000 milliseconds
mstimeout=1000,
verbose=False
) | python | def preRun_(self):
self.report("preRun_")
super().preRun_()
self.client = ShmemRGBClient(
name=self.shmem_name,
n_ringbuffer=self.n_buffer, # size of ring buffer
width=self.image_dimensions[0],
height=self.image_dimensions[1],
# client timeouts if nothing has been received in 1000 milliseconds
mstimeout=1000,
verbose=False
) | [
"def",
"preRun_",
"(",
"self",
")",
":",
"self",
".",
"report",
"(",
"\"preRun_\"",
")",
"super",
"(",
")",
".",
"preRun_",
"(",
")",
"self",
".",
"client",
"=",
"ShmemRGBClient",
"(",
"name",
"=",
"self",
".",
"shmem_name",
",",
"n_ringbuffer",
"=",
... | Create the shared memory client immediately after fork | [
"Create",
"the",
"shared",
"memory",
"client",
"immediately",
"after",
"fork"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/multiprocess.py#L150-L163 |
10,729 | elsampsa/valkka-live | valkka/mvision/multiprocess.py | QValkkaShmemProcess2.activate_ | def activate_(self, n_buffer, image_dimensions, shmem_name):
"""Shared mem info is given. Now we can create the shmem client
"""
self.active = True
self.image_dimensions = image_dimensions
self.client = ShmemRGBClient(
name =shmem_name,
n_ringbuffer =n_buffer, # size of ring buffer
width =image_dimensions[0],
height =image_dimensions[1],
# client timeouts if nothing has been received in 1000 milliseconds
mstimeout =1000,
verbose =False
)
self.postActivate_() | python | def activate_(self, n_buffer, image_dimensions, shmem_name):
self.active = True
self.image_dimensions = image_dimensions
self.client = ShmemRGBClient(
name =shmem_name,
n_ringbuffer =n_buffer, # size of ring buffer
width =image_dimensions[0],
height =image_dimensions[1],
# client timeouts if nothing has been received in 1000 milliseconds
mstimeout =1000,
verbose =False
)
self.postActivate_() | [
"def",
"activate_",
"(",
"self",
",",
"n_buffer",
",",
"image_dimensions",
",",
"shmem_name",
")",
":",
"self",
".",
"active",
"=",
"True",
"self",
".",
"image_dimensions",
"=",
"image_dimensions",
"self",
".",
"client",
"=",
"ShmemRGBClient",
"(",
"name",
"... | Shared mem info is given. Now we can create the shmem client | [
"Shared",
"mem",
"info",
"is",
"given",
".",
"Now",
"we",
"can",
"create",
"the",
"shmem",
"client"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/multiprocess.py#L313-L327 |
10,730 | elsampsa/valkka-live | valkka/mvision/multiprocess.py | QValkkaShmemProcess2.deactivate_ | def deactivate_(self):
"""Init shmem variables to None
"""
self.preDeactivate_()
self.active = False
self.image_dimensions = None
self.client = None | python | def deactivate_(self):
self.preDeactivate_()
self.active = False
self.image_dimensions = None
self.client = None | [
"def",
"deactivate_",
"(",
"self",
")",
":",
"self",
".",
"preDeactivate_",
"(",
")",
"self",
".",
"active",
"=",
"False",
"self",
".",
"image_dimensions",
"=",
"None",
"self",
".",
"client",
"=",
"None"
] | Init shmem variables to None | [
"Init",
"shmem",
"variables",
"to",
"None"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/multiprocess.py#L334-L340 |
10,731 | elsampsa/valkka-live | valkka/mvision/nix/base.py | ExternalDetector.reset | def reset(self):
"""Tell the external analyzer to reset itself
"""
self.report("sending reset")
try:
self.p.stdin.write(bytes("T\n","utf-8"))
self.p.stdin.flush()
except IOError:
self.report("could not send reset command") | python | def reset(self):
self.report("sending reset")
try:
self.p.stdin.write(bytes("T\n","utf-8"))
self.p.stdin.flush()
except IOError:
self.report("could not send reset command") | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"report",
"(",
"\"sending reset\"",
")",
"try",
":",
"self",
".",
"p",
".",
"stdin",
".",
"write",
"(",
"bytes",
"(",
"\"T\\n\"",
",",
"\"utf-8\"",
")",
")",
"self",
".",
"p",
".",
"stdin",
".",
... | Tell the external analyzer to reset itself | [
"Tell",
"the",
"external",
"analyzer",
"to",
"reset",
"itself"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/nix/base.py#L78-L86 |
10,732 | elsampsa/valkka-live | valkka/mvision/nix/base.py | ExternalDetector.close | def close(self):
"""Tell the process to exit
"""
try:
self.p.stdin.write(bytes("X\n","utf-8"))
self.p.stdin.flush()
except IOError:
self.report("could not send exit command")
self.p.wait() # wait until the process is closed
try:
os.remove(self.tmpfile) # clean up the temporary file
except FileNotFoundError:
pass | python | def close(self):
try:
self.p.stdin.write(bytes("X\n","utf-8"))
self.p.stdin.flush()
except IOError:
self.report("could not send exit command")
self.p.wait() # wait until the process is closed
try:
os.remove(self.tmpfile) # clean up the temporary file
except FileNotFoundError:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"p",
".",
"stdin",
".",
"write",
"(",
"bytes",
"(",
"\"X\\n\"",
",",
"\"utf-8\"",
")",
")",
"self",
".",
"p",
".",
"stdin",
".",
"flush",
"(",
")",
"except",
"IOError",
":",
"self",
... | Tell the process to exit | [
"Tell",
"the",
"process",
"to",
"exit"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/nix/base.py#L89-L101 |
10,733 | elsampsa/valkka-live | valkka/mvision/nix/base.py | MVisionProcess.postActivate_ | def postActivate_(self):
"""Create temporary file for image dumps and the analyzer itself
"""
self.tmpfile = os.path.join(constant.tmpdir,"valkka-"+str(os.getpid())) # e.g. "/tmp/valkka-10968"
self.analyzer = ExternalDetector(
executable = self.executable,
image_dimensions = self.image_dimensions,
tmpfile = self.tmpfile
) | python | def postActivate_(self):
self.tmpfile = os.path.join(constant.tmpdir,"valkka-"+str(os.getpid())) # e.g. "/tmp/valkka-10968"
self.analyzer = ExternalDetector(
executable = self.executable,
image_dimensions = self.image_dimensions,
tmpfile = self.tmpfile
) | [
"def",
"postActivate_",
"(",
"self",
")",
":",
"self",
".",
"tmpfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"constant",
".",
"tmpdir",
",",
"\"valkka-\"",
"+",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
")",
"# e.g. \"/tmp/valkka-10968\" ",
"... | Create temporary file for image dumps and the analyzer itself | [
"Create",
"temporary",
"file",
"for",
"image",
"dumps",
"and",
"the",
"analyzer",
"itself"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/nix/base.py#L198-L206 |
10,734 | veripress/veripress | veripress_cli/generate.py | generate_pages_by_file | def generate_pages_by_file():
"""Generates custom pages of 'file' storage type."""
from veripress import app
from veripress.model import storage
from veripress.model.parsers import get_standard_format_name
from veripress.helpers import traverse_directory
deploy_dir = get_deploy_dir()
def copy_file(src, dst):
makedirs(os.path.dirname(dst), mode=0o755, exist_ok=True)
shutil.copyfile(src, dst)
with app.app_context(), app.test_client() as client:
root_path = os.path.join(app.instance_path, 'pages')
for path in traverse_directory(root_path):
# e.g. 'a/b/c/index.md'
rel_path = os.path.relpath(path, root_path)
# e.g. ('a/b/c/index', '.md')
filename, ext = os.path.splitext(rel_path)
if get_standard_format_name(ext[1:]) is not None:
# is source of custom page
rel_url = filename.replace(os.path.sep, '/') + '.html'
page = storage.get_page(rel_url, include_draft=False)
if page is not None:
# it's not a draft, so generate the html page
makedirs(os.path.join(deploy_dir,
os.path.dirname(rel_path)),
mode=0o755, exist_ok=True)
with open(os.path.join(deploy_dir, filename + '.html'),
'wb') as f:
f.write(client.get('/' + rel_url).data)
if app.config['PAGE_SOURCE_ACCESSIBLE']:
copy_file(path, os.path.join(deploy_dir, rel_path))
else:
# is other direct files
copy_file(path, os.path.join(deploy_dir, rel_path)) | python | def generate_pages_by_file():
from veripress import app
from veripress.model import storage
from veripress.model.parsers import get_standard_format_name
from veripress.helpers import traverse_directory
deploy_dir = get_deploy_dir()
def copy_file(src, dst):
makedirs(os.path.dirname(dst), mode=0o755, exist_ok=True)
shutil.copyfile(src, dst)
with app.app_context(), app.test_client() as client:
root_path = os.path.join(app.instance_path, 'pages')
for path in traverse_directory(root_path):
# e.g. 'a/b/c/index.md'
rel_path = os.path.relpath(path, root_path)
# e.g. ('a/b/c/index', '.md')
filename, ext = os.path.splitext(rel_path)
if get_standard_format_name(ext[1:]) is not None:
# is source of custom page
rel_url = filename.replace(os.path.sep, '/') + '.html'
page = storage.get_page(rel_url, include_draft=False)
if page is not None:
# it's not a draft, so generate the html page
makedirs(os.path.join(deploy_dir,
os.path.dirname(rel_path)),
mode=0o755, exist_ok=True)
with open(os.path.join(deploy_dir, filename + '.html'),
'wb') as f:
f.write(client.get('/' + rel_url).data)
if app.config['PAGE_SOURCE_ACCESSIBLE']:
copy_file(path, os.path.join(deploy_dir, rel_path))
else:
# is other direct files
copy_file(path, os.path.join(deploy_dir, rel_path)) | [
"def",
"generate_pages_by_file",
"(",
")",
":",
"from",
"veripress",
"import",
"app",
"from",
"veripress",
".",
"model",
"import",
"storage",
"from",
"veripress",
".",
"model",
".",
"parsers",
"import",
"get_standard_format_name",
"from",
"veripress",
".",
"helper... | Generates custom pages of 'file' storage type. | [
"Generates",
"custom",
"pages",
"of",
"file",
"storage",
"type",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress_cli/generate.py#L123-L159 |
10,735 | elsampsa/valkka-live | valkka/live/datamodel.py | DataModel.define | def define(self):
"""Define column patterns and collections
"""
self.collections = []
self.camera_collection = \
SimpleCollection(filename=os.path.join(self.directory, "devices.dat"),
row_classes=[
DataModel.EmptyRow,
DataModel.RTSPCameraRow,
DataModel.USBCameraRow
]
)
self.collections.append(self.camera_collection)
self.config_collection = \
SimpleCollection(filename=os.path.join(self.directory, "config.dat"),
row_classes=[ # we could dump here all kinds of info related to different kind of configuration forms
DataModel.MemoryConfigRow
]
)
self.collections.append(self.config_collection) | python | def define(self):
self.collections = []
self.camera_collection = \
SimpleCollection(filename=os.path.join(self.directory, "devices.dat"),
row_classes=[
DataModel.EmptyRow,
DataModel.RTSPCameraRow,
DataModel.USBCameraRow
]
)
self.collections.append(self.camera_collection)
self.config_collection = \
SimpleCollection(filename=os.path.join(self.directory, "config.dat"),
row_classes=[ # we could dump here all kinds of info related to different kind of configuration forms
DataModel.MemoryConfigRow
]
)
self.collections.append(self.config_collection) | [
"def",
"define",
"(",
"self",
")",
":",
"self",
".",
"collections",
"=",
"[",
"]",
"self",
".",
"camera_collection",
"=",
"SimpleCollection",
"(",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"\"devices.dat\"",
")"... | Define column patterns and collections | [
"Define",
"column",
"patterns",
"and",
"collections"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/datamodel.py#L720-L741 |
10,736 | Jaymon/pout | pout/path.py | SiteCustomizeFile.inject | def inject(self):
"""inject code into sitecustomize.py that will inject pout into the builtins
so it will be available globally"""
if self.is_injected():
return False
with open(self, mode="a+") as fp:
fp.seek(0)
fp.write("\n".join([
"",
"try:",
" import pout",
"except ImportError:",
" pass",
"else:",
" pout.inject()",
"",
]))
return True | python | def inject(self):
if self.is_injected():
return False
with open(self, mode="a+") as fp:
fp.seek(0)
fp.write("\n".join([
"",
"try:",
" import pout",
"except ImportError:",
" pass",
"else:",
" pout.inject()",
"",
]))
return True | [
"def",
"inject",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_injected",
"(",
")",
":",
"return",
"False",
"with",
"open",
"(",
"self",
",",
"mode",
"=",
"\"a+\"",
")",
"as",
"fp",
":",
"fp",
".",
"seek",
"(",
"0",
")",
"fp",
".",
"write",
"("... | inject code into sitecustomize.py that will inject pout into the builtins
so it will be available globally | [
"inject",
"code",
"into",
"sitecustomize",
".",
"py",
"that",
"will",
"inject",
"pout",
"into",
"the",
"builtins",
"so",
"it",
"will",
"be",
"available",
"globally"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/path.py#L103-L122 |
10,737 | veripress/veripress | veripress/model/storages.py | Storage.fix_relative_url | def fix_relative_url(self, publish_type, rel_url):
"""
Fix post or page relative url to a standard, uniform format.
:param publish_type: publish type ('post' or 'page')
:param rel_url: relative url to fix
:return: tuple(fixed relative url or file path if exists else None,
file exists or not)
:raise ValueError: unknown publish type
"""
if publish_type == 'post':
return self.fix_post_relative_url(rel_url), False
elif publish_type == 'page':
return self.fix_page_relative_url(rel_url)
else:
raise ValueError(
'Publish type "{}" is not supported'.format(publish_type)) | python | def fix_relative_url(self, publish_type, rel_url):
if publish_type == 'post':
return self.fix_post_relative_url(rel_url), False
elif publish_type == 'page':
return self.fix_page_relative_url(rel_url)
else:
raise ValueError(
'Publish type "{}" is not supported'.format(publish_type)) | [
"def",
"fix_relative_url",
"(",
"self",
",",
"publish_type",
",",
"rel_url",
")",
":",
"if",
"publish_type",
"==",
"'post'",
":",
"return",
"self",
".",
"fix_post_relative_url",
"(",
"rel_url",
")",
",",
"False",
"elif",
"publish_type",
"==",
"'page'",
":",
... | Fix post or page relative url to a standard, uniform format.
:param publish_type: publish type ('post' or 'page')
:param rel_url: relative url to fix
:return: tuple(fixed relative url or file path if exists else None,
file exists or not)
:raise ValueError: unknown publish type | [
"Fix",
"post",
"or",
"page",
"relative",
"url",
"to",
"a",
"standard",
"uniform",
"format",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L38-L54 |
10,738 | veripress/veripress | veripress/model/storages.py | Storage.fix_post_relative_url | def fix_post_relative_url(rel_url):
"""
Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.htm
- 2016/8/09/my-post/index.html
:param rel_url: relative url to fix
:return: fixed relative url, or None if cannot recognize
"""
m = re.match(
r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/'
r'(?P<post_name>[^/]+?)'
r'(?:(?:\.html)|(?:/(?P<index>index(?:\.html?)?)?))?$',
rel_url
)
if not m:
return None
year, month, day, post_name = m.groups()[:4]
try:
d = date(year=int(year), month=int(month), day=int(day))
return '/'.join((d.strftime('%Y/%m/%d'), post_name,
'index.html' if m.group('index') else ''))
except (TypeError, ValueError):
# the date is invalid
return None | python | def fix_post_relative_url(rel_url):
m = re.match(
r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/'
r'(?P<post_name>[^/]+?)'
r'(?:(?:\.html)|(?:/(?P<index>index(?:\.html?)?)?))?$',
rel_url
)
if not m:
return None
year, month, day, post_name = m.groups()[:4]
try:
d = date(year=int(year), month=int(month), day=int(day))
return '/'.join((d.strftime('%Y/%m/%d'), post_name,
'index.html' if m.group('index') else ''))
except (TypeError, ValueError):
# the date is invalid
return None | [
"def",
"fix_post_relative_url",
"(",
"rel_url",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'^(?P<year>\\d{4})/(?P<month>\\d{1,2})/(?P<day>\\d{1,2})/'",
"r'(?P<post_name>[^/]+?)'",
"r'(?:(?:\\.html)|(?:/(?P<index>index(?:\\.html?)?)?))?$'",
",",
"rel_url",
")",
"if",
"not",
... | Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.htm
- 2016/8/09/my-post/index.html
:param rel_url: relative url to fix
:return: fixed relative url, or None if cannot recognize | [
"Fix",
"post",
"relative",
"url",
"to",
"a",
"standard",
"uniform",
"format",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L58-L89 |
10,739 | veripress/veripress | veripress/model/storages.py | Storage._filter_result | def _filter_result(result, filter_functions=None):
"""
Filter result with given filter functions.
:param result: an iterable object
:param filter_functions: some filter functions
:return: a filter object (filtered result)
"""
if filter_functions is not None:
for filter_func in filter_functions:
result = filter(filter_func, result)
return result | python | def _filter_result(result, filter_functions=None):
if filter_functions is not None:
for filter_func in filter_functions:
result = filter(filter_func, result)
return result | [
"def",
"_filter_result",
"(",
"result",
",",
"filter_functions",
"=",
"None",
")",
":",
"if",
"filter_functions",
"is",
"not",
"None",
":",
"for",
"filter_func",
"in",
"filter_functions",
":",
"result",
"=",
"filter",
"(",
"filter_func",
",",
"result",
")",
... | Filter result with given filter functions.
:param result: an iterable object
:param filter_functions: some filter functions
:return: a filter object (filtered result) | [
"Filter",
"result",
"with",
"given",
"filter",
"functions",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L160-L171 |
10,740 | veripress/veripress | veripress/model/storages.py | Storage.get_posts_with_limits | def get_posts_with_limits(self, include_draft=False, **limits):
"""
Get all posts and filter them as needed.
:param include_draft: return draft posts or not
:param limits: other limits to the attrs of the result,
should be a dict with string or list values
:return: an iterable of Post objects
"""
filter_funcs = []
for attr in ('title', 'layout', 'author',
'email', 'tags', 'categories'):
if limits.get(attr):
filter_set = set(to_list(limits.get(attr)))
def get_filter_func(filter_set_, attr_):
return lambda p: filter_set_.intersection(
to_list(getattr(p, attr_)))
filter_funcs.append(get_filter_func(filter_set, attr))
for attr in ('created', 'updated'):
interval = limits.get(attr)
if isinstance(interval, (list, tuple)) and len(interval) == 2 \
and isinstance(interval[0], date) and isinstance(
interval[1], date):
# [start date(time), end date(time)]
start, end = interval
start = to_datetime(start)
if not isinstance(end, datetime):
# 'end' is a date,
# we should convert it to 00:00:00 of the next day,
# so that posts of that day will be included
end = datetime.strptime(
'%04d-%02d-%02d' % (end.year, end.month, end.day),
'%Y-%m-%d')
end += timedelta(days=1)
def get_filter_func(attr_, start_dt, end_dt):
return lambda p: start_dt <= getattr(p, attr_) < end_dt
filter_funcs.append(get_filter_func(attr, start, end))
return self.get_posts(include_draft=include_draft,
filter_functions=filter_funcs) | python | def get_posts_with_limits(self, include_draft=False, **limits):
filter_funcs = []
for attr in ('title', 'layout', 'author',
'email', 'tags', 'categories'):
if limits.get(attr):
filter_set = set(to_list(limits.get(attr)))
def get_filter_func(filter_set_, attr_):
return lambda p: filter_set_.intersection(
to_list(getattr(p, attr_)))
filter_funcs.append(get_filter_func(filter_set, attr))
for attr in ('created', 'updated'):
interval = limits.get(attr)
if isinstance(interval, (list, tuple)) and len(interval) == 2 \
and isinstance(interval[0], date) and isinstance(
interval[1], date):
# [start date(time), end date(time)]
start, end = interval
start = to_datetime(start)
if not isinstance(end, datetime):
# 'end' is a date,
# we should convert it to 00:00:00 of the next day,
# so that posts of that day will be included
end = datetime.strptime(
'%04d-%02d-%02d' % (end.year, end.month, end.day),
'%Y-%m-%d')
end += timedelta(days=1)
def get_filter_func(attr_, start_dt, end_dt):
return lambda p: start_dt <= getattr(p, attr_) < end_dt
filter_funcs.append(get_filter_func(attr, start, end))
return self.get_posts(include_draft=include_draft,
filter_functions=filter_funcs) | [
"def",
"get_posts_with_limits",
"(",
"self",
",",
"include_draft",
"=",
"False",
",",
"*",
"*",
"limits",
")",
":",
"filter_funcs",
"=",
"[",
"]",
"for",
"attr",
"in",
"(",
"'title'",
",",
"'layout'",
",",
"'author'",
",",
"'email'",
",",
"'tags'",
",",
... | Get all posts and filter them as needed.
:param include_draft: return draft posts or not
:param limits: other limits to the attrs of the result,
should be a dict with string or list values
:return: an iterable of Post objects | [
"Get",
"all",
"posts",
"and",
"filter",
"them",
"as",
"needed",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L173-L218 |
10,741 | veripress/veripress | veripress/model/storages.py | Storage.search_for | def search_for(self, query, include_draft=False):
"""
Search for a query text.
:param query: keyword to query
:param include_draft: return draft posts/pages or not
:return: an iterable object of posts and pages (if allowed).
"""
query = query.lower()
if not query:
return []
def contains_query_keyword(post_or_page):
contains = query in post_or_page.title.lower() \
or query in Markup(
get_parser(post_or_page.format).parse_whole(
post_or_page.raw_content)
).striptags().lower()
return contains
return filter(contains_query_keyword,
chain(self.get_posts(include_draft=include_draft),
self.get_pages(include_draft=include_draft)
if current_app.config[
'ALLOW_SEARCH_PAGES'] else [])) | python | def search_for(self, query, include_draft=False):
query = query.lower()
if not query:
return []
def contains_query_keyword(post_or_page):
contains = query in post_or_page.title.lower() \
or query in Markup(
get_parser(post_or_page.format).parse_whole(
post_or_page.raw_content)
).striptags().lower()
return contains
return filter(contains_query_keyword,
chain(self.get_posts(include_draft=include_draft),
self.get_pages(include_draft=include_draft)
if current_app.config[
'ALLOW_SEARCH_PAGES'] else [])) | [
"def",
"search_for",
"(",
"self",
",",
"query",
",",
"include_draft",
"=",
"False",
")",
":",
"query",
"=",
"query",
".",
"lower",
"(",
")",
"if",
"not",
"query",
":",
"return",
"[",
"]",
"def",
"contains_query_keyword",
"(",
"post_or_page",
")",
":",
... | Search for a query text.
:param query: keyword to query
:param include_draft: return draft posts/pages or not
:return: an iterable object of posts and pages (if allowed). | [
"Search",
"for",
"a",
"query",
"text",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L220-L244 |
10,742 | veripress/veripress | veripress/model/storages.py | FileStorage.fix_page_relative_url | def fix_page_relative_url(rel_url):
"""
Fix page relative url to a standard, uniform format.
Possible input:
- my-page
- my-page/
- my-page/index
- my-page/index.htm
- my-page/index.html
- my-page/specific.file
:param rel_url: relative url to fix
:return: tuple(fixed relative url or FILE PATH if exists else None,
file exists or not)
"""
rel_url = rel_url.lstrip('/') # trim all heading '/'
endswith_slash = rel_url.endswith('/')
rel_url = rel_url.rstrip('/') + (
'/' if endswith_slash else '') # preserve only one trailing '/'
if not rel_url or rel_url == '/':
return None, False
file_path = os.path.join(current_app.instance_path, 'pages',
rel_url.replace('/', os.path.sep))
if rel_url.endswith('/'):
index_html_file_path = os.path.join(file_path, 'index.html')
if os.path.isfile(index_html_file_path):
# index.html exists
return index_html_file_path, True
return rel_url, False
elif os.path.isfile(file_path):
ext = os.path.splitext(file_path)[1][1:]
if get_standard_format_name(ext) is not None:
# is source of custom page
if current_app.config['PAGE_SOURCE_ACCESSIBLE']:
return file_path, True
else:
# is other direct files
return file_path, True
elif os.path.isdir(file_path):
return rel_url + '/', False
sp = rel_url.rsplit('/', 1)
m = re.match(r'(.+)\.html?', sp[-1])
if m:
sp[-1] = m.group(1) + '.html'
else:
sp[-1] += '.html'
return '/'.join(sp), False | python | def fix_page_relative_url(rel_url):
rel_url = rel_url.lstrip('/') # trim all heading '/'
endswith_slash = rel_url.endswith('/')
rel_url = rel_url.rstrip('/') + (
'/' if endswith_slash else '') # preserve only one trailing '/'
if not rel_url or rel_url == '/':
return None, False
file_path = os.path.join(current_app.instance_path, 'pages',
rel_url.replace('/', os.path.sep))
if rel_url.endswith('/'):
index_html_file_path = os.path.join(file_path, 'index.html')
if os.path.isfile(index_html_file_path):
# index.html exists
return index_html_file_path, True
return rel_url, False
elif os.path.isfile(file_path):
ext = os.path.splitext(file_path)[1][1:]
if get_standard_format_name(ext) is not None:
# is source of custom page
if current_app.config['PAGE_SOURCE_ACCESSIBLE']:
return file_path, True
else:
# is other direct files
return file_path, True
elif os.path.isdir(file_path):
return rel_url + '/', False
sp = rel_url.rsplit('/', 1)
m = re.match(r'(.+)\.html?', sp[-1])
if m:
sp[-1] = m.group(1) + '.html'
else:
sp[-1] += '.html'
return '/'.join(sp), False | [
"def",
"fix_page_relative_url",
"(",
"rel_url",
")",
":",
"rel_url",
"=",
"rel_url",
".",
"lstrip",
"(",
"'/'",
")",
"# trim all heading '/'",
"endswith_slash",
"=",
"rel_url",
".",
"endswith",
"(",
"'/'",
")",
"rel_url",
"=",
"rel_url",
".",
"rstrip",
"(",
... | Fix page relative url to a standard, uniform format.
Possible input:
- my-page
- my-page/
- my-page/index
- my-page/index.htm
- my-page/index.html
- my-page/specific.file
:param rel_url: relative url to fix
:return: tuple(fixed relative url or FILE PATH if exists else None,
file exists or not) | [
"Fix",
"page",
"relative",
"url",
"to",
"a",
"standard",
"uniform",
"format",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L250-L299 |
10,743 | veripress/veripress | veripress/model/storages.py | FileStorage.search_file | def search_file(search_root, search_filename,
instance_relative_root=False):
"""
Search for a filename in a specific search root dir.
:param search_root: root dir to search
:param search_filename: filename to search (no extension)
:param instance_relative_root: search root is relative to instance path
:return: tuple(full_file_path, extension without heading dot)
"""
if instance_relative_root:
search_root = os.path.join(current_app.instance_path, search_root)
file_path = None
file_ext = None
for file in os.listdir(search_root):
filename, ext = os.path.splitext(file)
if filename == search_filename and ext and ext != '.':
file_path = os.path.join(search_root, filename + ext)
file_ext = ext[1:] # remove heading '.' (dot)
break
return file_path, file_ext | python | def search_file(search_root, search_filename,
instance_relative_root=False):
if instance_relative_root:
search_root = os.path.join(current_app.instance_path, search_root)
file_path = None
file_ext = None
for file in os.listdir(search_root):
filename, ext = os.path.splitext(file)
if filename == search_filename and ext and ext != '.':
file_path = os.path.join(search_root, filename + ext)
file_ext = ext[1:] # remove heading '.' (dot)
break
return file_path, file_ext | [
"def",
"search_file",
"(",
"search_root",
",",
"search_filename",
",",
"instance_relative_root",
"=",
"False",
")",
":",
"if",
"instance_relative_root",
":",
"search_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_app",
".",
"instance_path",
",",
"sear... | Search for a filename in a specific search root dir.
:param search_root: root dir to search
:param search_filename: filename to search (no extension)
:param instance_relative_root: search root is relative to instance path
:return: tuple(full_file_path, extension without heading dot) | [
"Search",
"for",
"a",
"filename",
"in",
"a",
"specific",
"search",
"root",
"dir",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L303-L323 |
10,744 | veripress/veripress | veripress/model/storages.py | FileStorage.read_file | def read_file(file_path):
"""
Read yaml head and raw body content from a file.
:param file_path: file path
:return: tuple(meta, raw_content)
"""
with open(file_path, 'r', encoding='utf-8') as f:
whole = f.read().strip()
if whole.startswith('---'):
# may has yaml meta info, so we try to split it out
sp = re.split(r'-{3,}', whole.lstrip('-'), maxsplit=1)
if len(sp) == 2:
# do have yaml meta info, so we read it
return yaml.load(sp[0]), sp[1].lstrip()
return {}, whole | python | def read_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
whole = f.read().strip()
if whole.startswith('---'):
# may has yaml meta info, so we try to split it out
sp = re.split(r'-{3,}', whole.lstrip('-'), maxsplit=1)
if len(sp) == 2:
# do have yaml meta info, so we read it
return yaml.load(sp[0]), sp[1].lstrip()
return {}, whole | [
"def",
"read_file",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"whole",
"=",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"if",
"whole",
".",
"startswith",
... | Read yaml head and raw body content from a file.
:param file_path: file path
:return: tuple(meta, raw_content) | [
"Read",
"yaml",
"head",
"and",
"raw",
"body",
"content",
"from",
"a",
"file",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L331-L347 |
10,745 | veripress/veripress | veripress/model/storages.py | FileStorage.get_posts | def get_posts(self, include_draft=False, filter_functions=None):
"""
Get all posts from filesystem.
:param include_draft: return draft posts or not
:param filter_functions: filter to apply BEFORE result being sorted
:return: an iterable of Post objects (the first is the latest post)
"""
def posts_generator(path):
"""Loads valid posts one by one in the given path."""
if os.path.isdir(path):
for file in os.listdir(path):
filename, ext = os.path.splitext(file)
format_name = get_standard_format_name(ext[1:])
if format_name is not None and re.match(
r'\d{4}-\d{2}-\d{2}-.+', filename):
# the format is supported and the filename is valid,
# so load this post
post = Post()
post.format = format_name
post.meta, post.raw_content = FileStorage.read_file(
os.path.join(path, file))
post.rel_url = filename.replace('-', '/', 3) + '/'
post.unique_key = '/post/' + post.rel_url
yield post
posts_path = os.path.join(current_app.instance_path, 'posts')
result = filter(lambda p: include_draft or not p.is_draft,
posts_generator(posts_path))
result = self._filter_result(result, filter_functions)
return sorted(result, key=lambda p: p.created, reverse=True) | python | def get_posts(self, include_draft=False, filter_functions=None):
def posts_generator(path):
"""Loads valid posts one by one in the given path."""
if os.path.isdir(path):
for file in os.listdir(path):
filename, ext = os.path.splitext(file)
format_name = get_standard_format_name(ext[1:])
if format_name is not None and re.match(
r'\d{4}-\d{2}-\d{2}-.+', filename):
# the format is supported and the filename is valid,
# so load this post
post = Post()
post.format = format_name
post.meta, post.raw_content = FileStorage.read_file(
os.path.join(path, file))
post.rel_url = filename.replace('-', '/', 3) + '/'
post.unique_key = '/post/' + post.rel_url
yield post
posts_path = os.path.join(current_app.instance_path, 'posts')
result = filter(lambda p: include_draft or not p.is_draft,
posts_generator(posts_path))
result = self._filter_result(result, filter_functions)
return sorted(result, key=lambda p: p.created, reverse=True) | [
"def",
"get_posts",
"(",
"self",
",",
"include_draft",
"=",
"False",
",",
"filter_functions",
"=",
"None",
")",
":",
"def",
"posts_generator",
"(",
"path",
")",
":",
"\"\"\"Loads valid posts one by one in the given path.\"\"\"",
"if",
"os",
".",
"path",
".",
"isdi... | Get all posts from filesystem.
:param include_draft: return draft posts or not
:param filter_functions: filter to apply BEFORE result being sorted
:return: an iterable of Post objects (the first is the latest post) | [
"Get",
"all",
"posts",
"from",
"filesystem",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L350-L382 |
10,746 | veripress/veripress | veripress/model/storages.py | FileStorage.get_post | def get_post(self, rel_url, include_draft=False):
"""
Get post for given relative url from filesystem.
Possible input:
- 2017/01/01/my-post/
- 2017/01/01/my-post/index.html
:param rel_url: relative url
:param include_draft: return draft post or not
:return: a Post object
"""
raw_rel_url = str(rel_url)
if rel_url.endswith('/index.html'):
rel_url = rel_url.rsplit('/', 1)[
0] + '/' # remove the trailing 'index.html'
post_filename = rel_url[:-1].replace('/', '-')
post_file_path, post_file_ext = FileStorage.search_instance_file(
'posts', post_filename)
if post_file_path is None or post_file_ext is None or \
get_standard_format_name(post_file_ext) is None:
# no such post
return None
# construct the post object
post = Post()
post.rel_url = raw_rel_url
# 'rel_url' contains no trailing 'index.html'
post.unique_key = '/post/' + rel_url
post.format = get_standard_format_name(post_file_ext)
post.meta, post.raw_content = FileStorage.read_file(post_file_path)
return post if include_draft or not post.is_draft else None | python | def get_post(self, rel_url, include_draft=False):
raw_rel_url = str(rel_url)
if rel_url.endswith('/index.html'):
rel_url = rel_url.rsplit('/', 1)[
0] + '/' # remove the trailing 'index.html'
post_filename = rel_url[:-1].replace('/', '-')
post_file_path, post_file_ext = FileStorage.search_instance_file(
'posts', post_filename)
if post_file_path is None or post_file_ext is None or \
get_standard_format_name(post_file_ext) is None:
# no such post
return None
# construct the post object
post = Post()
post.rel_url = raw_rel_url
# 'rel_url' contains no trailing 'index.html'
post.unique_key = '/post/' + rel_url
post.format = get_standard_format_name(post_file_ext)
post.meta, post.raw_content = FileStorage.read_file(post_file_path)
return post if include_draft or not post.is_draft else None | [
"def",
"get_post",
"(",
"self",
",",
"rel_url",
",",
"include_draft",
"=",
"False",
")",
":",
"raw_rel_url",
"=",
"str",
"(",
"rel_url",
")",
"if",
"rel_url",
".",
"endswith",
"(",
"'/index.html'",
")",
":",
"rel_url",
"=",
"rel_url",
".",
"rsplit",
"(",... | Get post for given relative url from filesystem.
Possible input:
- 2017/01/01/my-post/
- 2017/01/01/my-post/index.html
:param rel_url: relative url
:param include_draft: return draft post or not
:return: a Post object | [
"Get",
"post",
"for",
"given",
"relative",
"url",
"from",
"filesystem",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L385-L417 |
10,747 | veripress/veripress | veripress/model/storages.py | FileStorage.get_tags | def get_tags(self):
"""
Get all tags and post count of each tag.
:return: dict_item(tag_name, Pair(count_all, count_published))
"""
posts = self.get_posts(include_draft=True)
result = {}
for post in posts:
for tag_name in set(post.tags):
result[tag_name] = result.setdefault(
tag_name, Pair(0, 0)) + Pair(1, 0 if post.is_draft else 1)
return list(result.items()) | python | def get_tags(self):
posts = self.get_posts(include_draft=True)
result = {}
for post in posts:
for tag_name in set(post.tags):
result[tag_name] = result.setdefault(
tag_name, Pair(0, 0)) + Pair(1, 0 if post.is_draft else 1)
return list(result.items()) | [
"def",
"get_tags",
"(",
"self",
")",
":",
"posts",
"=",
"self",
".",
"get_posts",
"(",
"include_draft",
"=",
"True",
")",
"result",
"=",
"{",
"}",
"for",
"post",
"in",
"posts",
":",
"for",
"tag_name",
"in",
"set",
"(",
"post",
".",
"tags",
")",
":"... | Get all tags and post count of each tag.
:return: dict_item(tag_name, Pair(count_all, count_published)) | [
"Get",
"all",
"tags",
"and",
"post",
"count",
"of",
"each",
"tag",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L420-L432 |
10,748 | veripress/veripress | veripress/model/storages.py | FileStorage.get_categories | def get_categories(self):
"""
Get all categories and post count of each category.
:return dict_item(category_name, Pair(count_all, count_published))
"""
posts = self.get_posts(include_draft=True)
result = {}
for post in posts:
for category_name in set(post.categories):
result[category_name] = result.setdefault(
category_name,
Pair(0, 0)) + Pair(1, 0 if post.is_draft else 1)
return list(result.items()) | python | def get_categories(self):
posts = self.get_posts(include_draft=True)
result = {}
for post in posts:
for category_name in set(post.categories):
result[category_name] = result.setdefault(
category_name,
Pair(0, 0)) + Pair(1, 0 if post.is_draft else 1)
return list(result.items()) | [
"def",
"get_categories",
"(",
"self",
")",
":",
"posts",
"=",
"self",
".",
"get_posts",
"(",
"include_draft",
"=",
"True",
")",
"result",
"=",
"{",
"}",
"for",
"post",
"in",
"posts",
":",
"for",
"category_name",
"in",
"set",
"(",
"post",
".",
"categori... | Get all categories and post count of each category.
:return dict_item(category_name, Pair(count_all, count_published)) | [
"Get",
"all",
"categories",
"and",
"post",
"count",
"of",
"each",
"category",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L435-L448 |
10,749 | veripress/veripress | veripress/model/storages.py | FileStorage.get_page | def get_page(self, rel_url, include_draft=False):
"""
Get custom page for given relative url from filesystem.
Possible input:
- my-page/
- my-page/index.html
- my-another-page.html
- a/b/c/
- a/b/c/d.html
:param rel_url: relative url
:param include_draft: return draft page or not
:return: a Page object
"""
page_dir = os.path.dirname(rel_url.replace('/', os.path.sep))
page_path = os.path.join(current_app.instance_path, 'pages', page_dir)
if not os.path.isdir(page_path):
# no such directory
return None
page_filename = rel_url[len(page_dir):].lstrip('/')
if not page_filename:
page_filename = 'index'
else:
page_filename = os.path.splitext(page_filename)[0]
page_file_path, page_file_ext = FileStorage.search_file(page_path,
page_filename)
if page_file_path is None or page_file_ext is None or \
get_standard_format_name(page_file_ext) is None:
# no such page
return None
page = Page()
page.rel_url = rel_url
page.unique_key = '/' + (
rel_url.rsplit('/', 1)[0] + '/' if rel_url.endswith(
'/index.html') else rel_url)
page.format = get_standard_format_name(page_file_ext)
page.meta, page.raw_content = FileStorage.read_file(page_file_path)
return page if include_draft or not page.is_draft else None | python | def get_page(self, rel_url, include_draft=False):
page_dir = os.path.dirname(rel_url.replace('/', os.path.sep))
page_path = os.path.join(current_app.instance_path, 'pages', page_dir)
if not os.path.isdir(page_path):
# no such directory
return None
page_filename = rel_url[len(page_dir):].lstrip('/')
if not page_filename:
page_filename = 'index'
else:
page_filename = os.path.splitext(page_filename)[0]
page_file_path, page_file_ext = FileStorage.search_file(page_path,
page_filename)
if page_file_path is None or page_file_ext is None or \
get_standard_format_name(page_file_ext) is None:
# no such page
return None
page = Page()
page.rel_url = rel_url
page.unique_key = '/' + (
rel_url.rsplit('/', 1)[0] + '/' if rel_url.endswith(
'/index.html') else rel_url)
page.format = get_standard_format_name(page_file_ext)
page.meta, page.raw_content = FileStorage.read_file(page_file_path)
return page if include_draft or not page.is_draft else None | [
"def",
"get_page",
"(",
"self",
",",
"rel_url",
",",
"include_draft",
"=",
"False",
")",
":",
"page_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"rel_url",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"path",
".",
"sep",
")",
")",
"page_path",
... | Get custom page for given relative url from filesystem.
Possible input:
- my-page/
- my-page/index.html
- my-another-page.html
- a/b/c/
- a/b/c/d.html
:param rel_url: relative url
:param include_draft: return draft page or not
:return: a Page object | [
"Get",
"custom",
"page",
"for",
"given",
"relative",
"url",
"from",
"filesystem",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L482-L523 |
10,750 | veripress/veripress | veripress/model/storages.py | FileStorage.get_widgets | def get_widgets(self, position=None, include_draft=False):
"""
Get widgets for given position from filesystem.
:param position: position or position list
:param include_draft: return draft widgets or not
:return: an iterable of Widget objects
"""
def widgets_generator(path):
"""Loads valid widgets one by one in the given path."""
if os.path.isdir(path):
for file in os.listdir(path):
_, ext = os.path.splitext(file)
format_name = get_standard_format_name(ext[1:])
if format_name is not None:
# the format is supported, so load it
widget = Widget()
widget.format = format_name
widget.meta, widget.raw_content = \
FileStorage.read_file(os.path.join(path, file))
yield widget
widgets_path = os.path.join(current_app.instance_path, 'widgets')
positions = to_list(position) if position is not None else position
result = filter(
lambda w: (w.position in positions
if positions is not None else True) and
(include_draft or not w.is_draft),
widgets_generator(widgets_path))
return sorted(result, key=lambda w: (w.position, w.order)) | python | def get_widgets(self, position=None, include_draft=False):
def widgets_generator(path):
"""Loads valid widgets one by one in the given path."""
if os.path.isdir(path):
for file in os.listdir(path):
_, ext = os.path.splitext(file)
format_name = get_standard_format_name(ext[1:])
if format_name is not None:
# the format is supported, so load it
widget = Widget()
widget.format = format_name
widget.meta, widget.raw_content = \
FileStorage.read_file(os.path.join(path, file))
yield widget
widgets_path = os.path.join(current_app.instance_path, 'widgets')
positions = to_list(position) if position is not None else position
result = filter(
lambda w: (w.position in positions
if positions is not None else True) and
(include_draft or not w.is_draft),
widgets_generator(widgets_path))
return sorted(result, key=lambda w: (w.position, w.order)) | [
"def",
"get_widgets",
"(",
"self",
",",
"position",
"=",
"None",
",",
"include_draft",
"=",
"False",
")",
":",
"def",
"widgets_generator",
"(",
"path",
")",
":",
"\"\"\"Loads valid widgets one by one in the given path.\"\"\"",
"if",
"os",
".",
"path",
".",
"isdir"... | Get widgets for given position from filesystem.
:param position: position or position list
:param include_draft: return draft widgets or not
:return: an iterable of Widget objects | [
"Get",
"widgets",
"for",
"given",
"position",
"from",
"filesystem",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/storages.py#L526-L556 |
10,751 | veripress/veripress | veripress/view/__init__.py | custom_render_template | def custom_render_template(template_name_or_list, **context):
"""
Try to render templates in the custom folder first,
if no custom templates, try the theme's default ones.
"""
response_str = render_template(
functools.reduce(lambda x, y: x + [os.path.join('custom', y), y],
to_list(template_name_or_list), []),
**context
)
if hasattr(g, 'status_code'):
status_code = g.status_code
else:
status_code = 200
return response_str, status_code | python | def custom_render_template(template_name_or_list, **context):
response_str = render_template(
functools.reduce(lambda x, y: x + [os.path.join('custom', y), y],
to_list(template_name_or_list), []),
**context
)
if hasattr(g, 'status_code'):
status_code = g.status_code
else:
status_code = 200
return response_str, status_code | [
"def",
"custom_render_template",
"(",
"template_name_or_list",
",",
"*",
"*",
"context",
")",
":",
"response_str",
"=",
"render_template",
"(",
"functools",
".",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"[",
"os",
".",
"path",
".",
"join",
... | Try to render templates in the custom folder first,
if no custom templates, try the theme's default ones. | [
"Try",
"to",
"render",
"templates",
"in",
"the",
"custom",
"folder",
"first",
"if",
"no",
"custom",
"templates",
"try",
"the",
"theme",
"s",
"default",
"ones",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/view/__init__.py#L36-L50 |
10,752 | veripress/veripress | veripress/view/__init__.py | templated | def templated(template=None, *templates):
"""
Decorate a view function with one or more default template name.
This will try templates in the custom folder first,
the theme's original ones second.
:param template: template name or template name list
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
template_ = template
if template_ is None:
template_ = request.endpoint.split('.', 1)[1].replace(
'.', '/') + '.html'
context = func(*args, **kwargs)
if context is None:
context = {}
elif not isinstance(context, dict):
return context
return custom_render_template(
list(chain(to_list(template_), templates)), **context)
return wrapper
return decorator | python | def templated(template=None, *templates):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
template_ = template
if template_ is None:
template_ = request.endpoint.split('.', 1)[1].replace(
'.', '/') + '.html'
context = func(*args, **kwargs)
if context is None:
context = {}
elif not isinstance(context, dict):
return context
return custom_render_template(
list(chain(to_list(template_), templates)), **context)
return wrapper
return decorator | [
"def",
"templated",
"(",
"template",
"=",
"None",
",",
"*",
"templates",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | Decorate a view function with one or more default template name.
This will try templates in the custom folder first,
the theme's original ones second.
:param template: template name or template name list | [
"Decorate",
"a",
"view",
"function",
"with",
"one",
"or",
"more",
"default",
"template",
"name",
".",
"This",
"will",
"try",
"templates",
"in",
"the",
"custom",
"folder",
"first",
"the",
"theme",
"s",
"original",
"ones",
"second",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/view/__init__.py#L53-L79 |
10,753 | veripress/veripress | veripress_cli/helpers.py | copy_folder_content | def copy_folder_content(src, dst):
"""
Copy all content in src directory to dst directory.
The src and dst must exist.
"""
for file in os.listdir(src):
file_path = os.path.join(src, file)
dst_file_path = os.path.join(dst, file)
if os.path.isdir(file_path):
shutil.copytree(file_path, dst_file_path)
else:
shutil.copyfile(file_path, dst_file_path) | python | def copy_folder_content(src, dst):
for file in os.listdir(src):
file_path = os.path.join(src, file)
dst_file_path = os.path.join(dst, file)
if os.path.isdir(file_path):
shutil.copytree(file_path, dst_file_path)
else:
shutil.copyfile(file_path, dst_file_path) | [
"def",
"copy_folder_content",
"(",
"src",
",",
"dst",
")",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"src",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src",
",",
"file",
")",
"dst_file_path",
"=",
"os",
".",
"path"... | Copy all content in src directory to dst directory.
The src and dst must exist. | [
"Copy",
"all",
"content",
"in",
"src",
"directory",
"to",
"dst",
"directory",
".",
"The",
"src",
"and",
"dst",
"must",
"exist",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress_cli/helpers.py#L5-L16 |
10,754 | veripress/veripress | veripress_cli/helpers.py | remove_folder_content | def remove_folder_content(path, ignore_hidden_file=False):
"""
Remove all content in the given folder.
"""
for file in os.listdir(path):
if ignore_hidden_file and file.startswith('.'):
continue
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
shutil.rmtree(file_path)
else:
os.remove(file_path) | python | def remove_folder_content(path, ignore_hidden_file=False):
for file in os.listdir(path):
if ignore_hidden_file and file.startswith('.'):
continue
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
shutil.rmtree(file_path)
else:
os.remove(file_path) | [
"def",
"remove_folder_content",
"(",
"path",
",",
"ignore_hidden_file",
"=",
"False",
")",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"ignore_hidden_file",
"and",
"file",
".",
"startswith",
"(",
"'.'",
")",
":",
"continue"... | Remove all content in the given folder. | [
"Remove",
"all",
"content",
"in",
"the",
"given",
"folder",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress_cli/helpers.py#L19-L31 |
10,755 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.unload | def unload(self):
"""
Unloads OpenALPR from memory.
:return: None
"""
if self.loaded:
self.loaded = False
self._openalprpy_lib.dispose(self.alpr_pointer) | python | def unload(self):
if self.loaded:
self.loaded = False
self._openalprpy_lib.dispose(self.alpr_pointer) | [
"def",
"unload",
"(",
"self",
")",
":",
"if",
"self",
".",
"loaded",
":",
"self",
".",
"loaded",
"=",
"False",
"self",
".",
"_openalprpy_lib",
".",
"dispose",
"(",
"self",
".",
"alpr_pointer",
")"
] | Unloads OpenALPR from memory.
:return: None | [
"Unloads",
"OpenALPR",
"from",
"memory",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L127-L136 |
10,756 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.recognize_file | def recognize_file(self, file_path):
"""
This causes OpenALPR to attempt to recognize an image by opening a file on
disk.
:param file_path: The path to the image that will be analyzed
:return: An OpenALPR analysis in the form of a response dictionary
"""
file_path = _convert_to_charp(file_path)
ptr = self._recognize_file_func(self.alpr_pointer, file_path)
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | python | def recognize_file(self, file_path):
file_path = _convert_to_charp(file_path)
ptr = self._recognize_file_func(self.alpr_pointer, file_path)
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | [
"def",
"recognize_file",
"(",
"self",
",",
"file_path",
")",
":",
"file_path",
"=",
"_convert_to_charp",
"(",
"file_path",
")",
"ptr",
"=",
"self",
".",
"_recognize_file_func",
"(",
"self",
".",
"alpr_pointer",
",",
"file_path",
")",
"json_data",
"=",
"ctypes"... | This causes OpenALPR to attempt to recognize an image by opening a file on
disk.
:param file_path: The path to the image that will be analyzed
:return: An OpenALPR analysis in the form of a response dictionary | [
"This",
"causes",
"OpenALPR",
"to",
"attempt",
"to",
"recognize",
"an",
"image",
"by",
"opening",
"a",
"file",
"on",
"disk",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L149-L163 |
10,757 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.recognize_array | def recognize_array(self, byte_array):
"""
This causes OpenALPR to attempt to recognize an image passed in as a byte array.
:param byte_array: This should be a string (Python 2) or a bytes object (Python 3)
:return: An OpenALPR analysis in the form of a response dictionary
"""
if type(byte_array) != bytes:
raise TypeError("Expected a byte array (string in Python 2, bytes in Python 3)")
pb = ctypes.cast(byte_array, ctypes.POINTER(ctypes.c_ubyte))
ptr = self._recognize_array_func(self.alpr_pointer, pb, len(byte_array))
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | python | def recognize_array(self, byte_array):
if type(byte_array) != bytes:
raise TypeError("Expected a byte array (string in Python 2, bytes in Python 3)")
pb = ctypes.cast(byte_array, ctypes.POINTER(ctypes.c_ubyte))
ptr = self._recognize_array_func(self.alpr_pointer, pb, len(byte_array))
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | [
"def",
"recognize_array",
"(",
"self",
",",
"byte_array",
")",
":",
"if",
"type",
"(",
"byte_array",
")",
"!=",
"bytes",
":",
"raise",
"TypeError",
"(",
"\"Expected a byte array (string in Python 2, bytes in Python 3)\"",
")",
"pb",
"=",
"ctypes",
".",
"cast",
"("... | This causes OpenALPR to attempt to recognize an image passed in as a byte array.
:param byte_array: This should be a string (Python 2) or a bytes object (Python 3)
:return: An OpenALPR analysis in the form of a response dictionary | [
"This",
"causes",
"OpenALPR",
"to",
"attempt",
"to",
"recognize",
"an",
"image",
"passed",
"in",
"as",
"a",
"byte",
"array",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L165-L180 |
10,758 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.recognize_ndarray | def recognize_ndarray(self, ndarray):
"""
This causes OpenALPR to attempt to recognize an image passed in as a numpy array.
:param ndarray: numpy.array as used in cv2 module
:return: An OpenALPR analysis in the form of a response dictionary
"""
if self._recognize_raw_image_func is None:
raise RuntimeError('NumPy missing')
height, width = ndarray.shape[:2]
bpp = ndarray.shape[2] if len(ndarray.shape) > 2 else 1
ptr = self._recognize_raw_image_func(self.alpr_pointer, ndarray.flatten(), bpp, width, height)
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
# there is a bug in the openalpr python bindings
# sometimes there are real numbers with "," as the decimal point..!
# print("openalpr_lib : recognize_ndarray : json_data =", json_data)
p = re.compile('\d(\,)\d')
json_data = p.subn(".", json_data)[0]
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | python | def recognize_ndarray(self, ndarray):
if self._recognize_raw_image_func is None:
raise RuntimeError('NumPy missing')
height, width = ndarray.shape[:2]
bpp = ndarray.shape[2] if len(ndarray.shape) > 2 else 1
ptr = self._recognize_raw_image_func(self.alpr_pointer, ndarray.flatten(), bpp, width, height)
json_data = ctypes.cast(ptr, ctypes.c_char_p).value
json_data = _convert_from_charp(json_data)
# there is a bug in the openalpr python bindings
# sometimes there are real numbers with "," as the decimal point..!
# print("openalpr_lib : recognize_ndarray : json_data =", json_data)
p = re.compile('\d(\,)\d')
json_data = p.subn(".", json_data)[0]
response_obj = json.loads(json_data)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return response_obj | [
"def",
"recognize_ndarray",
"(",
"self",
",",
"ndarray",
")",
":",
"if",
"self",
".",
"_recognize_raw_image_func",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'NumPy missing'",
")",
"height",
",",
"width",
"=",
"ndarray",
".",
"shape",
"[",
":",
"2",
... | This causes OpenALPR to attempt to recognize an image passed in as a numpy array.
:param ndarray: numpy.array as used in cv2 module
:return: An OpenALPR analysis in the form of a response dictionary | [
"This",
"causes",
"OpenALPR",
"to",
"attempt",
"to",
"recognize",
"an",
"image",
"passed",
"in",
"as",
"a",
"numpy",
"array",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L182-L205 |
10,759 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.get_version | def get_version(self):
"""
This gets the version of OpenALPR
:return: Version information
"""
ptr = self._get_version_func(self.alpr_pointer)
version_number = ctypes.cast(ptr, ctypes.c_char_p).value
version_number = _convert_from_charp(version_number)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return version_number | python | def get_version(self):
ptr = self._get_version_func(self.alpr_pointer)
version_number = ctypes.cast(ptr, ctypes.c_char_p).value
version_number = _convert_from_charp(version_number)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return version_number | [
"def",
"get_version",
"(",
"self",
")",
":",
"ptr",
"=",
"self",
".",
"_get_version_func",
"(",
"self",
".",
"alpr_pointer",
")",
"version_number",
"=",
"ctypes",
".",
"cast",
"(",
"ptr",
",",
"ctypes",
".",
"c_char_p",
")",
".",
"value",
"version_number",... | This gets the version of OpenALPR
:return: Version information | [
"This",
"gets",
"the",
"version",
"of",
"OpenALPR"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L207-L218 |
10,760 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.set_country | def set_country(self, country):
"""
This sets the country for detecting license plates. For example,
setting country to "us" for United States or "eu" for Europe.
:param country: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
country = _convert_to_charp(country)
self._set_country_func(self.alpr_pointer, country) | python | def set_country(self, country):
country = _convert_to_charp(country)
self._set_country_func(self.alpr_pointer, country) | [
"def",
"set_country",
"(",
"self",
",",
"country",
")",
":",
"country",
"=",
"_convert_to_charp",
"(",
"country",
")",
"self",
".",
"_set_country_func",
"(",
"self",
".",
"alpr_pointer",
",",
"country",
")"
] | This sets the country for detecting license plates. For example,
setting country to "us" for United States or "eu" for Europe.
:param country: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None | [
"This",
"sets",
"the",
"country",
"for",
"detecting",
"license",
"plates",
".",
"For",
"example",
"setting",
"country",
"to",
"us",
"for",
"United",
"States",
"or",
"eu",
"for",
"Europe",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L230-L239 |
10,761 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.set_prewarp | def set_prewarp(self, prewarp):
"""
Updates the prewarp configuration used to skew images in OpenALPR before
processing.
:param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
prewarp = _convert_to_charp(prewarp)
self._set_prewarp_func(self.alpr_pointer, prewarp) | python | def set_prewarp(self, prewarp):
prewarp = _convert_to_charp(prewarp)
self._set_prewarp_func(self.alpr_pointer, prewarp) | [
"def",
"set_prewarp",
"(",
"self",
",",
"prewarp",
")",
":",
"prewarp",
"=",
"_convert_to_charp",
"(",
"prewarp",
")",
"self",
".",
"_set_prewarp_func",
"(",
"self",
".",
"alpr_pointer",
",",
"prewarp",
")"
] | Updates the prewarp configuration used to skew images in OpenALPR before
processing.
:param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None | [
"Updates",
"the",
"prewarp",
"configuration",
"used",
"to",
"skew",
"images",
"in",
"OpenALPR",
"before",
"processing",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L241-L250 |
10,762 | elsampsa/valkka-live | valkka/mvision/alpr/openalpr_fix.py | Alpr.set_default_region | def set_default_region(self, region):
"""
This sets the default region for detecting license plates. For example,
setting region to "md" for Maryland or "fr" for France.
:param region: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None
"""
region = _convert_to_charp(region)
self._set_default_region_func(self.alpr_pointer, region) | python | def set_default_region(self, region):
region = _convert_to_charp(region)
self._set_default_region_func(self.alpr_pointer, region) | [
"def",
"set_default_region",
"(",
"self",
",",
"region",
")",
":",
"region",
"=",
"_convert_to_charp",
"(",
"region",
")",
"self",
".",
"_set_default_region_func",
"(",
"self",
".",
"alpr_pointer",
",",
"region",
")"
] | This sets the default region for detecting license plates. For example,
setting region to "md" for Maryland or "fr" for France.
:param region: A unicode/ascii string (Python 2/3) or bytes array (Python 3)
:return: None | [
"This",
"sets",
"the",
"default",
"region",
"for",
"detecting",
"license",
"plates",
".",
"For",
"example",
"setting",
"region",
"to",
"md",
"for",
"Maryland",
"or",
"fr",
"for",
"France",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/alpr/openalpr_fix.py#L252-L261 |
10,763 | Jaymon/pout | pout/reflect.py | CallString.is_complete | def is_complete(self):
"""Return True if this call string is complete, meaning it has a function
name and balanced parens"""
try:
[t for t in self.tokens]
ret = True
logger.debug('CallString [{}] is complete'.format(self.strip()))
except tokenize.TokenError:
logger.debug('CallString [{}] is NOT complete'.format(self.strip()))
ret = False
return ret | python | def is_complete(self):
try:
[t for t in self.tokens]
ret = True
logger.debug('CallString [{}] is complete'.format(self.strip()))
except tokenize.TokenError:
logger.debug('CallString [{}] is NOT complete'.format(self.strip()))
ret = False
return ret | [
"def",
"is_complete",
"(",
"self",
")",
":",
"try",
":",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"tokens",
"]",
"ret",
"=",
"True",
"logger",
".",
"debug",
"(",
"'CallString [{}] is complete'",
".",
"format",
"(",
"self",
".",
"strip",
"(",
")",
")"... | Return True if this call string is complete, meaning it has a function
name and balanced parens | [
"Return",
"True",
"if",
"this",
"call",
"string",
"is",
"complete",
"meaning",
"it",
"has",
"a",
"function",
"name",
"and",
"balanced",
"parens"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/reflect.py#L30-L42 |
10,764 | Jaymon/pout | pout/reflect.py | Call._find_calls | def _find_calls(self, ast_tree, called_module, called_func):
'''
scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
from pout import v
from pout import v as voom
import pout as poom
# this function would return: ['pout.v', 'v', 'voom', 'poom.v']
module finder might be useful someday
link -- http://docs.python.org/library/modulefinder.html
link -- http://stackoverflow.com/questions/2572582/return-a-list-of-imported-python-modules-used-in-a-script
ast_tree -- _ast.* instance -- the internal ast object that is being checked, returned from compile()
with ast.PyCF_ONLY_AST flag
called_module -- string -- we are checking the ast for imports of this module
called_func -- string -- we are checking the ast for aliases of this function
return -- set -- the list of possible calls the ast_tree could make to call the called_func
'''
s = set()
# always add the default call, the set will make sure there are no dupes...
s.add("{}.{}".format(called_module, called_func))
if hasattr(ast_tree, 'name'):
if ast_tree.name == called_func:
# the function is defined in this module
s.add(called_func)
if hasattr(ast_tree, 'body'):
# further down the rabbit hole we go
if isinstance(ast_tree.body, Iterable):
for ast_body in ast_tree.body:
s.update(self._find_calls(ast_body, called_module, called_func))
elif hasattr(ast_tree, 'names'):
# base case
if hasattr(ast_tree, 'module'):
# we are in a from ... import ... statement
if ast_tree.module == called_module:
for ast_name in ast_tree.names:
if ast_name.name == called_func:
s.add(unicode(ast_name.asname if ast_name.asname is not None else ast_name.name))
else:
# we are in a import ... statement
for ast_name in ast_tree.names:
if hasattr(ast_name, 'name') and (ast_name.name == called_module):
call = "{}.{}".format(
ast_name.asname if ast_name.asname is not None else ast_name.name,
called_func
)
s.add(call)
return s | python | def _find_calls(self, ast_tree, called_module, called_func):
'''
scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
from pout import v
from pout import v as voom
import pout as poom
# this function would return: ['pout.v', 'v', 'voom', 'poom.v']
module finder might be useful someday
link -- http://docs.python.org/library/modulefinder.html
link -- http://stackoverflow.com/questions/2572582/return-a-list-of-imported-python-modules-used-in-a-script
ast_tree -- _ast.* instance -- the internal ast object that is being checked, returned from compile()
with ast.PyCF_ONLY_AST flag
called_module -- string -- we are checking the ast for imports of this module
called_func -- string -- we are checking the ast for aliases of this function
return -- set -- the list of possible calls the ast_tree could make to call the called_func
'''
s = set()
# always add the default call, the set will make sure there are no dupes...
s.add("{}.{}".format(called_module, called_func))
if hasattr(ast_tree, 'name'):
if ast_tree.name == called_func:
# the function is defined in this module
s.add(called_func)
if hasattr(ast_tree, 'body'):
# further down the rabbit hole we go
if isinstance(ast_tree.body, Iterable):
for ast_body in ast_tree.body:
s.update(self._find_calls(ast_body, called_module, called_func))
elif hasattr(ast_tree, 'names'):
# base case
if hasattr(ast_tree, 'module'):
# we are in a from ... import ... statement
if ast_tree.module == called_module:
for ast_name in ast_tree.names:
if ast_name.name == called_func:
s.add(unicode(ast_name.asname if ast_name.asname is not None else ast_name.name))
else:
# we are in a import ... statement
for ast_name in ast_tree.names:
if hasattr(ast_name, 'name') and (ast_name.name == called_module):
call = "{}.{}".format(
ast_name.asname if ast_name.asname is not None else ast_name.name,
called_func
)
s.add(call)
return s | [
"def",
"_find_calls",
"(",
"self",
",",
"ast_tree",
",",
"called_module",
",",
"called_func",
")",
":",
"s",
"=",
"set",
"(",
")",
"# always add the default call, the set will make sure there are no dupes...",
"s",
".",
"add",
"(",
"\"{}.{}\"",
".",
"format",
"(",
... | scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
from pout import v
from pout import v as voom
import pout as poom
# this function would return: ['pout.v', 'v', 'voom', 'poom.v']
module finder might be useful someday
link -- http://docs.python.org/library/modulefinder.html
link -- http://stackoverflow.com/questions/2572582/return-a-list-of-imported-python-modules-used-in-a-script
ast_tree -- _ast.* instance -- the internal ast object that is being checked, returned from compile()
with ast.PyCF_ONLY_AST flag
called_module -- string -- we are checking the ast for imports of this module
called_func -- string -- we are checking the ast for aliases of this function
return -- set -- the list of possible calls the ast_tree could make to call the called_func | [
"scan",
"the",
"abstract",
"source",
"tree",
"looking",
"for",
"possible",
"ways",
"to",
"call",
"the",
"called_module",
"and",
"called_func"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/reflect.py#L277-L339 |
10,765 | Jaymon/pout | pout/reflect.py | Reflect._get_arg_info | def _get_arg_info(self):
'''
get all the info of a method call
this will find what arg names you passed into the method and tie them to their passed in values,
it will also find file and line number
return -- dict -- a bunch of info on the call
'''
ret_dict = {
'args': [],
#'frame': None,
'line': 'Unknown',
'file': 'Unknown',
'arg_names': []
}
arg_vals = self.arg_vals
#modname = self.modname
c = self.call
ret_dict.update(c.info)
if len(arg_vals) > 0:
args = []
if len(ret_dict['arg_names']) > 0:
# match the found arg names to their respective values
for i, arg_name in enumerate(ret_dict['arg_names']):
args.append({'name': arg_name, 'val': arg_vals[i]})
else:
# we can't autodiscover the names, in an interactive shell session?
for i, arg_val in enumerate(arg_vals):
args.append({'name': 'Unknown {}'.format(i), 'val': arg_val})
ret_dict['args'] = args
return ret_dict | python | def _get_arg_info(self):
'''
get all the info of a method call
this will find what arg names you passed into the method and tie them to their passed in values,
it will also find file and line number
return -- dict -- a bunch of info on the call
'''
ret_dict = {
'args': [],
#'frame': None,
'line': 'Unknown',
'file': 'Unknown',
'arg_names': []
}
arg_vals = self.arg_vals
#modname = self.modname
c = self.call
ret_dict.update(c.info)
if len(arg_vals) > 0:
args = []
if len(ret_dict['arg_names']) > 0:
# match the found arg names to their respective values
for i, arg_name in enumerate(ret_dict['arg_names']):
args.append({'name': arg_name, 'val': arg_vals[i]})
else:
# we can't autodiscover the names, in an interactive shell session?
for i, arg_val in enumerate(arg_vals):
args.append({'name': 'Unknown {}'.format(i), 'val': arg_val})
ret_dict['args'] = args
return ret_dict | [
"def",
"_get_arg_info",
"(",
"self",
")",
":",
"ret_dict",
"=",
"{",
"'args'",
":",
"[",
"]",
",",
"#'frame': None,",
"'line'",
":",
"'Unknown'",
",",
"'file'",
":",
"'Unknown'",
",",
"'arg_names'",
":",
"[",
"]",
"}",
"arg_vals",
"=",
"self",
".",
"ar... | get all the info of a method call
this will find what arg names you passed into the method and tie them to their passed in values,
it will also find file and line number
return -- dict -- a bunch of info on the call | [
"get",
"all",
"the",
"info",
"of",
"a",
"method",
"call"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/reflect.py#L368-L405 |
10,766 | Jaymon/pout | pout/reflect.py | Reflect._find_entry_call | def _find_entry_call(self, frames):
"""attempts to auto-discover the correct frame"""
back_i = 0
pout_path = self._get_src_file(self.modname)
for frame_i, frame in enumerate(frames):
if frame[1] == pout_path:
back_i = frame_i
return Call(frames[back_i]) | python | def _find_entry_call(self, frames):
back_i = 0
pout_path = self._get_src_file(self.modname)
for frame_i, frame in enumerate(frames):
if frame[1] == pout_path:
back_i = frame_i
return Call(frames[back_i]) | [
"def",
"_find_entry_call",
"(",
"self",
",",
"frames",
")",
":",
"back_i",
"=",
"0",
"pout_path",
"=",
"self",
".",
"_get_src_file",
"(",
"self",
".",
"modname",
")",
"for",
"frame_i",
",",
"frame",
"in",
"enumerate",
"(",
"frames",
")",
":",
"if",
"fr... | attempts to auto-discover the correct frame | [
"attempts",
"to",
"auto",
"-",
"discover",
"the",
"correct",
"frame"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/reflect.py#L425-L434 |
10,767 | veripress/veripress | veripress/helpers.py | url_rule | def url_rule(blueprint_or_app, rules,
endpoint=None, view_func=None, **options):
"""
Add one or more url rules to the given Flask blueprint or app.
:param blueprint_or_app: Flask blueprint or app
:param rules: a single rule string or a list of rules
:param endpoint: endpoint
:param view_func: view function
:param options: other options
"""
for rule in to_list(rules):
blueprint_or_app.add_url_rule(rule,
endpoint=endpoint,
view_func=view_func,
**options) | python | def url_rule(blueprint_or_app, rules,
endpoint=None, view_func=None, **options):
for rule in to_list(rules):
blueprint_or_app.add_url_rule(rule,
endpoint=endpoint,
view_func=view_func,
**options) | [
"def",
"url_rule",
"(",
"blueprint_or_app",
",",
"rules",
",",
"endpoint",
"=",
"None",
",",
"view_func",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"for",
"rule",
"in",
"to_list",
"(",
"rules",
")",
":",
"blueprint_or_app",
".",
"add_url_rule",
"(... | Add one or more url rules to the given Flask blueprint or app.
:param blueprint_or_app: Flask blueprint or app
:param rules: a single rule string or a list of rules
:param endpoint: endpoint
:param view_func: view function
:param options: other options | [
"Add",
"one",
"or",
"more",
"url",
"rules",
"to",
"the",
"given",
"Flask",
"blueprint",
"or",
"app",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L9-L24 |
10,768 | veripress/veripress | veripress/helpers.py | to_list | def to_list(item_or_list):
"""
Convert a single item, a tuple, a generator or anything else to a list.
:param item_or_list: single item or iterable to convert
:return: a list
"""
if isinstance(item_or_list, list):
return item_or_list
elif isinstance(item_or_list, (str, bytes)):
return [item_or_list]
elif isinstance(item_or_list, Iterable):
return list(item_or_list)
else:
return [item_or_list] | python | def to_list(item_or_list):
if isinstance(item_or_list, list):
return item_or_list
elif isinstance(item_or_list, (str, bytes)):
return [item_or_list]
elif isinstance(item_or_list, Iterable):
return list(item_or_list)
else:
return [item_or_list] | [
"def",
"to_list",
"(",
"item_or_list",
")",
":",
"if",
"isinstance",
"(",
"item_or_list",
",",
"list",
")",
":",
"return",
"item_or_list",
"elif",
"isinstance",
"(",
"item_or_list",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"return",
"[",
"item_or_list... | Convert a single item, a tuple, a generator or anything else to a list.
:param item_or_list: single item or iterable to convert
:return: a list | [
"Convert",
"a",
"single",
"item",
"a",
"tuple",
"a",
"generator",
"or",
"anything",
"else",
"to",
"a",
"list",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L27-L41 |
10,769 | veripress/veripress | veripress/helpers.py | to_datetime | def to_datetime(date_or_datetime):
"""
Convert a date object to a datetime object,
or return as it is if it's not a date object.
:param date_or_datetime: date or datetime object
:return: a datetime object
"""
if isinstance(date_or_datetime, date) and \
not isinstance(date_or_datetime, datetime):
d = date_or_datetime
return datetime.strptime(
'%04d-%02d-%02d' % (d.year, d.month, d.day), '%Y-%m-%d')
return date_or_datetime | python | def to_datetime(date_or_datetime):
if isinstance(date_or_datetime, date) and \
not isinstance(date_or_datetime, datetime):
d = date_or_datetime
return datetime.strptime(
'%04d-%02d-%02d' % (d.year, d.month, d.day), '%Y-%m-%d')
return date_or_datetime | [
"def",
"to_datetime",
"(",
"date_or_datetime",
")",
":",
"if",
"isinstance",
"(",
"date_or_datetime",
",",
"date",
")",
"and",
"not",
"isinstance",
"(",
"date_or_datetime",
",",
"datetime",
")",
":",
"d",
"=",
"date_or_datetime",
"return",
"datetime",
".",
"st... | Convert a date object to a datetime object,
or return as it is if it's not a date object.
:param date_or_datetime: date or datetime object
:return: a datetime object | [
"Convert",
"a",
"date",
"object",
"to",
"a",
"datetime",
"object",
"or",
"return",
"as",
"it",
"is",
"if",
"it",
"s",
"not",
"a",
"date",
"object",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L44-L57 |
10,770 | veripress/veripress | veripress/helpers.py | timezone_from_str | def timezone_from_str(tz_str):
"""
Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo)
"""
m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
if m:
# in format 'UTC±[hh]:[mm]'
delta_h = int(m.group(1))
delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
return timezone(timedelta(hours=delta_h, minutes=delta_m))
# in format 'Asia/Shanghai'
try:
return pytz.timezone(tz_str)
except pytz.exceptions.UnknownTimeZoneError:
return None | python | def timezone_from_str(tz_str):
m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
if m:
# in format 'UTC±[hh]:[mm]'
delta_h = int(m.group(1))
delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
return timezone(timedelta(hours=delta_h, minutes=delta_m))
# in format 'Asia/Shanghai'
try:
return pytz.timezone(tz_str)
except pytz.exceptions.UnknownTimeZoneError:
return None | [
"def",
"timezone_from_str",
"(",
"tz_str",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'UTC([+|-]\\d{1,2}):(\\d{2})'",
",",
"tz_str",
")",
"if",
"m",
":",
"# in format 'UTC±[hh]:[mm]'",
"delta_h",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
... | Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo) | [
"Convert",
"a",
"timezone",
"string",
"to",
"a",
"timezone",
"object",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L60-L78 |
10,771 | veripress/veripress | veripress/helpers.py | traverse_directory | def traverse_directory(dir_path, yield_dir=False):
"""
Traverse through a directory recursively.
:param dir_path: directory path
:param yield_dir: yield subdirectory or not
:return: a generator
"""
if not os.path.isdir(dir_path):
return
for item in os.listdir(dir_path):
new_path = os.path.join(dir_path, item)
if os.path.isdir(new_path):
if yield_dir:
yield new_path + os.path.sep
yield from traverse_directory(new_path, yield_dir)
else:
yield new_path | python | def traverse_directory(dir_path, yield_dir=False):
if not os.path.isdir(dir_path):
return
for item in os.listdir(dir_path):
new_path = os.path.join(dir_path, item)
if os.path.isdir(new_path):
if yield_dir:
yield new_path + os.path.sep
yield from traverse_directory(new_path, yield_dir)
else:
yield new_path | [
"def",
"traverse_directory",
"(",
"dir_path",
",",
"yield_dir",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_path",
")",
":",
"return",
"for",
"item",
"in",
"os",
".",
"listdir",
"(",
"dir_path",
")",
":",
"new_path",... | Traverse through a directory recursively.
:param dir_path: directory path
:param yield_dir: yield subdirectory or not
:return: a generator | [
"Traverse",
"through",
"a",
"directory",
"recursively",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L143-L161 |
10,772 | veripress/veripress | veripress/helpers.py | parse_toc | def parse_toc(html_content):
"""
Parse TOC of HTML content if the SHOW_TOC config is true.
:param html_content: raw HTML content
:return: tuple(processed HTML, toc list, toc HTML unordered list)
"""
from flask import current_app
from veripress.model.toc import HtmlTocParser
if current_app.config['SHOW_TOC']:
toc_parser = HtmlTocParser()
toc_parser.feed(html_content)
toc_html = toc_parser.toc_html(
depth=current_app.config['TOC_DEPTH'],
lowest_level=current_app.config['TOC_LOWEST_LEVEL'])
toc = toc_parser.toc(
depth=current_app.config['TOC_DEPTH'],
lowest_level=current_app.config['TOC_LOWEST_LEVEL'])
return toc_parser.html, toc, toc_html
else:
return html_content, None, None | python | def parse_toc(html_content):
from flask import current_app
from veripress.model.toc import HtmlTocParser
if current_app.config['SHOW_TOC']:
toc_parser = HtmlTocParser()
toc_parser.feed(html_content)
toc_html = toc_parser.toc_html(
depth=current_app.config['TOC_DEPTH'],
lowest_level=current_app.config['TOC_LOWEST_LEVEL'])
toc = toc_parser.toc(
depth=current_app.config['TOC_DEPTH'],
lowest_level=current_app.config['TOC_LOWEST_LEVEL'])
return toc_parser.html, toc, toc_html
else:
return html_content, None, None | [
"def",
"parse_toc",
"(",
"html_content",
")",
":",
"from",
"flask",
"import",
"current_app",
"from",
"veripress",
".",
"model",
".",
"toc",
"import",
"HtmlTocParser",
"if",
"current_app",
".",
"config",
"[",
"'SHOW_TOC'",
"]",
":",
"toc_parser",
"=",
"HtmlTocP... | Parse TOC of HTML content if the SHOW_TOC config is true.
:param html_content: raw HTML content
:return: tuple(processed HTML, toc list, toc HTML unordered list) | [
"Parse",
"TOC",
"of",
"HTML",
"content",
"if",
"the",
"SHOW_TOC",
"config",
"is",
"true",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L164-L185 |
10,773 | elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.index | def index(self, row, column, parent):
""" Returns the index of the item in the model specified by the given row, column and parent index.
row, column == int, parent == QModelIndex
"""
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.root
else:
# So, here we go from QModelIndex to the actual object .. ?
parentItem = parent.internalPointer()
# the only place where a child item is queried
childItem = parentItem.getChild(row)
if childItem:
# return self.createIndex(row, column)
return self.createIndex(row, column, childItem)
"""
# .. that one does not work for PySide 5.12+
TypeError: 'PySide2.QtCore.QAbstractItemModel.createIndex' called with wrong argument types:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, ServerListItem)
Supported signatures:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, quintptr = 0)
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, void = nullptr)
"""
else:
return QtCore.QModelIndex() | python | def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.root
else:
# So, here we go from QModelIndex to the actual object .. ?
parentItem = parent.internalPointer()
# the only place where a child item is queried
childItem = parentItem.getChild(row)
if childItem:
# return self.createIndex(row, column)
return self.createIndex(row, column, childItem)
"""
# .. that one does not work for PySide 5.12+
TypeError: 'PySide2.QtCore.QAbstractItemModel.createIndex' called with wrong argument types:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, ServerListItem)
Supported signatures:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, quintptr = 0)
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, void = nullptr)
"""
else:
return QtCore.QModelIndex() | [
"def",
"index",
"(",
"self",
",",
"row",
",",
"column",
",",
"parent",
")",
":",
"if",
"not",
"self",
".",
"hasIndex",
"(",
"row",
",",
"column",
",",
"parent",
")",
":",
"return",
"QtCore",
".",
"QModelIndex",
"(",
")",
"if",
"not",
"parent",
".",... | Returns the index of the item in the model specified by the given row, column and parent index.
row, column == int, parent == QModelIndex | [
"Returns",
"the",
"index",
"of",
"the",
"item",
"in",
"the",
"model",
"specified",
"by",
"the",
"given",
"row",
"column",
"and",
"parent",
"index",
".",
"row",
"column",
"==",
"int",
"parent",
"==",
"QModelIndex"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L52-L80 |
10,774 | elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.columnCount | def columnCount(self, parent):
""" Returns the number of columns for the children of the given parent.
"""
# print("columnCount:",self)
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.root.columnCount() | python | def columnCount(self, parent):
# print("columnCount:",self)
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.root.columnCount() | [
"def",
"columnCount",
"(",
"self",
",",
"parent",
")",
":",
"# print(\"columnCount:\",self)",
"if",
"parent",
".",
"isValid",
"(",
")",
":",
"return",
"parent",
".",
"internalPointer",
"(",
")",
".",
"columnCount",
"(",
")",
"else",
":",
"return",
"self",
... | Returns the number of columns for the children of the given parent. | [
"Returns",
"the",
"number",
"of",
"columns",
"for",
"the",
"children",
"of",
"the",
"given",
"parent",
"."
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L97-L104 |
10,775 | Jaymon/pout | pout/interface.py | BaseInterface._str | def _str(self, name, val):
'''
return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
return -- string
'''
s = ''
v = Value(val)
if name:
logger.debug("{} is type {}".format(name, v.typename))
try:
count = len(val)
s = "{} ({}) = {}".format(name, count, v.string_value())
except (TypeError, KeyError, AttributeError) as e:
logger.info(e, exc_info=True)
s = "{} = {}".format(name, v.string_value())
else:
s = v.string_value()
return s | python | def _str(self, name, val):
'''
return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
return -- string
'''
s = ''
v = Value(val)
if name:
logger.debug("{} is type {}".format(name, v.typename))
try:
count = len(val)
s = "{} ({}) = {}".format(name, count, v.string_value())
except (TypeError, KeyError, AttributeError) as e:
logger.info(e, exc_info=True)
s = "{} = {}".format(name, v.string_value())
else:
s = v.string_value()
return s | [
"def",
"_str",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"s",
"=",
"''",
"v",
"=",
"Value",
"(",
"val",
")",
"if",
"name",
":",
"logger",
".",
"debug",
"(",
"\"{} is type {}\"",
".",
"format",
"(",
"name",
",",
"v",
".",
"typename",
")",
... | return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
return -- string | [
"return",
"a",
"string",
"version",
"of",
"name",
"=",
"val",
"that",
"can",
"be",
"printed"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L106-L134 |
10,776 | Jaymon/pout | pout/interface.py | LoggingInterface.loggers | def loggers(self):
"""Return all the loggers that should be activated"""
ret = []
if self.logger_name:
if isinstance(self.logger_name, logging.Logger):
ret.append((self.logger_name.name, self.logger_name))
else:
ret.append((self.logger_name, logging.getLogger(self.logger_name)))
else:
ret = list(logging.Logger.manager.loggerDict.items())
ret.append(("root", logging.getLogger()))
return ret | python | def loggers(self):
ret = []
if self.logger_name:
if isinstance(self.logger_name, logging.Logger):
ret.append((self.logger_name.name, self.logger_name))
else:
ret.append((self.logger_name, logging.getLogger(self.logger_name)))
else:
ret = list(logging.Logger.manager.loggerDict.items())
ret.append(("root", logging.getLogger()))
return ret | [
"def",
"loggers",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"self",
".",
"logger_name",
":",
"if",
"isinstance",
"(",
"self",
".",
"logger_name",
",",
"logging",
".",
"Logger",
")",
":",
"ret",
".",
"append",
"(",
"(",
"self",
".",
"logger... | Return all the loggers that should be activated | [
"Return",
"all",
"the",
"loggers",
"that",
"should",
"be",
"activated"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L516-L528 |
10,777 | Jaymon/pout | pout/interface.py | TraceInterface._get_backtrace | def _get_backtrace(self, frames, inspect_packages=False, depth=0):
'''
get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
return -- list -- each line will be a nicely formatted entry of the backtrace
'''
calls = []
#count = 1
#for count, f in enumerate(frames[1:], 1):
for count, f in enumerate(frames, 1):
#prev_f = frames[i]
#called_module = inspect.getmodule(prev_f[0]).__name__
#called_func = prev_f[3]
call = self.call_class(f)
s = self._get_call_summary(call, inspect_packages=inspect_packages, index=count)
calls.append(s)
#count += 1
if depth and (count > depth):
break
# reverse the order on return so most recent is on the bottom
return calls[::-1] | python | def _get_backtrace(self, frames, inspect_packages=False, depth=0):
'''
get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
return -- list -- each line will be a nicely formatted entry of the backtrace
'''
calls = []
#count = 1
#for count, f in enumerate(frames[1:], 1):
for count, f in enumerate(frames, 1):
#prev_f = frames[i]
#called_module = inspect.getmodule(prev_f[0]).__name__
#called_func = prev_f[3]
call = self.call_class(f)
s = self._get_call_summary(call, inspect_packages=inspect_packages, index=count)
calls.append(s)
#count += 1
if depth and (count > depth):
break
# reverse the order on return so most recent is on the bottom
return calls[::-1] | [
"def",
"_get_backtrace",
"(",
"self",
",",
"frames",
",",
"inspect_packages",
"=",
"False",
",",
"depth",
"=",
"0",
")",
":",
"calls",
"=",
"[",
"]",
"#count = 1",
"#for count, f in enumerate(frames[1:], 1):",
"for",
"count",
",",
"f",
"in",
"enumerate",
"(",
... | get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
return -- list -- each line will be a nicely formatted entry of the backtrace | [
"get",
"a",
"nicely",
"formatted",
"backtrace"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L587-L620 |
10,778 | Jaymon/pout | pout/interface.py | TraceInterface._get_call_summary | def _get_call_summary(self, call, index=0, inspect_packages=True):
'''
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- integer -- set to something above 0 if you would like the summary to be numbered
inspect_packages -- boolean -- set to True to get the full format even for system frames
return -- string
'''
call_info = call.info
inspect_regex = re.compile(r'[\\\\/]python\d(?:\.\d+)?', re.I)
# truncate the filepath if it is super long
f = call_info['file']
if len(f) > 75:
f = "{}...{}".format(f[0:30], f[-45:])
if inspect_packages or not inspect_regex.search(call_info['file']):
s = "{}:{}\n\n{}\n\n".format(
f,
call_info['line'],
String(call_info['call']).indent(1)
)
else:
s = "{}:{}\n".format(
f,
call_info['line']
)
if index > 0:
s = "{:02d} - {}".format(index, s)
return s | python | def _get_call_summary(self, call, index=0, inspect_packages=True):
'''
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- integer -- set to something above 0 if you would like the summary to be numbered
inspect_packages -- boolean -- set to True to get the full format even for system frames
return -- string
'''
call_info = call.info
inspect_regex = re.compile(r'[\\\\/]python\d(?:\.\d+)?', re.I)
# truncate the filepath if it is super long
f = call_info['file']
if len(f) > 75:
f = "{}...{}".format(f[0:30], f[-45:])
if inspect_packages or not inspect_regex.search(call_info['file']):
s = "{}:{}\n\n{}\n\n".format(
f,
call_info['line'],
String(call_info['call']).indent(1)
)
else:
s = "{}:{}\n".format(
f,
call_info['line']
)
if index > 0:
s = "{:02d} - {}".format(index, s)
return s | [
"def",
"_get_call_summary",
"(",
"self",
",",
"call",
",",
"index",
"=",
"0",
",",
"inspect_packages",
"=",
"True",
")",
":",
"call_info",
"=",
"call",
".",
"info",
"inspect_regex",
"=",
"re",
".",
"compile",
"(",
"r'[\\\\\\\\/]python\\d(?:\\.\\d+)?'",
",",
... | get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- integer -- set to something above 0 if you would like the summary to be numbered
inspect_packages -- boolean -- set to True to get the full format even for system frames
return -- string | [
"get",
"a",
"call",
"summary"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L622-L664 |
10,779 | veripress/veripress | veripress/model/parsers.py | parser | def parser(format_name, ext_names=None):
"""
Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name
"""
def decorator(cls):
format_name_lower = format_name.lower()
if ext_names is None:
_ext_format_mapping[format_name_lower] = format_name_lower
else:
for ext in to_list(ext_names):
_ext_format_mapping[ext.lower()] = format_name_lower
_format_parser_mapping[format_name_lower] = cls()
return cls
return decorator | python | def parser(format_name, ext_names=None):
def decorator(cls):
format_name_lower = format_name.lower()
if ext_names is None:
_ext_format_mapping[format_name_lower] = format_name_lower
else:
for ext in to_list(ext_names):
_ext_format_mapping[ext.lower()] = format_name_lower
_format_parser_mapping[format_name_lower] = cls()
return cls
return decorator | [
"def",
"parser",
"(",
"format_name",
",",
"ext_names",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"format_name_lower",
"=",
"format_name",
".",
"lower",
"(",
")",
"if",
"ext_names",
"is",
"None",
":",
"_ext_format_mapping",
"[",
"form... | Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name | [
"Decorate",
"a",
"parser",
"class",
"to",
"register",
"it",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/parsers.py#L100-L118 |
10,780 | veripress/veripress | veripress/model/parsers.py | Parser.parse_preview | def parse_preview(self, raw_content):
"""
Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:param raw_content: raw content
:return: tuple(parsed string, whether there is more content or not)
"""
if self._read_more_exp is None:
return self.parse_whole(raw_content), False
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
has_more_content = True
result = sp[0].rstrip()
else:
has_more_content = False
result = raw_content
# since the preview part contains no read_more_sep,
# we can safely use the parse_whole method
return self.parse_whole(result), has_more_content | python | def parse_preview(self, raw_content):
if self._read_more_exp is None:
return self.parse_whole(raw_content), False
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
has_more_content = True
result = sp[0].rstrip()
else:
has_more_content = False
result = raw_content
# since the preview part contains no read_more_sep,
# we can safely use the parse_whole method
return self.parse_whole(result), has_more_content | [
"def",
"parse_preview",
"(",
"self",
",",
"raw_content",
")",
":",
"if",
"self",
".",
"_read_more_exp",
"is",
"None",
":",
"return",
"self",
".",
"parse_whole",
"(",
"raw_content",
")",
",",
"False",
"sp",
"=",
"self",
".",
"_read_more_exp",
".",
"split",
... | Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:param raw_content: raw content
:return: tuple(parsed string, whether there is more content or not) | [
"Parse",
"the",
"preview",
"part",
"of",
"the",
"content",
"and",
"return",
"the",
"parsed",
"string",
"and",
"whether",
"there",
"is",
"more",
"content",
"or",
"not",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/parsers.py#L26-L49 |
10,781 | veripress/veripress | veripress/model/parsers.py | Parser.remove_read_more_sep | def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
"""
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
result = '\n\n'.join((sp[0].rstrip(), sp[1].lstrip()))
else:
result = raw_content
return result | python | def remove_read_more_sep(self, raw_content):
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
result = '\n\n'.join((sp[0].rstrip(), sp[1].lstrip()))
else:
result = raw_content
return result | [
"def",
"remove_read_more_sep",
"(",
"self",
",",
"raw_content",
")",
":",
"if",
"self",
".",
"_read_more_exp",
"is",
"None",
":",
"return",
"raw_content",
"sp",
"=",
"self",
".",
"_read_more_exp",
".",
"split",
"(",
"raw_content",
",",
"maxsplit",
"=",
"1",
... | Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content. | [
"Removes",
"the",
"first",
"read_more_sep",
"that",
"occurs",
"in",
"raw_content",
".",
"Subclasses",
"should",
"call",
"this",
"method",
"to",
"preprocess",
"raw_content",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/parsers.py#L58-L71 |
10,782 | Jaymon/pout | pout/__init__.py | tofile | def tofile(path=""):
"""Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the file you want to write to
"""
if not path:
path = os.path.join(os.getcwd(), "{}.txt".format(__name__))
global stream
orig_stream = stream
try:
stream = FileStream(path)
yield stream
finally:
stream = orig_stream | python | def tofile(path=""):
if not path:
path = os.path.join(os.getcwd(), "{}.txt".format(__name__))
global stream
orig_stream = stream
try:
stream = FileStream(path)
yield stream
finally:
stream = orig_stream | [
"def",
"tofile",
"(",
"path",
"=",
"\"\"",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"\"{}.txt\"",
".",
"format",
"(",
"__name__",
")",
")",
"global",
"stream",
"orig... | Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the file you want to write to | [
"Instead",
"of",
"printing",
"to",
"a",
"screen",
"print",
"to",
"a",
"file"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L97-L120 |
10,783 | Jaymon/pout | pout/__init__.py | v | def v(*args, **kwargs):
'''
print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
""" prints out:
foo = 1
bar =
[
0: 1,
1: 2,
2: 3
]
(/file:line)
"""
*args -- list -- the variables you want to see pretty printed for humans
'''
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance() | python | def v(*args, **kwargs):
'''
print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
""" prints out:
foo = 1
bar =
[
0: 1,
1: 2,
2: 3
]
(/file:line)
"""
*args -- list -- the variables you want to see pretty printed for humans
'''
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance() | [
"def",
"v",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"raise",
"ValueError",
"(",
"\"you didn't pass any arguments to print out\"",
")",
"with",
"Reflect",
".",
"context",
"(",
"args",
",",
"*",
"*",
"kwargs",
")",
"a... | print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
""" prints out:
foo = 1
bar =
[
0: 1,
1: 2,
2: 3
]
(/file:line)
"""
*args -- list -- the variables you want to see pretty printed for humans | [
"print",
"the",
"name",
"=",
"values",
"of",
"any",
"passed",
"in",
"variables"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L124-L155 |
10,784 | Jaymon/pout | pout/__init__.py | vs | def vs(*args, **kwargs):
"""
exactly like v, but doesn't print variable names or file positions
.. seealso:: ss()
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance.writeline(instance.value()) | python | def vs(*args, **kwargs):
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance.writeline(instance.value()) | [
"def",
"vs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"raise",
"ValueError",
"(",
"\"you didn't pass any arguments to print out\"",
")",
"with",
"Reflect",
".",
"context",
"(",
"args",
",",
"*",
"*",
"kwargs",
")",
"... | exactly like v, but doesn't print variable names or file positions
.. seealso:: ss() | [
"exactly",
"like",
"v",
"but",
"doesn",
"t",
"print",
"variable",
"names",
"or",
"file",
"positions"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L158-L169 |
10,785 | Jaymon/pout | pout/__init__.py | h | def h(count=0, **kwargs):
'''
prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here"
'''
with Reflect.context(**kwargs) as r:
kwargs["count"] = count
instance = H_CLASS(r, stream, **kwargs)
instance() | python | def h(count=0, **kwargs):
'''
prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here"
'''
with Reflect.context(**kwargs) as r:
kwargs["count"] = count
instance = H_CLASS(r, stream, **kwargs)
instance() | [
"def",
"h",
"(",
"count",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Reflect",
".",
"context",
"(",
"*",
"*",
"kwargs",
")",
"as",
"r",
":",
"kwargs",
"[",
"\"count\"",
"]",
"=",
"count",
"instance",
"=",
"H_CLASS",
"(",
"r",
",",
"s... | prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here" | [
"prints",
"here",
"count"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L257-L270 |
10,786 | Jaymon/pout | pout/__init__.py | b | def b(*args, **kwargs):
'''
create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = B_CLASS(r, stream, **kwargs)
instance() | python | def b(*args, **kwargs):
'''
create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = B_CLASS(r, stream, **kwargs)
instance() | [
"def",
"b",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Reflect",
".",
"context",
"(",
"*",
"*",
"kwargs",
")",
"as",
"r",
":",
"kwargs",
"[",
"\"args\"",
"]",
"=",
"args",
"instance",
"=",
"B_CLASS",
"(",
"r",
",",
"stream",
... | create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep | [
"create",
"a",
"big",
"text",
"break",
"you",
"just",
"kind",
"of",
"have",
"to",
"run",
"it",
"and",
"see"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L273-L286 |
10,787 | Jaymon/pout | pout/__init__.py | c | def c(*args, **kwargs):
'''
kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = C_CLASS(r, stream, **kwargs)
instance() | python | def c(*args, **kwargs):
'''
kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = C_CLASS(r, stream, **kwargs)
instance() | [
"def",
"c",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Reflect",
".",
"context",
"(",
"*",
"*",
"kwargs",
")",
"as",
"r",
":",
"kwargs",
"[",
"\"args\"",
"]",
"=",
"args",
"instance",
"=",
"C_CLASS",
"(",
"r",
",",
"stream",
... | kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump | [
"kind",
"of",
"like",
"od",
"-",
"c",
"on",
"the",
"command",
"line",
"basically",
"it",
"dumps",
"each",
"character",
"and",
"info",
"about",
"that",
"char"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L289-L301 |
10,788 | Jaymon/pout | pout/__init__.py | m | def m(name='', **kwargs):
"""
Print out memory usage at this point in time
http://docs.python.org/2/library/resource.html
http://stackoverflow.com/a/15448600/5006
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended
"""
with Reflect.context(**kwargs) as r:
kwargs["name"] = name
instance = M_CLASS(r, stream, **kwargs)
instance() | python | def m(name='', **kwargs):
with Reflect.context(**kwargs) as r:
kwargs["name"] = name
instance = M_CLASS(r, stream, **kwargs)
instance() | [
"def",
"m",
"(",
"name",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Reflect",
".",
"context",
"(",
"*",
"*",
"kwargs",
")",
"as",
"r",
":",
"kwargs",
"[",
"\"name\"",
"]",
"=",
"name",
"instance",
"=",
"M_CLASS",
"(",
"r",
",",
"str... | Print out memory usage at this point in time
http://docs.python.org/2/library/resource.html
http://stackoverflow.com/a/15448600/5006
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended | [
"Print",
"out",
"memory",
"usage",
"at",
"this",
"point",
"in",
"time"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L320-L331 |
10,789 | Jaymon/pout | pout/__init__.py | p | def p(name="", **kwargs):
'''
really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast your code is, super handy, not super accurate
since -- 2013-5-9
example --
p("starting profile")
time.sleep(1)
p() # stop the "starting profile" session
# you can go N levels deep
p("one")
p("two")
time.sleep(0.5)
p() # stop profiling of "two"
time.sleep(0.5)
p() # stop profiling of "one"
with pout.p("three"):
time.sleep(0.5)
name -- string -- pass this in to start a profiling session
return -- context manager
'''
with Reflect.context(**kwargs) as r:
if name:
instance = P_CLASS(r, stream, name, **kwargs)
else:
instance = P_CLASS.pop(r)
instance()
return instance | python | def p(name="", **kwargs):
'''
really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast your code is, super handy, not super accurate
since -- 2013-5-9
example --
p("starting profile")
time.sleep(1)
p() # stop the "starting profile" session
# you can go N levels deep
p("one")
p("two")
time.sleep(0.5)
p() # stop profiling of "two"
time.sleep(0.5)
p() # stop profiling of "one"
with pout.p("three"):
time.sleep(0.5)
name -- string -- pass this in to start a profiling session
return -- context manager
'''
with Reflect.context(**kwargs) as r:
if name:
instance = P_CLASS(r, stream, name, **kwargs)
else:
instance = P_CLASS.pop(r)
instance()
return instance | [
"def",
"p",
"(",
"name",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"Reflect",
".",
"context",
"(",
"*",
"*",
"kwargs",
")",
"as",
"r",
":",
"if",
"name",
":",
"instance",
"=",
"P_CLASS",
"(",
"r",
",",
"stream",
",",
"name",
",",
... | really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast your code is, super handy, not super accurate
since -- 2013-5-9
example --
p("starting profile")
time.sleep(1)
p() # stop the "starting profile" session
# you can go N levels deep
p("one")
p("two")
time.sleep(0.5)
p() # stop profiling of "two"
time.sleep(0.5)
p() # stop profiling of "one"
with pout.p("three"):
time.sleep(0.5)
name -- string -- pass this in to start a profiling session
return -- context manager | [
"really",
"quick",
"and",
"dirty",
"profiling"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L334-L371 |
10,790 | Jaymon/pout | pout/__init__.py | t | def t(inspect_packages=False, depth=0, **kwargs):
'''
print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
'''
#frame = inspect.currentframe()
try:
frames = inspect.stack()
kwargs["frames"] = frames
kwargs["inspect_packages"] = inspect_packages
kwargs["depth"] = depth
with Reflect.context(**kwargs) as r:
instance = T_CLASS(r, stream, **kwargs)
instance()
finally:
del frames | python | def t(inspect_packages=False, depth=0, **kwargs):
'''
print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
'''
#frame = inspect.currentframe()
try:
frames = inspect.stack()
kwargs["frames"] = frames
kwargs["inspect_packages"] = inspect_packages
kwargs["depth"] = depth
with Reflect.context(**kwargs) as r:
instance = T_CLASS(r, stream, **kwargs)
instance()
finally:
del frames | [
"def",
"t",
"(",
"inspect_packages",
"=",
"False",
",",
"depth",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"#frame = inspect.currentframe()",
"try",
":",
"frames",
"=",
"inspect",
".",
"stack",
"(",
")",
"kwargs",
"[",
"\"frames\"",
"]",
"=",
"frames"... | print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack) | [
"print",
"a",
"backtrace"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L420-L447 |
10,791 | Jaymon/pout | pout/__init__.py | inject | def inject():
"""Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable
"""
try:
from .compat import builtins
module = sys.modules[__name__]
setattr(builtins, __name__, module)
#builtins.pout = pout
except ImportError:
pass | python | def inject():
try:
from .compat import builtins
module = sys.modules[__name__]
setattr(builtins, __name__, module)
#builtins.pout = pout
except ImportError:
pass | [
"def",
"inject",
"(",
")",
":",
"try",
":",
"from",
".",
"compat",
"import",
"builtins",
"module",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"setattr",
"(",
"builtins",
",",
"__name__",
",",
"module",
")",
"#builtins.pout = pout",
"except",
"Import... | Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable | [
"Injects",
"pout",
"into",
"the",
"builtins",
"module",
"so",
"it",
"can",
"be",
"called",
"from",
"anywhere",
"without",
"having",
"to",
"be",
"explicitely",
"imported",
"this",
"is",
"really",
"just",
"for",
"convenience",
"when",
"debugging"
] | fa71b64384ddeb3b538855ed93e785d9985aad05 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L450-L465 |
10,792 | veripress/veripress | veripress/__init__.py | create_app | def create_app(config_filename, instance_path=None):
"""
Factory function to create Flask application object.
:param config_filename: absolute or relative filename of the config file
:param instance_path: instance path to initialize or run a VeriPress app
:return: a Flask app object
"""
app_ = CustomFlask(
__name__,
instance_path=instance_path or os.environ.get(
'VERIPRESS_INSTANCE_PATH') or os.getcwd(),
instance_relative_config=True
)
app_.config.update(dict(STORAGE_TYPE='file',
THEME='default',
CACHE_TYPE='simple',
MODE='view-only',
ENTRIES_PER_PAGE=5,
FEED_COUNT=10,
SHOW_TOC=True,
TOC_DEPTH=3,
TOC_LOWEST_LEVEL=3,
ALLOW_SEARCH_PAGES=True,
PAGE_SOURCE_ACCESSIBLE=False))
app_.config.from_pyfile(config_filename, silent=True)
theme_folder = os.path.join(app_.instance_path,
'themes', app_.config['THEME'])
# use templates in the selected theme's folder
app_.template_folder = os.path.join(theme_folder, 'templates')
# use static files in the selected theme's folder
app_.theme_static_folder = os.path.join(theme_folder, 'static')
# global static folder
app_.static_folder = os.path.join(app_.instance_path, 'static')
return app_ | python | def create_app(config_filename, instance_path=None):
app_ = CustomFlask(
__name__,
instance_path=instance_path or os.environ.get(
'VERIPRESS_INSTANCE_PATH') or os.getcwd(),
instance_relative_config=True
)
app_.config.update(dict(STORAGE_TYPE='file',
THEME='default',
CACHE_TYPE='simple',
MODE='view-only',
ENTRIES_PER_PAGE=5,
FEED_COUNT=10,
SHOW_TOC=True,
TOC_DEPTH=3,
TOC_LOWEST_LEVEL=3,
ALLOW_SEARCH_PAGES=True,
PAGE_SOURCE_ACCESSIBLE=False))
app_.config.from_pyfile(config_filename, silent=True)
theme_folder = os.path.join(app_.instance_path,
'themes', app_.config['THEME'])
# use templates in the selected theme's folder
app_.template_folder = os.path.join(theme_folder, 'templates')
# use static files in the selected theme's folder
app_.theme_static_folder = os.path.join(theme_folder, 'static')
# global static folder
app_.static_folder = os.path.join(app_.instance_path, 'static')
return app_ | [
"def",
"create_app",
"(",
"config_filename",
",",
"instance_path",
"=",
"None",
")",
":",
"app_",
"=",
"CustomFlask",
"(",
"__name__",
",",
"instance_path",
"=",
"instance_path",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'VERIPRESS_INSTANCE_PATH'",
")",
"o... | Factory function to create Flask application object.
:param config_filename: absolute or relative filename of the config file
:param instance_path: instance path to initialize or run a VeriPress app
:return: a Flask app object | [
"Factory",
"function",
"to",
"create",
"Flask",
"application",
"object",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/__init__.py#L30-L66 |
10,793 | veripress/veripress | veripress/__init__.py | CustomFlask.send_static_file | def send_static_file(self, filename):
"""
Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object
"""
if self.config['MODE'] == 'api-only':
# if 'api-only' mode is set, we should not send static files
abort(404)
theme_static_folder = getattr(self, 'theme_static_folder', None)
if theme_static_folder:
try:
return send_from_directory(theme_static_folder, filename)
except NotFound:
pass
return super(CustomFlask, self).send_static_file(filename) | python | def send_static_file(self, filename):
if self.config['MODE'] == 'api-only':
# if 'api-only' mode is set, we should not send static files
abort(404)
theme_static_folder = getattr(self, 'theme_static_folder', None)
if theme_static_folder:
try:
return send_from_directory(theme_static_folder, filename)
except NotFound:
pass
return super(CustomFlask, self).send_static_file(filename) | [
"def",
"send_static_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"config",
"[",
"'MODE'",
"]",
"==",
"'api-only'",
":",
"# if 'api-only' mode is set, we should not send static files",
"abort",
"(",
"404",
")",
"theme_static_folder",
"=",
"getatt... | Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object | [
"Send",
"static",
"files",
"from",
"the",
"static",
"folder",
"in",
"the",
"current",
"selected",
"theme",
"prior",
"to",
"the",
"global",
"static",
"folder",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/__init__.py#L9-L27 |
10,794 | elsampsa/valkka-live | valkka/live/container/video.py | VideoContainer.mouseGestureHandler | def mouseGestureHandler(self, info):
"""This is the callback for MouseClickContext. Passed to VideoWidget as a parameter
"""
print(self.pre, ": mouseGestureHandler: ")
# *** single click events ***
if (info.fsingle):
print(self.pre, ": mouseGestureHandler: single click")
if (info.button == QtCore.Qt.LeftButton):
print(self.pre, ": mouseGestureHandler: Left button clicked")
elif (info.button == QtCore.Qt.RightButton):
print(self.pre, ": mouseGestureHandler: Right button clicked")
self.handle_right_single_click(info)
# *** double click events ***
elif (info.fdouble):
if (info.button == QtCore.Qt.LeftButton):
print(
self.pre,
": mouseGestureHandler: Left button double-clicked")
self.handle_left_double_click(info)
elif (info.button == QtCore.Qt.RightButton):
print(
self.pre,
": mouseGestureHandler: Right button double-clicked") | python | def mouseGestureHandler(self, info):
print(self.pre, ": mouseGestureHandler: ")
# *** single click events ***
if (info.fsingle):
print(self.pre, ": mouseGestureHandler: single click")
if (info.button == QtCore.Qt.LeftButton):
print(self.pre, ": mouseGestureHandler: Left button clicked")
elif (info.button == QtCore.Qt.RightButton):
print(self.pre, ": mouseGestureHandler: Right button clicked")
self.handle_right_single_click(info)
# *** double click events ***
elif (info.fdouble):
if (info.button == QtCore.Qt.LeftButton):
print(
self.pre,
": mouseGestureHandler: Left button double-clicked")
self.handle_left_double_click(info)
elif (info.button == QtCore.Qt.RightButton):
print(
self.pre,
": mouseGestureHandler: Right button double-clicked") | [
"def",
"mouseGestureHandler",
"(",
"self",
",",
"info",
")",
":",
"print",
"(",
"self",
".",
"pre",
",",
"\": mouseGestureHandler: \"",
")",
"# *** single click events ***",
"if",
"(",
"info",
".",
"fsingle",
")",
":",
"print",
"(",
"self",
".",
"pre",
",",
... | This is the callback for MouseClickContext. Passed to VideoWidget as a parameter | [
"This",
"is",
"the",
"callback",
"for",
"MouseClickContext",
".",
"Passed",
"to",
"VideoWidget",
"as",
"a",
"parameter"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/video.py#L283-L305 |
10,795 | elsampsa/valkka-live | valkka/live/container/video.py | VideoContainer.handle_left_double_click | def handle_left_double_click(self, info):
"""Whatever we want to do, when the VideoWidget has been double-clicked with the left button
"""
if (self.double_click_focus == False): # turn focus on
print(self.pre, "handle_left_double_click: focus on")
self.cb_focus()
else: # turn focus off
print(self.pre, "handle_left_double_click: focus off")
self.cb_unfocus()
self.double_click_focus = not(
self.double_click_focus) | python | def handle_left_double_click(self, info):
if (self.double_click_focus == False): # turn focus on
print(self.pre, "handle_left_double_click: focus on")
self.cb_focus()
else: # turn focus off
print(self.pre, "handle_left_double_click: focus off")
self.cb_unfocus()
self.double_click_focus = not(
self.double_click_focus) | [
"def",
"handle_left_double_click",
"(",
"self",
",",
"info",
")",
":",
"if",
"(",
"self",
".",
"double_click_focus",
"==",
"False",
")",
":",
"# turn focus on",
"print",
"(",
"self",
".",
"pre",
",",
"\"handle_left_double_click: focus on\"",
")",
"self",
".",
... | Whatever we want to do, when the VideoWidget has been double-clicked with the left button | [
"Whatever",
"we",
"want",
"to",
"do",
"when",
"the",
"VideoWidget",
"has",
"been",
"double",
"-",
"clicked",
"with",
"the",
"left",
"button"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/video.py#L309-L319 |
10,796 | veripress/veripress | veripress/model/__init__.py | get_storage | def get_storage():
"""
Get storage object of current app context,
will create a new one if not exists.
:return: a storage object
:raise: ConfigurationError: storage type in config is not supported
"""
storage_ = getattr(g, '_storage', None)
if storage_ is None:
storage_type = current_app.config['STORAGE_TYPE']
if storage_type == 'file':
storage_ = g._storage = storages.FileStorage()
else:
raise ConfigurationError(
'Storage type "{}" is not supported.'.format(storage_type))
return storage_ | python | def get_storage():
storage_ = getattr(g, '_storage', None)
if storage_ is None:
storage_type = current_app.config['STORAGE_TYPE']
if storage_type == 'file':
storage_ = g._storage = storages.FileStorage()
else:
raise ConfigurationError(
'Storage type "{}" is not supported.'.format(storage_type))
return storage_ | [
"def",
"get_storage",
"(",
")",
":",
"storage_",
"=",
"getattr",
"(",
"g",
",",
"'_storage'",
",",
"None",
")",
"if",
"storage_",
"is",
"None",
":",
"storage_type",
"=",
"current_app",
".",
"config",
"[",
"'STORAGE_TYPE'",
"]",
"if",
"storage_type",
"==",
... | Get storage object of current app context,
will create a new one if not exists.
:return: a storage object
:raise: ConfigurationError: storage type in config is not supported | [
"Get",
"storage",
"object",
"of",
"current",
"app",
"context",
"will",
"create",
"a",
"new",
"one",
"if",
"not",
"exists",
"."
] | 9e3df3a10eb1db32da596bf52118fe6acbe4b14a | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/__init__.py#L11-L27 |
10,797 | elsampsa/valkka-live | valkka/live/form.py | SlotFormSet.chooseForm_slot | def chooseForm_slot(self, element, element_old):
"""Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List classes, widget attribute's, currentItemChanged method (List.widget is QListWidget that has currentItemChanged slot), so the element and element_old parameters are QListWidgetItem instances with extra attributes "_id" and "_classname" attached.
Queries the database for element._id
"""
self.current_slot = None
if (verbose):
# enable this if you're unsure what's coming here..
print(self.pre, "chooseForm_slot :", element)
if (isinstance(element, type(None))):
self.current_row = None
self.element = None
else:
# print(self.pre,"chooseForm_slot :",element)
assert(hasattr(element, "_id"))
assert(hasattr(element, "classname"))
try:
self.current_row = self.row_instance_by_name[element.classname]
except KeyError:
print(
self.pre,
"chooseForm_slot : no such classname for this FormSet : ",
element.classname)
self.current_row = None
self.element = None
else:
self.resetForm()
self.current_row.get(self.collection, element._id)
self.element = element
self.current_slot = self.current_row.get_column_value("slot")
self.showCurrent() | python | def chooseForm_slot(self, element, element_old):
self.current_slot = None
if (verbose):
# enable this if you're unsure what's coming here..
print(self.pre, "chooseForm_slot :", element)
if (isinstance(element, type(None))):
self.current_row = None
self.element = None
else:
# print(self.pre,"chooseForm_slot :",element)
assert(hasattr(element, "_id"))
assert(hasattr(element, "classname"))
try:
self.current_row = self.row_instance_by_name[element.classname]
except KeyError:
print(
self.pre,
"chooseForm_slot : no such classname for this FormSet : ",
element.classname)
self.current_row = None
self.element = None
else:
self.resetForm()
self.current_row.get(self.collection, element._id)
self.element = element
self.current_slot = self.current_row.get_column_value("slot")
self.showCurrent() | [
"def",
"chooseForm_slot",
"(",
"self",
",",
"element",
",",
"element_old",
")",
":",
"self",
".",
"current_slot",
"=",
"None",
"if",
"(",
"verbose",
")",
":",
"# enable this if you're unsure what's coming here..",
"print",
"(",
"self",
".",
"pre",
",",
"\"choose... | Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List classes, widget attribute's, currentItemChanged method (List.widget is QListWidget that has currentItemChanged slot), so the element and element_old parameters are QListWidgetItem instances with extra attributes "_id" and "_classname" attached.
Queries the database for element._id | [
"Calling",
"this",
"slot",
"chooses",
"the",
"form",
"to",
"be",
"shown"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/form.py#L74-L112 |
10,798 | elsampsa/valkka-live | valkka/live/form.py | SlotFormSet.update_dropdown_list_slot | def update_dropdown_list_slot(self):
"""Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available
"""
self.dropdown_widget.clear() # this will trigger dropdown_changed_slot
self.row_instance_by_index = []
for i, key in enumerate(self.row_instance_by_name.keys()):
row_instance = self.row_instance_by_name[key]
if (row_instance.isActive()):
self.row_instance_by_index.append(row_instance)
display_name = row_instance.getName()
self.dropdown_widget.insertItem(i, display_name)
row_instance.updateWidget() | python | def update_dropdown_list_slot(self):
self.dropdown_widget.clear() # this will trigger dropdown_changed_slot
self.row_instance_by_index = []
for i, key in enumerate(self.row_instance_by_name.keys()):
row_instance = self.row_instance_by_name[key]
if (row_instance.isActive()):
self.row_instance_by_index.append(row_instance)
display_name = row_instance.getName()
self.dropdown_widget.insertItem(i, display_name)
row_instance.updateWidget() | [
"def",
"update_dropdown_list_slot",
"(",
"self",
")",
":",
"self",
".",
"dropdown_widget",
".",
"clear",
"(",
")",
"# this will trigger dropdown_changed_slot",
"self",
".",
"row_instance_by_index",
"=",
"[",
"]",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(",
"... | Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available | [
"Keep",
"updating",
"the",
"dropdown",
"list",
".",
"Say",
"don",
"t",
"let",
"the",
"user",
"choose",
"USB",
"devices",
"if",
"none",
"is",
"available"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/form.py#L190-L201 |
10,799 | elsampsa/valkka-live | valkka/live/filterchain.py | FilterChainGroup.get | def get(self, **kwargs):
"""Find correct filterchain based on generic variables
"""
for chain in self.chains:
for key in kwargs:
getter_name = "get_"+key
# scan all possible getters
if (hasattr(chain, getter_name)):
getter = getattr(chain, getter_name) # e.g. "get_address"
if (getter() == kwargs[key]):
return chain
return None | python | def get(self, **kwargs):
for chain in self.chains:
for key in kwargs:
getter_name = "get_"+key
# scan all possible getters
if (hasattr(chain, getter_name)):
getter = getattr(chain, getter_name) # e.g. "get_address"
if (getter() == kwargs[key]):
return chain
return None | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"chain",
"in",
"self",
".",
"chains",
":",
"for",
"key",
"in",
"kwargs",
":",
"getter_name",
"=",
"\"get_\"",
"+",
"key",
"# scan all possible getters",
"if",
"(",
"hasattr",
"(",
"ch... | Find correct filterchain based on generic variables | [
"Find",
"correct",
"filterchain",
"based",
"on",
"generic",
"variables"
] | 218bb2ecf71c516c85b1b6e075454bba13090cd8 | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/filterchain.py#L214-L225 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.