repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
minrk/findspark | findspark.py | _add_to_submit_args | def _add_to_submit_args(s):
"""Adds string s to the PYSPARK_SUBMIT_ARGS env var"""
new_args = os.environ.get("PYSPARK_SUBMIT_ARGS", "") + (" %s" % s)
os.environ["PYSPARK_SUBMIT_ARGS"] = new_args
return new_args | python | def _add_to_submit_args(s):
"""Adds string s to the PYSPARK_SUBMIT_ARGS env var"""
new_args = os.environ.get("PYSPARK_SUBMIT_ARGS", "") + (" %s" % s)
os.environ["PYSPARK_SUBMIT_ARGS"] = new_args
return new_args | [
"def",
"_add_to_submit_args",
"(",
"s",
")",
":",
"new_args",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PYSPARK_SUBMIT_ARGS\"",
",",
"\"\"",
")",
"+",
"(",
"\" %s\"",
"%",
"s",
")",
"os",
".",
"environ",
"[",
"\"PYSPARK_SUBMIT_ARGS\"",
"]",
"=",
"new_args",
"return",
"new_args"
] | Adds string s to the PYSPARK_SUBMIT_ARGS env var | [
"Adds",
"string",
"s",
"to",
"the",
"PYSPARK_SUBMIT_ARGS",
"env",
"var"
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L149-L153 | train | 238,200 |
minrk/findspark | findspark.py | add_packages | def add_packages(packages):
"""Add external packages to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
packages: list of package names in string format
"""
#if the parameter is a string, convert to a single element list
if isinstance(packages,str):
packages = [packages]
_add_to_submit_args("--packages "+ ",".join(packages) +" pyspark-shell") | python | def add_packages(packages):
"""Add external packages to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
packages: list of package names in string format
"""
#if the parameter is a string, convert to a single element list
if isinstance(packages,str):
packages = [packages]
_add_to_submit_args("--packages "+ ",".join(packages) +" pyspark-shell") | [
"def",
"add_packages",
"(",
"packages",
")",
":",
"#if the parameter is a string, convert to a single element list",
"if",
"isinstance",
"(",
"packages",
",",
"str",
")",
":",
"packages",
"=",
"[",
"packages",
"]",
"_add_to_submit_args",
"(",
"\"--packages \"",
"+",
"\",\"",
".",
"join",
"(",
"packages",
")",
"+",
"\" pyspark-shell\"",
")"
] | Add external packages to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
packages: list of package names in string format | [
"Add",
"external",
"packages",
"to",
"the",
"pyspark",
"interpreter",
"."
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L155-L169 | train | 238,201 |
minrk/findspark | findspark.py | add_jars | def add_jars(jars):
"""Add external jars to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
jars: list of path to jars in string format
"""
#if the parameter is a string, convert to a single element list
if isinstance(jars,str):
jars = [jars]
_add_to_submit_args("--jars "+ ",".join(jars) +" pyspark-shell") | python | def add_jars(jars):
"""Add external jars to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
jars: list of path to jars in string format
"""
#if the parameter is a string, convert to a single element list
if isinstance(jars,str):
jars = [jars]
_add_to_submit_args("--jars "+ ",".join(jars) +" pyspark-shell") | [
"def",
"add_jars",
"(",
"jars",
")",
":",
"#if the parameter is a string, convert to a single element list",
"if",
"isinstance",
"(",
"jars",
",",
"str",
")",
":",
"jars",
"=",
"[",
"jars",
"]",
"_add_to_submit_args",
"(",
"\"--jars \"",
"+",
"\",\"",
".",
"join",
"(",
"jars",
")",
"+",
"\" pyspark-shell\"",
")"
] | Add external jars to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
jars: list of path to jars in string format | [
"Add",
"external",
"jars",
"to",
"the",
"pyspark",
"interpreter",
"."
] | 20c945d5136269ca56b1341786c49087faa7c75e | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L171-L185 | train | 238,202 |
sdispater/cleo | cleo/parser.py | Parser.parse | def parse(cls, expression):
"""
Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict
"""
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
if not matches:
raise ValueError("Unable to determine command name from signature.")
name = matches.group(0)
parsed["name"] = name
tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)
if tokens:
parsed.update(cls._parameters(tokens))
return parsed | python | def parse(cls, expression):
"""
Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict
"""
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
if not matches:
raise ValueError("Unable to determine command name from signature.")
name = matches.group(0)
parsed["name"] = name
tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)
if tokens:
parsed.update(cls._parameters(tokens))
return parsed | [
"def",
"parse",
"(",
"cls",
",",
"expression",
")",
":",
"parsed",
"=",
"{",
"\"name\"",
":",
"None",
",",
"\"arguments\"",
":",
"[",
"]",
",",
"\"options\"",
":",
"[",
"]",
"}",
"if",
"not",
"expression",
".",
"strip",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Console command signature is empty.\"",
")",
"expression",
"=",
"expression",
".",
"replace",
"(",
"os",
".",
"linesep",
",",
"\"\"",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"[^\\s]+\"",
",",
"expression",
")",
"if",
"not",
"matches",
":",
"raise",
"ValueError",
"(",
"\"Unable to determine command name from signature.\"",
")",
"name",
"=",
"matches",
".",
"group",
"(",
"0",
")",
"parsed",
"[",
"\"name\"",
"]",
"=",
"name",
"tokens",
"=",
"re",
".",
"findall",
"(",
"r\"\\{\\s*(.*?)\\s*\\}\"",
",",
"expression",
")",
"if",
"tokens",
":",
"parsed",
".",
"update",
"(",
"cls",
".",
"_parameters",
"(",
"tokens",
")",
")",
"return",
"parsed"
] | Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict | [
"Parse",
"the",
"given",
"console",
"command",
"definition",
"into",
"a",
"dict",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L16-L45 | train | 238,203 |
sdispater/cleo | cleo/parser.py | Parser._parameters | def _parameters(cls, tokens):
"""
Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict
"""
arguments = []
options = []
for token in tokens:
if not token.startswith("--"):
arguments.append(cls._parse_argument(token))
else:
options.append(cls._parse_option(token))
return {"arguments": arguments, "options": options} | python | def _parameters(cls, tokens):
"""
Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict
"""
arguments = []
options = []
for token in tokens:
if not token.startswith("--"):
arguments.append(cls._parse_argument(token))
else:
options.append(cls._parse_option(token))
return {"arguments": arguments, "options": options} | [
"def",
"_parameters",
"(",
"cls",
",",
"tokens",
")",
":",
"arguments",
"=",
"[",
"]",
"options",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"if",
"not",
"token",
".",
"startswith",
"(",
"\"--\"",
")",
":",
"arguments",
".",
"append",
"(",
"cls",
".",
"_parse_argument",
"(",
"token",
")",
")",
"else",
":",
"options",
".",
"append",
"(",
"cls",
".",
"_parse_option",
"(",
"token",
")",
")",
"return",
"{",
"\"arguments\"",
":",
"arguments",
",",
"\"options\"",
":",
"options",
"}"
] | Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict | [
"Extract",
"all",
"of",
"the",
"parameters",
"from",
"the",
"tokens",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L48-L66 | train | 238,204 |
sdispater/cleo | cleo/parser.py | Parser._parse_argument | def _parse_argument(cls, token):
"""
Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
if token.endswith("?*"):
return _argument(
token.rstrip("?*"),
Argument.MULTI_VALUED | Argument.OPTIONAL,
description,
None,
)
elif token.endswith("*"):
return _argument(
token.rstrip("*"),
Argument.MULTI_VALUED | Argument.REQUIRED,
description,
None,
)
elif token.endswith("?"):
return _argument(token.rstrip("?"), Argument.OPTIONAL, description, None)
matches = re.match(r"(.+)=(.+)", token)
if matches:
return _argument(
matches.group(1), Argument.OPTIONAL, description, matches.group(2)
)
return _argument(token, Argument.REQUIRED, description, None) | python | def _parse_argument(cls, token):
"""
Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
if token.endswith("?*"):
return _argument(
token.rstrip("?*"),
Argument.MULTI_VALUED | Argument.OPTIONAL,
description,
None,
)
elif token.endswith("*"):
return _argument(
token.rstrip("*"),
Argument.MULTI_VALUED | Argument.REQUIRED,
description,
None,
)
elif token.endswith("?"):
return _argument(token.rstrip("?"), Argument.OPTIONAL, description, None)
matches = re.match(r"(.+)=(.+)", token)
if matches:
return _argument(
matches.group(1), Argument.OPTIONAL, description, matches.group(2)
)
return _argument(token, Argument.REQUIRED, description, None) | [
"def",
"_parse_argument",
"(",
"cls",
",",
"token",
")",
":",
"description",
"=",
"\"\"",
"validator",
"=",
"None",
"if",
"\" : \"",
"in",
"token",
":",
"token",
",",
"description",
"=",
"tuple",
"(",
"token",
".",
"split",
"(",
"\" : \"",
",",
"2",
")",
")",
"token",
"=",
"token",
".",
"strip",
"(",
")",
"description",
"=",
"description",
".",
"strip",
"(",
")",
"# Checking validator:",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"(.*)\\((.*?)\\)\"",
",",
"token",
")",
"if",
"matches",
":",
"token",
"=",
"matches",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"validator",
"=",
"matches",
".",
"group",
"(",
"2",
")",
".",
"strip",
"(",
")",
"if",
"token",
".",
"endswith",
"(",
"\"?*\"",
")",
":",
"return",
"_argument",
"(",
"token",
".",
"rstrip",
"(",
"\"?*\"",
")",
",",
"Argument",
".",
"MULTI_VALUED",
"|",
"Argument",
".",
"OPTIONAL",
",",
"description",
",",
"None",
",",
")",
"elif",
"token",
".",
"endswith",
"(",
"\"*\"",
")",
":",
"return",
"_argument",
"(",
"token",
".",
"rstrip",
"(",
"\"*\"",
")",
",",
"Argument",
".",
"MULTI_VALUED",
"|",
"Argument",
".",
"REQUIRED",
",",
"description",
",",
"None",
",",
")",
"elif",
"token",
".",
"endswith",
"(",
"\"?\"",
")",
":",
"return",
"_argument",
"(",
"token",
".",
"rstrip",
"(",
"\"?\"",
")",
",",
"Argument",
".",
"OPTIONAL",
",",
"description",
",",
"None",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"(.+)=(.+)\"",
",",
"token",
")",
"if",
"matches",
":",
"return",
"_argument",
"(",
"matches",
".",
"group",
"(",
"1",
")",
",",
"Argument",
".",
"OPTIONAL",
",",
"description",
",",
"matches",
".",
"group",
"(",
"2",
")",
")",
"return",
"_argument",
"(",
"token",
",",
"Argument",
".",
"REQUIRED",
",",
"description",
",",
"None",
")"
] | Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument | [
"Parse",
"an",
"argument",
"expression",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L69-L117 | train | 238,205 |
sdispater/cleo | cleo/parser.py | Parser._parse_option | def _parse_option(cls, token):
"""
Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
shortcut = None
matches = re.split(r"\s*\|\s*", token, 2)
if len(matches) > 1:
shortcut = matches[0].lstrip("-")
token = matches[1]
else:
token = token.lstrip("-")
default = None
mode = Option.NO_VALUE
if token.endswith("=*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=*")
elif token.endswith("=?*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=?*")
elif token.endswith("=?"):
mode = Option.OPTIONAL_VALUE
token = token.rstrip("=?")
elif token.endswith("="):
mode = Option.REQUIRED_VALUE
token = token.rstrip("=")
matches = re.match(r"(.+)(=[?*]*)(.+)", token)
if matches:
token = matches.group(1)
operator = matches.group(2)
default = matches.group(3)
if operator == "=*":
mode = Option.REQUIRED_VALUE | Option.MULTI_VALUED
elif operator == "=?*":
mode = Option.MULTI_VALUED
elif operator == "=?":
mode = Option.OPTIONAL_VALUE
elif operator == "=":
mode = Option.REQUIRED_VALUE
return _option(token, shortcut, mode, description, default) | python | def _parse_option(cls, token):
"""
Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
shortcut = None
matches = re.split(r"\s*\|\s*", token, 2)
if len(matches) > 1:
shortcut = matches[0].lstrip("-")
token = matches[1]
else:
token = token.lstrip("-")
default = None
mode = Option.NO_VALUE
if token.endswith("=*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=*")
elif token.endswith("=?*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=?*")
elif token.endswith("=?"):
mode = Option.OPTIONAL_VALUE
token = token.rstrip("=?")
elif token.endswith("="):
mode = Option.REQUIRED_VALUE
token = token.rstrip("=")
matches = re.match(r"(.+)(=[?*]*)(.+)", token)
if matches:
token = matches.group(1)
operator = matches.group(2)
default = matches.group(3)
if operator == "=*":
mode = Option.REQUIRED_VALUE | Option.MULTI_VALUED
elif operator == "=?*":
mode = Option.MULTI_VALUED
elif operator == "=?":
mode = Option.OPTIONAL_VALUE
elif operator == "=":
mode = Option.REQUIRED_VALUE
return _option(token, shortcut, mode, description, default) | [
"def",
"_parse_option",
"(",
"cls",
",",
"token",
")",
":",
"description",
"=",
"\"\"",
"validator",
"=",
"None",
"if",
"\" : \"",
"in",
"token",
":",
"token",
",",
"description",
"=",
"tuple",
"(",
"token",
".",
"split",
"(",
"\" : \"",
",",
"2",
")",
")",
"token",
"=",
"token",
".",
"strip",
"(",
")",
"description",
"=",
"description",
".",
"strip",
"(",
")",
"# Checking validator:",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"(.*)\\((.*?)\\)\"",
",",
"token",
")",
"if",
"matches",
":",
"token",
"=",
"matches",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"validator",
"=",
"matches",
".",
"group",
"(",
"2",
")",
".",
"strip",
"(",
")",
"shortcut",
"=",
"None",
"matches",
"=",
"re",
".",
"split",
"(",
"r\"\\s*\\|\\s*\"",
",",
"token",
",",
"2",
")",
"if",
"len",
"(",
"matches",
")",
">",
"1",
":",
"shortcut",
"=",
"matches",
"[",
"0",
"]",
".",
"lstrip",
"(",
"\"-\"",
")",
"token",
"=",
"matches",
"[",
"1",
"]",
"else",
":",
"token",
"=",
"token",
".",
"lstrip",
"(",
"\"-\"",
")",
"default",
"=",
"None",
"mode",
"=",
"Option",
".",
"NO_VALUE",
"if",
"token",
".",
"endswith",
"(",
"\"=*\"",
")",
":",
"mode",
"=",
"Option",
".",
"MULTI_VALUED",
"token",
"=",
"token",
".",
"rstrip",
"(",
"\"=*\"",
")",
"elif",
"token",
".",
"endswith",
"(",
"\"=?*\"",
")",
":",
"mode",
"=",
"Option",
".",
"MULTI_VALUED",
"token",
"=",
"token",
".",
"rstrip",
"(",
"\"=?*\"",
")",
"elif",
"token",
".",
"endswith",
"(",
"\"=?\"",
")",
":",
"mode",
"=",
"Option",
".",
"OPTIONAL_VALUE",
"token",
"=",
"token",
".",
"rstrip",
"(",
"\"=?\"",
")",
"elif",
"token",
".",
"endswith",
"(",
"\"=\"",
")",
":",
"mode",
"=",
"Option",
".",
"REQUIRED_VALUE",
"token",
"=",
"token",
".",
"rstrip",
"(",
"\"=\"",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"(.+)(=[?*]*)(.+)\"",
",",
"token",
")",
"if",
"matches",
":",
"token",
"=",
"matches",
".",
"group",
"(",
"1",
")",
"operator",
"=",
"matches",
".",
"group",
"(",
"2",
")",
"default",
"=",
"matches",
".",
"group",
"(",
"3",
")",
"if",
"operator",
"==",
"\"=*\"",
":",
"mode",
"=",
"Option",
".",
"REQUIRED_VALUE",
"|",
"Option",
".",
"MULTI_VALUED",
"elif",
"operator",
"==",
"\"=?*\"",
":",
"mode",
"=",
"Option",
".",
"MULTI_VALUED",
"elif",
"operator",
"==",
"\"=?\"",
":",
"mode",
"=",
"Option",
".",
"OPTIONAL_VALUE",
"elif",
"operator",
"==",
"\"=\"",
":",
"mode",
"=",
"Option",
".",
"REQUIRED_VALUE",
"return",
"_option",
"(",
"token",
",",
"shortcut",
",",
"mode",
",",
"description",
",",
"default",
")"
] | Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption | [
"Parse",
"an",
"option",
"expression",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L120-L186 | train | 238,206 |
sdispater/cleo | cleo/application.py | Application.add | def add(self, command): # type: (BaseCommand) -> Application
"""
Adds a command object.
"""
self.add_command(command.config)
command.set_application(self)
return self | python | def add(self, command): # type: (BaseCommand) -> Application
"""
Adds a command object.
"""
self.add_command(command.config)
command.set_application(self)
return self | [
"def",
"add",
"(",
"self",
",",
"command",
")",
":",
"# type: (BaseCommand) -> Application",
"self",
".",
"add_command",
"(",
"command",
".",
"config",
")",
"command",
".",
"set_application",
"(",
"self",
")",
"return",
"self"
] | Adds a command object. | [
"Adds",
"a",
"command",
"object",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/application.py#L38-L45 | train | 238,207 |
sdispater/cleo | cleo/commands/command.py | Command._configure_using_fluent_definition | def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default) | python | def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default) | [
"def",
"_configure_using_fluent_definition",
"(",
"self",
")",
":",
"definition",
"=",
"Parser",
".",
"parse",
"(",
"self",
".",
"signature",
")",
"self",
".",
"_config",
".",
"set_name",
"(",
"definition",
"[",
"\"name\"",
"]",
")",
"for",
"name",
",",
"flags",
",",
"description",
",",
"default",
"in",
"definition",
"[",
"\"arguments\"",
"]",
":",
"self",
".",
"_config",
".",
"add_argument",
"(",
"name",
",",
"flags",
",",
"description",
",",
"default",
")",
"for",
"long_name",
",",
"short_name",
",",
"flags",
",",
"description",
",",
"default",
"in",
"definition",
"[",
"\"options\"",
"]",
":",
"self",
".",
"_config",
".",
"add_option",
"(",
"long_name",
",",
"short_name",
",",
"flags",
",",
"description",
",",
"default",
")"
] | Configure the console command using a fluent definition. | [
"Configure",
"the",
"console",
"command",
"using",
"a",
"fluent",
"definition",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L71-L83 | train | 238,208 |
sdispater/cleo | cleo/commands/command.py | Command.argument | def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key) | python | def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key) | [
"def",
"argument",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"_args",
".",
"arguments",
"(",
")",
"return",
"self",
".",
"_args",
".",
"argument",
"(",
"key",
")"
] | Get the value of a command argument. | [
"Get",
"the",
"value",
"of",
"a",
"command",
"argument",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L124-L131 | train | 238,209 |
sdispater/cleo | cleo/commands/command.py | Command.option | def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key) | python | def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key) | [
"def",
"option",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"_args",
".",
"options",
"(",
")",
"return",
"self",
".",
"_args",
".",
"option",
"(",
"key",
")"
] | Get the value of a command option. | [
"Get",
"the",
"value",
"of",
"a",
"command",
"option",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L133-L140 | train | 238,210 |
sdispater/cleo | cleo/commands/command.py | Command.confirm | def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex) | python | def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex) | [
"def",
"confirm",
"(",
"self",
",",
"question",
",",
"default",
"=",
"False",
",",
"true_answer_regex",
"=",
"\"(?i)^y\"",
")",
":",
"return",
"self",
".",
"_io",
".",
"confirm",
"(",
"question",
",",
"default",
",",
"true_answer_regex",
")"
] | Confirm a question with the user. | [
"Confirm",
"a",
"question",
"with",
"the",
"user",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L142-L146 | train | 238,211 |
sdispater/cleo | cleo/commands/command.py | Command.ask | def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default) | python | def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default) | [
"def",
"ask",
"(",
"self",
",",
"question",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"question",
",",
"Question",
")",
":",
"return",
"self",
".",
"_io",
".",
"ask_question",
"(",
"question",
")",
"return",
"self",
".",
"_io",
".",
"ask",
"(",
"question",
",",
"default",
")"
] | Prompt the user for input. | [
"Prompt",
"the",
"user",
"for",
"input",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L148-L155 | train | 238,212 |
sdispater/cleo | cleo/commands/command.py | Command.choice | def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question) | python | def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question) | [
"def",
"choice",
"(",
"self",
",",
"question",
",",
"choices",
",",
"default",
"=",
"None",
",",
"attempts",
"=",
"None",
",",
"multiple",
"=",
"False",
")",
":",
"question",
"=",
"ChoiceQuestion",
"(",
"question",
",",
"choices",
",",
"default",
")",
"question",
".",
"set_max_attempts",
"(",
"attempts",
")",
"question",
".",
"set_multi_select",
"(",
"multiple",
")",
"return",
"self",
".",
"_io",
".",
"ask_question",
"(",
"question",
")"
] | Give the user a single choice from an list of answers. | [
"Give",
"the",
"user",
"a",
"single",
"choice",
"from",
"an",
"list",
"of",
"answers",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L163-L172 | train | 238,213 |
sdispater/cleo | cleo/commands/command.py | Command.create_question | def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs) | python | def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs) | [
"def",
"create_question",
"(",
"self",
",",
"question",
",",
"type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"type",
":",
"return",
"Question",
"(",
"question",
",",
"*",
"*",
"kwargs",
")",
"if",
"type",
"==",
"\"choice\"",
":",
"return",
"ChoiceQuestion",
"(",
"question",
",",
"*",
"*",
"kwargs",
")",
"if",
"type",
"==",
"\"confirmation\"",
":",
"return",
"ConfirmationQuestion",
"(",
"question",
",",
"*",
"*",
"kwargs",
")"
] | Returns a Question of specified type. | [
"Returns",
"a",
"Question",
"of",
"specified",
"type",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L174-L185 | train | 238,214 |
sdispater/cleo | cleo/commands/command.py | Command.table | def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table | python | def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table | [
"def",
"table",
"(",
"self",
",",
"header",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"style",
"=",
"None",
")",
":",
"if",
"style",
"is",
"not",
"None",
":",
"style",
"=",
"self",
".",
"TABLE_STYLES",
"[",
"style",
"]",
"table",
"=",
"Table",
"(",
"style",
")",
"if",
"header",
":",
"table",
".",
"set_header_row",
"(",
"header",
")",
"if",
"rows",
":",
"table",
".",
"set_rows",
"(",
"rows",
")",
"return",
"table"
] | Return a Table instance. | [
"Return",
"a",
"Table",
"instance",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L187-L202 | train | 238,215 |
sdispater/cleo | cleo/commands/command.py | Command.render_table | def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io) | python | def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io) | [
"def",
"render_table",
"(",
"self",
",",
"headers",
",",
"rows",
",",
"style",
"=",
"None",
")",
":",
"table",
"=",
"self",
".",
"table",
"(",
"headers",
",",
"rows",
",",
"style",
")",
"table",
".",
"render",
"(",
"self",
".",
"_io",
")"
] | Format input to textual table. | [
"Format",
"input",
"to",
"textual",
"table",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L204-L210 | train | 238,216 |
sdispater/cleo | cleo/commands/command.py | Command.line | def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity) | python | def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity) | [
"def",
"line",
"(",
"self",
",",
"text",
",",
"style",
"=",
"None",
",",
"verbosity",
"=",
"None",
")",
":",
"if",
"style",
":",
"styled",
"=",
"\"<%s>%s</>\"",
"%",
"(",
"style",
",",
"text",
")",
"else",
":",
"styled",
"=",
"text",
"self",
".",
"_io",
".",
"write_line",
"(",
"styled",
",",
"verbosity",
")"
] | Write a string as information output. | [
"Write",
"a",
"string",
"as",
"information",
"output",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L224-L233 | train | 238,217 |
sdispater/cleo | cleo/commands/command.py | Command.line_error | def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity) | python | def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity) | [
"def",
"line_error",
"(",
"self",
",",
"text",
",",
"style",
"=",
"None",
",",
"verbosity",
"=",
"None",
")",
":",
"if",
"style",
":",
"styled",
"=",
"\"<%s>%s</>\"",
"%",
"(",
"style",
",",
"text",
")",
"else",
":",
"styled",
"=",
"text",
"self",
".",
"_io",
".",
"error_line",
"(",
"styled",
",",
"verbosity",
")"
] | Write a string as information output to stderr. | [
"Write",
"a",
"string",
"as",
"information",
"output",
"to",
"stderr",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L235-L244 | train | 238,218 |
sdispater/cleo | cleo/commands/command.py | Command.progress_indicator | def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values) | python | def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values) | [
"def",
"progress_indicator",
"(",
"self",
",",
"fmt",
"=",
"None",
",",
"interval",
"=",
"100",
",",
"values",
"=",
"None",
")",
":",
"return",
"ProgressIndicator",
"(",
"self",
".",
"io",
",",
"fmt",
",",
"interval",
",",
"values",
")"
] | Creates a new progress indicator. | [
"Creates",
"a",
"new",
"progress",
"indicator",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L284-L288 | train | 238,219 |
sdispater/cleo | cleo/commands/command.py | Command.spin | def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message) | python | def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message) | [
"def",
"spin",
"(",
"self",
",",
"start_message",
",",
"end_message",
",",
"fmt",
"=",
"None",
",",
"interval",
"=",
"100",
",",
"values",
"=",
"None",
")",
":",
"spinner",
"=",
"ProgressIndicator",
"(",
"self",
".",
"io",
",",
"fmt",
",",
"interval",
",",
"values",
")",
"return",
"spinner",
".",
"auto",
"(",
"start_message",
",",
"end_message",
")"
] | Automatically spin a progress indicator. | [
"Automatically",
"spin",
"a",
"progress",
"indicator",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L290-L296 | train | 238,220 |
sdispater/cleo | cleo/commands/command.py | Command.add_style | def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style) | python | def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style) | [
"def",
"add_style",
"(",
"self",
",",
"name",
",",
"fg",
"=",
"None",
",",
"bg",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"style",
"=",
"Style",
"(",
"name",
")",
"if",
"fg",
"is",
"not",
"None",
":",
"style",
".",
"fg",
"(",
"fg",
")",
"if",
"bg",
"is",
"not",
"None",
":",
"style",
".",
"bg",
"(",
"bg",
")",
"if",
"options",
"is",
"not",
"None",
":",
"if",
"\"bold\"",
"in",
"options",
":",
"style",
".",
"bold",
"(",
")",
"if",
"\"underline\"",
"in",
"options",
":",
"style",
".",
"underlined",
"(",
")",
"self",
".",
"_io",
".",
"output",
".",
"formatter",
".",
"add_style",
"(",
"style",
")",
"self",
".",
"_io",
".",
"error_output",
".",
"formatter",
".",
"add_style",
"(",
"style",
")"
] | Adds a new style | [
"Adds",
"a",
"new",
"style"
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L298-L317 | train | 238,221 |
sdispater/cleo | cleo/commands/command.py | Command.overwrite | def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size) | python | def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size) | [
"def",
"overwrite",
"(",
"self",
",",
"text",
",",
"size",
"=",
"None",
")",
":",
"self",
".",
"_io",
".",
"overwrite",
"(",
"text",
",",
"size",
"=",
"size",
")"
] | Overwrites the current line.
It will not add a new line so use line('')
if necessary. | [
"Overwrites",
"the",
"current",
"line",
"."
] | cf44ac2eba2d6435516501e47e5521ee2da9115a | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L319-L326 | train | 238,222 |
Mergifyio/git-pull-request | git_pull_request/__init__.py | get_github_hostname_user_repo_from_url | def get_github_hostname_user_repo_from_url(url):
"""Return hostname, user and repository to fork from.
:param url: The URL to parse
:return: hostname, user, repository
"""
parsed = parse.urlparse(url)
if parsed.netloc == '':
# Probably ssh
host, sep, path = parsed.path.partition(":")
if "@" in host:
username, sep, host = host.partition("@")
else:
path = parsed.path[1:].rstrip('/')
host = parsed.netloc
user, repo = path.split("/", 1)
return host, user, repo[:-4] if repo.endswith('.git') else repo | python | def get_github_hostname_user_repo_from_url(url):
"""Return hostname, user and repository to fork from.
:param url: The URL to parse
:return: hostname, user, repository
"""
parsed = parse.urlparse(url)
if parsed.netloc == '':
# Probably ssh
host, sep, path = parsed.path.partition(":")
if "@" in host:
username, sep, host = host.partition("@")
else:
path = parsed.path[1:].rstrip('/')
host = parsed.netloc
user, repo = path.split("/", 1)
return host, user, repo[:-4] if repo.endswith('.git') else repo | [
"def",
"get_github_hostname_user_repo_from_url",
"(",
"url",
")",
":",
"parsed",
"=",
"parse",
".",
"urlparse",
"(",
"url",
")",
"if",
"parsed",
".",
"netloc",
"==",
"''",
":",
"# Probably ssh",
"host",
",",
"sep",
",",
"path",
"=",
"parsed",
".",
"path",
".",
"partition",
"(",
"\":\"",
")",
"if",
"\"@\"",
"in",
"host",
":",
"username",
",",
"sep",
",",
"host",
"=",
"host",
".",
"partition",
"(",
"\"@\"",
")",
"else",
":",
"path",
"=",
"parsed",
".",
"path",
"[",
"1",
":",
"]",
".",
"rstrip",
"(",
"'/'",
")",
"host",
"=",
"parsed",
".",
"netloc",
"user",
",",
"repo",
"=",
"path",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"return",
"host",
",",
"user",
",",
"repo",
"[",
":",
"-",
"4",
"]",
"if",
"repo",
".",
"endswith",
"(",
"'.git'",
")",
"else",
"repo"
] | Return hostname, user and repository to fork from.
:param url: The URL to parse
:return: hostname, user, repository | [
"Return",
"hostname",
"user",
"and",
"repository",
"to",
"fork",
"from",
"."
] | 58dbe3325b3dfada02482a32223fb36ebb193248 | https://github.com/Mergifyio/git-pull-request/blob/58dbe3325b3dfada02482a32223fb36ebb193248/git_pull_request/__init__.py#L114-L130 | train | 238,223 |
Mergifyio/git-pull-request | git_pull_request/__init__.py | git_get_title_and_message | def git_get_title_and_message(begin, end):
"""Get title and message summary for patches between 2 commits.
:param begin: first commit to look at
:param end: last commit to look at
:return: number of commits, title, message
"""
titles = git_get_log_titles(begin, end)
title = "Pull request for " + end
if len(titles) == 1:
title = titles[0]
pr_template = find_pull_request_template()
if pr_template:
message = get_pr_template_message(pr_template)
else:
if len(titles) == 1:
message = git_get_commit_body(end)
else:
message = "\n".join(titles)
return (len(titles), title, message) | python | def git_get_title_and_message(begin, end):
"""Get title and message summary for patches between 2 commits.
:param begin: first commit to look at
:param end: last commit to look at
:return: number of commits, title, message
"""
titles = git_get_log_titles(begin, end)
title = "Pull request for " + end
if len(titles) == 1:
title = titles[0]
pr_template = find_pull_request_template()
if pr_template:
message = get_pr_template_message(pr_template)
else:
if len(titles) == 1:
message = git_get_commit_body(end)
else:
message = "\n".join(titles)
return (len(titles), title, message) | [
"def",
"git_get_title_and_message",
"(",
"begin",
",",
"end",
")",
":",
"titles",
"=",
"git_get_log_titles",
"(",
"begin",
",",
"end",
")",
"title",
"=",
"\"Pull request for \"",
"+",
"end",
"if",
"len",
"(",
"titles",
")",
"==",
"1",
":",
"title",
"=",
"titles",
"[",
"0",
"]",
"pr_template",
"=",
"find_pull_request_template",
"(",
")",
"if",
"pr_template",
":",
"message",
"=",
"get_pr_template_message",
"(",
"pr_template",
")",
"else",
":",
"if",
"len",
"(",
"titles",
")",
"==",
"1",
":",
"message",
"=",
"git_get_commit_body",
"(",
"end",
")",
"else",
":",
"message",
"=",
"\"\\n\"",
".",
"join",
"(",
"titles",
")",
"return",
"(",
"len",
"(",
"titles",
")",
",",
"title",
",",
"message",
")"
] | Get title and message summary for patches between 2 commits.
:param begin: first commit to look at
:param end: last commit to look at
:return: number of commits, title, message | [
"Get",
"title",
"and",
"message",
"summary",
"for",
"patches",
"between",
"2",
"commits",
"."
] | 58dbe3325b3dfada02482a32223fb36ebb193248 | https://github.com/Mergifyio/git-pull-request/blob/58dbe3325b3dfada02482a32223fb36ebb193248/git_pull_request/__init__.py#L160-L180 | train | 238,224 |
zhebrak/raftos | raftos/state.py | validate_commit_index | def validate_commit_index(func):
"""Apply to State Machine everything up to commit index"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
for not_applied in range(self.log.last_applied + 1, self.log.commit_index + 1):
self.state_machine.apply(self.log[not_applied]['command'])
self.log.last_applied += 1
try:
self.apply_future.set_result(not_applied)
except (asyncio.futures.InvalidStateError, AttributeError):
pass
return func(self, *args, **kwargs)
return wrapped | python | def validate_commit_index(func):
"""Apply to State Machine everything up to commit index"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
for not_applied in range(self.log.last_applied + 1, self.log.commit_index + 1):
self.state_machine.apply(self.log[not_applied]['command'])
self.log.last_applied += 1
try:
self.apply_future.set_result(not_applied)
except (asyncio.futures.InvalidStateError, AttributeError):
pass
return func(self, *args, **kwargs)
return wrapped | [
"def",
"validate_commit_index",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"not_applied",
"in",
"range",
"(",
"self",
".",
"log",
".",
"last_applied",
"+",
"1",
",",
"self",
".",
"log",
".",
"commit_index",
"+",
"1",
")",
":",
"self",
".",
"state_machine",
".",
"apply",
"(",
"self",
".",
"log",
"[",
"not_applied",
"]",
"[",
"'command'",
"]",
")",
"self",
".",
"log",
".",
"last_applied",
"+=",
"1",
"try",
":",
"self",
".",
"apply_future",
".",
"set_result",
"(",
"not_applied",
")",
"except",
"(",
"asyncio",
".",
"futures",
".",
"InvalidStateError",
",",
"AttributeError",
")",
":",
"pass",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped"
] | Apply to State Machine everything up to commit index | [
"Apply",
"to",
"State",
"Machine",
"everything",
"up",
"to",
"commit",
"index"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L42-L57 | train | 238,225 |
zhebrak/raftos | raftos/state.py | Leader.execute_command | async def execute_command(self, command):
"""Write to log & send AppendEntries RPC"""
self.apply_future = asyncio.Future(loop=self.loop)
entry = self.log.write(self.storage.term, command)
asyncio.ensure_future(self.append_entries(), loop=self.loop)
await self.apply_future | python | async def execute_command(self, command):
"""Write to log & send AppendEntries RPC"""
self.apply_future = asyncio.Future(loop=self.loop)
entry = self.log.write(self.storage.term, command)
asyncio.ensure_future(self.append_entries(), loop=self.loop)
await self.apply_future | [
"async",
"def",
"execute_command",
"(",
"self",
",",
"command",
")",
":",
"self",
".",
"apply_future",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"self",
".",
"loop",
")",
"entry",
"=",
"self",
".",
"log",
".",
"write",
"(",
"self",
".",
"storage",
".",
"term",
",",
"command",
")",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"append_entries",
"(",
")",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"await",
"self",
".",
"apply_future"
] | Write to log & send AppendEntries RPC | [
"Write",
"to",
"log",
"&",
"send",
"AppendEntries",
"RPC"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L260-L267 | train | 238,226 |
zhebrak/raftos | raftos/state.py | Candidate.start | def start(self):
"""Increment current term, vote for herself & send vote requests"""
self.storage.update({
'term': self.storage.term + 1,
'voted_for': self.id
})
self.vote_count = 1
self.request_vote()
self.election_timer.start() | python | def start(self):
"""Increment current term, vote for herself & send vote requests"""
self.storage.update({
'term': self.storage.term + 1,
'voted_for': self.id
})
self.vote_count = 1
self.request_vote()
self.election_timer.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"storage",
".",
"update",
"(",
"{",
"'term'",
":",
"self",
".",
"storage",
".",
"term",
"+",
"1",
",",
"'voted_for'",
":",
"self",
".",
"id",
"}",
")",
"self",
".",
"vote_count",
"=",
"1",
"self",
".",
"request_vote",
"(",
")",
"self",
".",
"election_timer",
".",
"start",
"(",
")"
] | Increment current term, vote for herself & send vote requests | [
"Increment",
"current",
"term",
"vote",
"for",
"herself",
"&",
"send",
"vote",
"requests"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L293-L302 | train | 238,227 |
zhebrak/raftos | raftos/state.py | Candidate.on_receive_request_vote_response | def on_receive_request_vote_response(self, data):
"""Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader
"""
if data.get('vote_granted'):
self.vote_count += 1
if self.state.is_majority(self.vote_count):
self.state.to_leader() | python | def on_receive_request_vote_response(self, data):
"""Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader
"""
if data.get('vote_granted'):
self.vote_count += 1
if self.state.is_majority(self.vote_count):
self.state.to_leader() | [
"def",
"on_receive_request_vote_response",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"'vote_granted'",
")",
":",
"self",
".",
"vote_count",
"+=",
"1",
"if",
"self",
".",
"state",
".",
"is_majority",
"(",
"self",
".",
"vote_count",
")",
":",
"self",
".",
"state",
".",
"to_leader",
"(",
")"
] | Receives response for vote request.
If the vote was granted then check if we got majority and may become Leader | [
"Receives",
"response",
"for",
"vote",
"request",
".",
"If",
"the",
"vote",
"was",
"granted",
"then",
"check",
"if",
"we",
"got",
"majority",
"and",
"may",
"become",
"Leader"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L326-L335 | train | 238,228 |
zhebrak/raftos | raftos/state.py | Follower.init_storage | def init_storage(self):
"""Set current term to zero upon initialization & voted_for to None"""
if not self.storage.exists('term'):
self.storage.update({
'term': 0,
})
self.storage.update({
'voted_for': None
}) | python | def init_storage(self):
"""Set current term to zero upon initialization & voted_for to None"""
if not self.storage.exists('term'):
self.storage.update({
'term': 0,
})
self.storage.update({
'voted_for': None
}) | [
"def",
"init_storage",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"storage",
".",
"exists",
"(",
"'term'",
")",
":",
"self",
".",
"storage",
".",
"update",
"(",
"{",
"'term'",
":",
"0",
",",
"}",
")",
"self",
".",
"storage",
".",
"update",
"(",
"{",
"'voted_for'",
":",
"None",
"}",
")"
] | Set current term to zero upon initialization & voted_for to None | [
"Set",
"current",
"term",
"to",
"zero",
"upon",
"initialization",
"&",
"voted_for",
"to",
"None"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L368-L377 | train | 238,229 |
zhebrak/raftos | raftos/state.py | State.wait_for_election_success | async def wait_for_election_success(cls):
"""Await this function if your cluster must have a leader"""
if cls.leader is None:
cls.leader_future = asyncio.Future(loop=cls.loop)
await cls.leader_future | python | async def wait_for_election_success(cls):
"""Await this function if your cluster must have a leader"""
if cls.leader is None:
cls.leader_future = asyncio.Future(loop=cls.loop)
await cls.leader_future | [
"async",
"def",
"wait_for_election_success",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"leader",
"is",
"None",
":",
"cls",
".",
"leader_future",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"cls",
".",
"loop",
")",
"await",
"cls",
".",
"leader_future"
] | Await this function if your cluster must have a leader | [
"Await",
"this",
"function",
"if",
"your",
"cluster",
"must",
"have",
"a",
"leader"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L597-L601 | train | 238,230 |
zhebrak/raftos | raftos/state.py | State.wait_until_leader | async def wait_until_leader(cls, node_id):
"""Await this function if you want to do nothing until node_id becomes a leader"""
if node_id is None:
raise ValueError('Node id can not be None!')
if cls.get_leader() != node_id:
cls.wait_until_leader_id = node_id
cls.wait_until_leader_future = asyncio.Future(loop=cls.loop)
await cls.wait_until_leader_future
cls.wait_until_leader_id = None
cls.wait_until_leader_future = None | python | async def wait_until_leader(cls, node_id):
"""Await this function if you want to do nothing until node_id becomes a leader"""
if node_id is None:
raise ValueError('Node id can not be None!')
if cls.get_leader() != node_id:
cls.wait_until_leader_id = node_id
cls.wait_until_leader_future = asyncio.Future(loop=cls.loop)
await cls.wait_until_leader_future
cls.wait_until_leader_id = None
cls.wait_until_leader_future = None | [
"async",
"def",
"wait_until_leader",
"(",
"cls",
",",
"node_id",
")",
":",
"if",
"node_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Node id can not be None!'",
")",
"if",
"cls",
".",
"get_leader",
"(",
")",
"!=",
"node_id",
":",
"cls",
".",
"wait_until_leader_id",
"=",
"node_id",
"cls",
".",
"wait_until_leader_future",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"cls",
".",
"loop",
")",
"await",
"cls",
".",
"wait_until_leader_future",
"cls",
".",
"wait_until_leader_id",
"=",
"None",
"cls",
".",
"wait_until_leader_future",
"=",
"None"
] | Await this function if you want to do nothing until node_id becomes a leader | [
"Await",
"this",
"function",
"if",
"you",
"want",
"to",
"do",
"nothing",
"until",
"node_id",
"becomes",
"a",
"leader"
] | 0d6f9e049b526279b1035f597291a96cf50c9b40 | https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L604-L615 | train | 238,231 |
datajoint/datajoint-python | datajoint/declare.py | declare | def declare(full_table_name, definition, context):
"""
Parse declaration and create new SQL table accordingly.
:param full_table_name: full name of the table
:param definition: DataJoint table definition
:param context: dictionary of objects that might be referred to in the table.
"""
table_name = full_table_name.strip('`').split('.')[1]
if len(table_name) > MAX_TABLE_NAME_LENGTH:
raise DataJointError(
'Table name `{name}` exceeds the max length of {max_length}'.format(
name=table_name,
max_length=MAX_TABLE_NAME_LENGTH))
# split definition into lines
definition = re.split(r'\s*\n\s*', definition.strip())
# check for optional table comment
table_comment = definition.pop(0)[1:].strip() if definition[0].startswith('#') else ''
in_key = True # parse primary keys
primary_key = []
attributes = []
attribute_sql = []
foreign_key_sql = []
index_sql = []
uses_external = False
for line in definition:
if line.startswith('#'): # additional comments are ignored
pass
elif line.startswith('---') or line.startswith('___'):
in_key = False # start parsing dependent attributes
elif is_foreign_key(line):
compile_foreign_key(line, context, attributes,
primary_key if in_key else None,
attribute_sql, foreign_key_sql, index_sql)
elif re.match(r'^(unique\s+)?index[^:]*$', line, re.I): # index
compile_index(line, index_sql)
else:
name, sql, is_external = compile_attribute(line, in_key, foreign_key_sql)
uses_external = uses_external or is_external
if in_key and name not in primary_key:
primary_key.append(name)
if name not in attributes:
attributes.append(name)
attribute_sql.append(sql)
# compile SQL
if not primary_key:
raise DataJointError('Table must have a primary key')
return (
'CREATE TABLE IF NOT EXISTS %s (\n' % full_table_name +
',\n'.join(attribute_sql + ['PRIMARY KEY (`' + '`,`'.join(primary_key) + '`)'] + foreign_key_sql + index_sql) +
'\n) ENGINE=InnoDB, COMMENT "%s"' % table_comment), uses_external | python | def declare(full_table_name, definition, context):
"""
Parse declaration and create new SQL table accordingly.
:param full_table_name: full name of the table
:param definition: DataJoint table definition
:param context: dictionary of objects that might be referred to in the table.
"""
table_name = full_table_name.strip('`').split('.')[1]
if len(table_name) > MAX_TABLE_NAME_LENGTH:
raise DataJointError(
'Table name `{name}` exceeds the max length of {max_length}'.format(
name=table_name,
max_length=MAX_TABLE_NAME_LENGTH))
# split definition into lines
definition = re.split(r'\s*\n\s*', definition.strip())
# check for optional table comment
table_comment = definition.pop(0)[1:].strip() if definition[0].startswith('#') else ''
in_key = True # parse primary keys
primary_key = []
attributes = []
attribute_sql = []
foreign_key_sql = []
index_sql = []
uses_external = False
for line in definition:
if line.startswith('#'): # additional comments are ignored
pass
elif line.startswith('---') or line.startswith('___'):
in_key = False # start parsing dependent attributes
elif is_foreign_key(line):
compile_foreign_key(line, context, attributes,
primary_key if in_key else None,
attribute_sql, foreign_key_sql, index_sql)
elif re.match(r'^(unique\s+)?index[^:]*$', line, re.I): # index
compile_index(line, index_sql)
else:
name, sql, is_external = compile_attribute(line, in_key, foreign_key_sql)
uses_external = uses_external or is_external
if in_key and name not in primary_key:
primary_key.append(name)
if name not in attributes:
attributes.append(name)
attribute_sql.append(sql)
# compile SQL
if not primary_key:
raise DataJointError('Table must have a primary key')
return (
'CREATE TABLE IF NOT EXISTS %s (\n' % full_table_name +
',\n'.join(attribute_sql + ['PRIMARY KEY (`' + '`,`'.join(primary_key) + '`)'] + foreign_key_sql + index_sql) +
'\n) ENGINE=InnoDB, COMMENT "%s"' % table_comment), uses_external | [
"def",
"declare",
"(",
"full_table_name",
",",
"definition",
",",
"context",
")",
":",
"table_name",
"=",
"full_table_name",
".",
"strip",
"(",
"'`'",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"table_name",
")",
">",
"MAX_TABLE_NAME_LENGTH",
":",
"raise",
"DataJointError",
"(",
"'Table name `{name}` exceeds the max length of {max_length}'",
".",
"format",
"(",
"name",
"=",
"table_name",
",",
"max_length",
"=",
"MAX_TABLE_NAME_LENGTH",
")",
")",
"# split definition into lines",
"definition",
"=",
"re",
".",
"split",
"(",
"r'\\s*\\n\\s*'",
",",
"definition",
".",
"strip",
"(",
")",
")",
"# check for optional table comment",
"table_comment",
"=",
"definition",
".",
"pop",
"(",
"0",
")",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
"if",
"definition",
"[",
"0",
"]",
".",
"startswith",
"(",
"'#'",
")",
"else",
"''",
"in_key",
"=",
"True",
"# parse primary keys",
"primary_key",
"=",
"[",
"]",
"attributes",
"=",
"[",
"]",
"attribute_sql",
"=",
"[",
"]",
"foreign_key_sql",
"=",
"[",
"]",
"index_sql",
"=",
"[",
"]",
"uses_external",
"=",
"False",
"for",
"line",
"in",
"definition",
":",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"# additional comments are ignored",
"pass",
"elif",
"line",
".",
"startswith",
"(",
"'---'",
")",
"or",
"line",
".",
"startswith",
"(",
"'___'",
")",
":",
"in_key",
"=",
"False",
"# start parsing dependent attributes",
"elif",
"is_foreign_key",
"(",
"line",
")",
":",
"compile_foreign_key",
"(",
"line",
",",
"context",
",",
"attributes",
",",
"primary_key",
"if",
"in_key",
"else",
"None",
",",
"attribute_sql",
",",
"foreign_key_sql",
",",
"index_sql",
")",
"elif",
"re",
".",
"match",
"(",
"r'^(unique\\s+)?index[^:]*$'",
",",
"line",
",",
"re",
".",
"I",
")",
":",
"# index",
"compile_index",
"(",
"line",
",",
"index_sql",
")",
"else",
":",
"name",
",",
"sql",
",",
"is_external",
"=",
"compile_attribute",
"(",
"line",
",",
"in_key",
",",
"foreign_key_sql",
")",
"uses_external",
"=",
"uses_external",
"or",
"is_external",
"if",
"in_key",
"and",
"name",
"not",
"in",
"primary_key",
":",
"primary_key",
".",
"append",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"attributes",
":",
"attributes",
".",
"append",
"(",
"name",
")",
"attribute_sql",
".",
"append",
"(",
"sql",
")",
"# compile SQL",
"if",
"not",
"primary_key",
":",
"raise",
"DataJointError",
"(",
"'Table must have a primary key'",
")",
"return",
"(",
"'CREATE TABLE IF NOT EXISTS %s (\\n'",
"%",
"full_table_name",
"+",
"',\\n'",
".",
"join",
"(",
"attribute_sql",
"+",
"[",
"'PRIMARY KEY (`'",
"+",
"'`,`'",
".",
"join",
"(",
"primary_key",
")",
"+",
"'`)'",
"]",
"+",
"foreign_key_sql",
"+",
"index_sql",
")",
"+",
"'\\n) ENGINE=InnoDB, COMMENT \"%s\"'",
"%",
"table_comment",
")",
",",
"uses_external"
] | Parse declaration and create new SQL table accordingly.
:param full_table_name: full name of the table
:param definition: DataJoint table definition
:param context: dictionary of objects that might be referred to in the table. | [
"Parse",
"declaration",
"and",
"create",
"new",
"SQL",
"table",
"accordingly",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/declare.py#L192-L245 | train | 238,232 |
datajoint/datajoint-python | datajoint/schema.py | create_virtual_module | def create_virtual_module(module_name, schema_name, create_schema=False, create_tables=False, connection=None):
"""
Creates a python module with the given name from the name of a schema on the server and
automatically adds classes to it corresponding to the tables in the schema.
:param module_name: displayed module name
:param schema_name: name of the database in mysql
:param create_schema: if True, create the schema on the database server
:param create_tables: if True, module.schema can be used as the decorator for declaring new
:return: the python module containing classes from the schema object and the table classes
"""
module = types.ModuleType(module_name)
_schema = Schema(schema_name, create_schema=create_schema, create_tables=create_tables, connection=connection)
_schema.spawn_missing_classes(context=module.__dict__)
module.__dict__['schema'] = _schema
return module | python | def create_virtual_module(module_name, schema_name, create_schema=False, create_tables=False, connection=None):
"""
Creates a python module with the given name from the name of a schema on the server and
automatically adds classes to it corresponding to the tables in the schema.
:param module_name: displayed module name
:param schema_name: name of the database in mysql
:param create_schema: if True, create the schema on the database server
:param create_tables: if True, module.schema can be used as the decorator for declaring new
:return: the python module containing classes from the schema object and the table classes
"""
module = types.ModuleType(module_name)
_schema = Schema(schema_name, create_schema=create_schema, create_tables=create_tables, connection=connection)
_schema.spawn_missing_classes(context=module.__dict__)
module.__dict__['schema'] = _schema
return module | [
"def",
"create_virtual_module",
"(",
"module_name",
",",
"schema_name",
",",
"create_schema",
"=",
"False",
",",
"create_tables",
"=",
"False",
",",
"connection",
"=",
"None",
")",
":",
"module",
"=",
"types",
".",
"ModuleType",
"(",
"module_name",
")",
"_schema",
"=",
"Schema",
"(",
"schema_name",
",",
"create_schema",
"=",
"create_schema",
",",
"create_tables",
"=",
"create_tables",
",",
"connection",
"=",
"connection",
")",
"_schema",
".",
"spawn_missing_classes",
"(",
"context",
"=",
"module",
".",
"__dict__",
")",
"module",
".",
"__dict__",
"[",
"'schema'",
"]",
"=",
"_schema",
"return",
"module"
] | Creates a python module with the given name from the name of a schema on the server and
automatically adds classes to it corresponding to the tables in the schema.
:param module_name: displayed module name
:param schema_name: name of the database in mysql
:param create_schema: if True, create the schema on the database server
:param create_tables: if True, module.schema can be used as the decorator for declaring new
:return: the python module containing classes from the schema object and the table classes | [
"Creates",
"a",
"python",
"module",
"with",
"the",
"given",
"name",
"from",
"the",
"name",
"of",
"a",
"schema",
"on",
"the",
"server",
"and",
"automatically",
"adds",
"classes",
"to",
"it",
"corresponding",
"to",
"the",
"tables",
"in",
"the",
"schema",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/schema.py#L241-L256 | train | 238,233 |
datajoint/datajoint-python | datajoint/schema.py | Schema.drop | def drop(self, force=False):
"""
Drop the associated schema if it exists
"""
if not self.exists:
logger.info("Schema named `{database}` does not exist. Doing nothing.".format(database=self.database))
elif (not config['safemode'] or
force or
user_choice("Proceed to delete entire schema `%s`?" % self.database, default='no') == 'yes'):
logger.info("Dropping `{database}`.".format(database=self.database))
try:
self.connection.query("DROP DATABASE `{database}`".format(database=self.database))
logger.info("Schema `{database}` was dropped successfully.".format(database=self.database))
except pymysql.OperationalError:
raise DataJointError("An attempt to drop schema `{database}` "
"has failed. Check permissions.".format(database=self.database)) | python | def drop(self, force=False):
"""
Drop the associated schema if it exists
"""
if not self.exists:
logger.info("Schema named `{database}` does not exist. Doing nothing.".format(database=self.database))
elif (not config['safemode'] or
force or
user_choice("Proceed to delete entire schema `%s`?" % self.database, default='no') == 'yes'):
logger.info("Dropping `{database}`.".format(database=self.database))
try:
self.connection.query("DROP DATABASE `{database}`".format(database=self.database))
logger.info("Schema `{database}` was dropped successfully.".format(database=self.database))
except pymysql.OperationalError:
raise DataJointError("An attempt to drop schema `{database}` "
"has failed. Check permissions.".format(database=self.database)) | [
"def",
"drop",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"exists",
":",
"logger",
".",
"info",
"(",
"\"Schema named `{database}` does not exist. Doing nothing.\"",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
")",
")",
"elif",
"(",
"not",
"config",
"[",
"'safemode'",
"]",
"or",
"force",
"or",
"user_choice",
"(",
"\"Proceed to delete entire schema `%s`?\"",
"%",
"self",
".",
"database",
",",
"default",
"=",
"'no'",
")",
"==",
"'yes'",
")",
":",
"logger",
".",
"info",
"(",
"\"Dropping `{database}`.\"",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
")",
")",
"try",
":",
"self",
".",
"connection",
".",
"query",
"(",
"\"DROP DATABASE `{database}`\"",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
")",
")",
"logger",
".",
"info",
"(",
"\"Schema `{database}` was dropped successfully.\"",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
")",
")",
"except",
"pymysql",
".",
"OperationalError",
":",
"raise",
"DataJointError",
"(",
"\"An attempt to drop schema `{database}` \"",
"\"has failed. Check permissions.\"",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
")",
")"
] | Drop the associated schema if it exists | [
"Drop",
"the",
"associated",
"schema",
"if",
"it",
"exists"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/schema.py#L146-L161 | train | 238,234 |
datajoint/datajoint-python | datajoint/schema.py | Schema.process_relation_class | def process_relation_class(self, relation_class, context, assert_declared=False):
"""
assign schema properties to the relation class and declare the table
"""
relation_class.database = self.database
relation_class._connection = self.connection
relation_class._heading = Heading()
# instantiate the class, declare the table if not already
instance = relation_class()
is_declared = instance.is_declared
if not is_declared:
if not self.create_tables or assert_declared:
raise DataJointError('Table not declared %s' % instance.table_name)
else:
instance.declare(context)
is_declared = is_declared or instance.is_declared
# fill values in Lookup tables from their contents property
if isinstance(instance, Lookup) and hasattr(instance, 'contents') and is_declared:
contents = list(instance.contents)
if len(contents) > len(instance):
if instance.heading.has_autoincrement:
warnings.warn(
'Contents has changed but cannot be inserted because {table} has autoincrement.'.format(
table=instance.__class__.__name__))
else:
instance.insert(contents, skip_duplicates=True) | python | def process_relation_class(self, relation_class, context, assert_declared=False):
"""
assign schema properties to the relation class and declare the table
"""
relation_class.database = self.database
relation_class._connection = self.connection
relation_class._heading = Heading()
# instantiate the class, declare the table if not already
instance = relation_class()
is_declared = instance.is_declared
if not is_declared:
if not self.create_tables or assert_declared:
raise DataJointError('Table not declared %s' % instance.table_name)
else:
instance.declare(context)
is_declared = is_declared or instance.is_declared
# fill values in Lookup tables from their contents property
if isinstance(instance, Lookup) and hasattr(instance, 'contents') and is_declared:
contents = list(instance.contents)
if len(contents) > len(instance):
if instance.heading.has_autoincrement:
warnings.warn(
'Contents has changed but cannot be inserted because {table} has autoincrement.'.format(
table=instance.__class__.__name__))
else:
instance.insert(contents, skip_duplicates=True) | [
"def",
"process_relation_class",
"(",
"self",
",",
"relation_class",
",",
"context",
",",
"assert_declared",
"=",
"False",
")",
":",
"relation_class",
".",
"database",
"=",
"self",
".",
"database",
"relation_class",
".",
"_connection",
"=",
"self",
".",
"connection",
"relation_class",
".",
"_heading",
"=",
"Heading",
"(",
")",
"# instantiate the class, declare the table if not already",
"instance",
"=",
"relation_class",
"(",
")",
"is_declared",
"=",
"instance",
".",
"is_declared",
"if",
"not",
"is_declared",
":",
"if",
"not",
"self",
".",
"create_tables",
"or",
"assert_declared",
":",
"raise",
"DataJointError",
"(",
"'Table not declared %s'",
"%",
"instance",
".",
"table_name",
")",
"else",
":",
"instance",
".",
"declare",
"(",
"context",
")",
"is_declared",
"=",
"is_declared",
"or",
"instance",
".",
"is_declared",
"# fill values in Lookup tables from their contents property",
"if",
"isinstance",
"(",
"instance",
",",
"Lookup",
")",
"and",
"hasattr",
"(",
"instance",
",",
"'contents'",
")",
"and",
"is_declared",
":",
"contents",
"=",
"list",
"(",
"instance",
".",
"contents",
")",
"if",
"len",
"(",
"contents",
")",
">",
"len",
"(",
"instance",
")",
":",
"if",
"instance",
".",
"heading",
".",
"has_autoincrement",
":",
"warnings",
".",
"warn",
"(",
"'Contents has changed but cannot be inserted because {table} has autoincrement.'",
".",
"format",
"(",
"table",
"=",
"instance",
".",
"__class__",
".",
"__name__",
")",
")",
"else",
":",
"instance",
".",
"insert",
"(",
"contents",
",",
"skip_duplicates",
"=",
"True",
")"
] | assign schema properties to the relation class and declare the table | [
"assign",
"schema",
"properties",
"to",
"the",
"relation",
"class",
"and",
"declare",
"the",
"table"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/schema.py#L171-L197 | train | 238,235 |
datajoint/datajoint-python | datajoint/table.py | Table.declare | def declare(self, context=None):
"""
Use self.definition to declare the table in the schema.
"""
try:
sql, uses_external = declare(self.full_table_name, self.definition, context)
if uses_external:
sql = sql.format(external_table=self.external_table.full_table_name)
self.connection.query(sql)
except pymysql.OperationalError as error:
# skip if no create privilege
if error.args[0] == server_error_codes['command denied']:
logger.warning(error.args[1])
else:
raise
else:
self._log('Declared ' + self.full_table_name) | python | def declare(self, context=None):
"""
Use self.definition to declare the table in the schema.
"""
try:
sql, uses_external = declare(self.full_table_name, self.definition, context)
if uses_external:
sql = sql.format(external_table=self.external_table.full_table_name)
self.connection.query(sql)
except pymysql.OperationalError as error:
# skip if no create privilege
if error.args[0] == server_error_codes['command denied']:
logger.warning(error.args[1])
else:
raise
else:
self._log('Declared ' + self.full_table_name) | [
"def",
"declare",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"sql",
",",
"uses_external",
"=",
"declare",
"(",
"self",
".",
"full_table_name",
",",
"self",
".",
"definition",
",",
"context",
")",
"if",
"uses_external",
":",
"sql",
"=",
"sql",
".",
"format",
"(",
"external_table",
"=",
"self",
".",
"external_table",
".",
"full_table_name",
")",
"self",
".",
"connection",
".",
"query",
"(",
"sql",
")",
"except",
"pymysql",
".",
"OperationalError",
"as",
"error",
":",
"# skip if no create privilege",
"if",
"error",
".",
"args",
"[",
"0",
"]",
"==",
"server_error_codes",
"[",
"'command denied'",
"]",
":",
"logger",
".",
"warning",
"(",
"error",
".",
"args",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"else",
":",
"self",
".",
"_log",
"(",
"'Declared '",
"+",
"self",
".",
"full_table_name",
")"
] | Use self.definition to declare the table in the schema. | [
"Use",
"self",
".",
"definition",
"to",
"declare",
"the",
"table",
"in",
"the",
"schema",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/table.py#L58-L74 | train | 238,236 |
datajoint/datajoint-python | datajoint/table.py | Table.delete_quick | def delete_quick(self, get_count=False):
"""
Deletes the table without cascading and without user prompt.
If this table has populated dependent tables, this will fail.
"""
query = 'DELETE FROM ' + self.full_table_name + self.where_clause
self.connection.query(query)
count = self.connection.query("SELECT ROW_COUNT()").fetchone()[0] if get_count else None
self._log(query[:255])
return count | python | def delete_quick(self, get_count=False):
"""
Deletes the table without cascading and without user prompt.
If this table has populated dependent tables, this will fail.
"""
query = 'DELETE FROM ' + self.full_table_name + self.where_clause
self.connection.query(query)
count = self.connection.query("SELECT ROW_COUNT()").fetchone()[0] if get_count else None
self._log(query[:255])
return count | [
"def",
"delete_quick",
"(",
"self",
",",
"get_count",
"=",
"False",
")",
":",
"query",
"=",
"'DELETE FROM '",
"+",
"self",
".",
"full_table_name",
"+",
"self",
".",
"where_clause",
"self",
".",
"connection",
".",
"query",
"(",
"query",
")",
"count",
"=",
"self",
".",
"connection",
".",
"query",
"(",
"\"SELECT ROW_COUNT()\"",
")",
".",
"fetchone",
"(",
")",
"[",
"0",
"]",
"if",
"get_count",
"else",
"None",
"self",
".",
"_log",
"(",
"query",
"[",
":",
"255",
"]",
")",
"return",
"count"
] | Deletes the table without cascading and without user prompt.
If this table has populated dependent tables, this will fail. | [
"Deletes",
"the",
"table",
"without",
"cascading",
"and",
"without",
"user",
"prompt",
".",
"If",
"this",
"table",
"has",
"populated",
"dependent",
"tables",
"this",
"will",
"fail",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/table.py#L313-L322 | train | 238,237 |
datajoint/datajoint-python | datajoint/table.py | Table._update | def _update(self, attrname, value=None):
"""
Updates a field in an existing tuple. This is not a datajoyous operation and should not be used
routinely. Relational database maintain referential integrity on the level of a tuple. Therefore,
the UPDATE operator can violate referential integrity. The datajoyous way to update information is
to delete the entire tuple and insert the entire update tuple.
Safety constraints:
1. self must be restricted to exactly one tuple
2. the update attribute must not be in primary key
Example
>>> (v2p.Mice() & key).update('mouse_dob', '2011-01-01')
>>> (v2p.Mice() & key).update( 'lens') # set the value to NULL
"""
if len(self) != 1:
raise DataJointError('Update is only allowed on one tuple at a time')
if attrname not in self.heading:
raise DataJointError('Invalid attribute name')
if attrname in self.heading.primary_key:
raise DataJointError('Cannot update a key value.')
attr = self.heading[attrname]
if attr.is_blob:
value = pack(value)
placeholder = '%s'
elif attr.numeric:
if value is None or np.isnan(np.float(value)): # nans are turned into NULLs
placeholder = 'NULL'
value = None
else:
placeholder = '%s'
value = str(int(value) if isinstance(value, bool) else value)
else:
placeholder = '%s'
command = "UPDATE {full_table_name} SET `{attrname}`={placeholder} {where_clause}".format(
full_table_name=self.from_clause,
attrname=attrname,
placeholder=placeholder,
where_clause=self.where_clause)
self.connection.query(command, args=(value, ) if value is not None else ()) | python | def _update(self, attrname, value=None):
"""
Updates a field in an existing tuple. This is not a datajoyous operation and should not be used
routinely. Relational database maintain referential integrity on the level of a tuple. Therefore,
the UPDATE operator can violate referential integrity. The datajoyous way to update information is
to delete the entire tuple and insert the entire update tuple.
Safety constraints:
1. self must be restricted to exactly one tuple
2. the update attribute must not be in primary key
Example
>>> (v2p.Mice() & key).update('mouse_dob', '2011-01-01')
>>> (v2p.Mice() & key).update( 'lens') # set the value to NULL
"""
if len(self) != 1:
raise DataJointError('Update is only allowed on one tuple at a time')
if attrname not in self.heading:
raise DataJointError('Invalid attribute name')
if attrname in self.heading.primary_key:
raise DataJointError('Cannot update a key value.')
attr = self.heading[attrname]
if attr.is_blob:
value = pack(value)
placeholder = '%s'
elif attr.numeric:
if value is None or np.isnan(np.float(value)): # nans are turned into NULLs
placeholder = 'NULL'
value = None
else:
placeholder = '%s'
value = str(int(value) if isinstance(value, bool) else value)
else:
placeholder = '%s'
command = "UPDATE {full_table_name} SET `{attrname}`={placeholder} {where_clause}".format(
full_table_name=self.from_clause,
attrname=attrname,
placeholder=placeholder,
where_clause=self.where_clause)
self.connection.query(command, args=(value, ) if value is not None else ()) | [
"def",
"_update",
"(",
"self",
",",
"attrname",
",",
"value",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
"!=",
"1",
":",
"raise",
"DataJointError",
"(",
"'Update is only allowed on one tuple at a time'",
")",
"if",
"attrname",
"not",
"in",
"self",
".",
"heading",
":",
"raise",
"DataJointError",
"(",
"'Invalid attribute name'",
")",
"if",
"attrname",
"in",
"self",
".",
"heading",
".",
"primary_key",
":",
"raise",
"DataJointError",
"(",
"'Cannot update a key value.'",
")",
"attr",
"=",
"self",
".",
"heading",
"[",
"attrname",
"]",
"if",
"attr",
".",
"is_blob",
":",
"value",
"=",
"pack",
"(",
"value",
")",
"placeholder",
"=",
"'%s'",
"elif",
"attr",
".",
"numeric",
":",
"if",
"value",
"is",
"None",
"or",
"np",
".",
"isnan",
"(",
"np",
".",
"float",
"(",
"value",
")",
")",
":",
"# nans are turned into NULLs",
"placeholder",
"=",
"'NULL'",
"value",
"=",
"None",
"else",
":",
"placeholder",
"=",
"'%s'",
"value",
"=",
"str",
"(",
"int",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
"else",
"value",
")",
"else",
":",
"placeholder",
"=",
"'%s'",
"command",
"=",
"\"UPDATE {full_table_name} SET `{attrname}`={placeholder} {where_clause}\"",
".",
"format",
"(",
"full_table_name",
"=",
"self",
".",
"from_clause",
",",
"attrname",
"=",
"attrname",
",",
"placeholder",
"=",
"placeholder",
",",
"where_clause",
"=",
"self",
".",
"where_clause",
")",
"self",
".",
"connection",
".",
"query",
"(",
"command",
",",
"args",
"=",
"(",
"value",
",",
")",
"if",
"value",
"is",
"not",
"None",
"else",
"(",
")",
")"
] | Updates a field in an existing tuple. This is not a datajoyous operation and should not be used
routinely. Relational database maintain referential integrity on the level of a tuple. Therefore,
the UPDATE operator can violate referential integrity. The datajoyous way to update information is
to delete the entire tuple and insert the entire update tuple.
Safety constraints:
1. self must be restricted to exactly one tuple
2. the update attribute must not be in primary key
Example
>>> (v2p.Mice() & key).update('mouse_dob', '2011-01-01')
>>> (v2p.Mice() & key).update( 'lens') # set the value to NULL | [
"Updates",
"a",
"field",
"in",
"an",
"existing",
"tuple",
".",
"This",
"is",
"not",
"a",
"datajoyous",
"operation",
"and",
"should",
"not",
"be",
"used",
"routinely",
".",
"Relational",
"database",
"maintain",
"referential",
"integrity",
"on",
"the",
"level",
"of",
"a",
"tuple",
".",
"Therefore",
"the",
"UPDATE",
"operator",
"can",
"violate",
"referential",
"integrity",
".",
"The",
"datajoyous",
"way",
"to",
"update",
"information",
"is",
"to",
"delete",
"the",
"entire",
"tuple",
"and",
"insert",
"the",
"entire",
"update",
"tuple",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/table.py#L525-L568 | train | 238,238 |
datajoint/datajoint-python | datajoint/expression.py | QueryExpression.where_clause | def where_clause(self):
"""
convert self.restriction to the SQL WHERE clause
"""
cond = self._make_condition(self.restriction)
return '' if cond is True else ' WHERE %s' % cond | python | def where_clause(self):
"""
convert self.restriction to the SQL WHERE clause
"""
cond = self._make_condition(self.restriction)
return '' if cond is True else ' WHERE %s' % cond | [
"def",
"where_clause",
"(",
"self",
")",
":",
"cond",
"=",
"self",
".",
"_make_condition",
"(",
"self",
".",
"restriction",
")",
"return",
"''",
"if",
"cond",
"is",
"True",
"else",
"' WHERE %s'",
"%",
"cond"
] | convert self.restriction to the SQL WHERE clause | [
"convert",
"self",
".",
"restriction",
"to",
"the",
"SQL",
"WHERE",
"clause"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L196-L201 | train | 238,239 |
datajoint/datajoint-python | datajoint/expression.py | QueryExpression.preview | def preview(self, limit=None, width=None):
"""
returns a preview of the contents of the query.
"""
heading = self.heading
rel = self.proj(*heading.non_blobs)
if limit is None:
limit = config['display.limit']
if width is None:
width = config['display.width']
tuples = rel.fetch(limit=limit+1, format="array")
has_more = len(tuples) > limit
tuples = tuples[:limit]
columns = heading.names
widths = {f: min(max([len(f)] +
[len(str(e)) for e in tuples[f]] if f in tuples.dtype.names else [len('=BLOB=')]) + 4, width) for f in columns}
templates = {f: '%%-%d.%ds' % (widths[f], widths[f]) for f in columns}
return (
' '.join([templates[f] % ('*' + f if f in rel.primary_key else f) for f in columns]) + '\n' +
' '.join(['+' + '-' * (widths[column] - 2) + '+' for column in columns]) + '\n' +
'\n'.join(' '.join(templates[f] % (tup[f] if f in tup.dtype.names else '=BLOB=')
for f in columns) for tup in tuples) +
('\n ...\n' if has_more else '\n') +
(' (Total: %d)\n' % len(rel) if config['display.show_tuple_count'] else '')) | python | def preview(self, limit=None, width=None):
"""
returns a preview of the contents of the query.
"""
heading = self.heading
rel = self.proj(*heading.non_blobs)
if limit is None:
limit = config['display.limit']
if width is None:
width = config['display.width']
tuples = rel.fetch(limit=limit+1, format="array")
has_more = len(tuples) > limit
tuples = tuples[:limit]
columns = heading.names
widths = {f: min(max([len(f)] +
[len(str(e)) for e in tuples[f]] if f in tuples.dtype.names else [len('=BLOB=')]) + 4, width) for f in columns}
templates = {f: '%%-%d.%ds' % (widths[f], widths[f]) for f in columns}
return (
' '.join([templates[f] % ('*' + f if f in rel.primary_key else f) for f in columns]) + '\n' +
' '.join(['+' + '-' * (widths[column] - 2) + '+' for column in columns]) + '\n' +
'\n'.join(' '.join(templates[f] % (tup[f] if f in tup.dtype.names else '=BLOB=')
for f in columns) for tup in tuples) +
('\n ...\n' if has_more else '\n') +
(' (Total: %d)\n' % len(rel) if config['display.show_tuple_count'] else '')) | [
"def",
"preview",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"width",
"=",
"None",
")",
":",
"heading",
"=",
"self",
".",
"heading",
"rel",
"=",
"self",
".",
"proj",
"(",
"*",
"heading",
".",
"non_blobs",
")",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"config",
"[",
"'display.limit'",
"]",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"config",
"[",
"'display.width'",
"]",
"tuples",
"=",
"rel",
".",
"fetch",
"(",
"limit",
"=",
"limit",
"+",
"1",
",",
"format",
"=",
"\"array\"",
")",
"has_more",
"=",
"len",
"(",
"tuples",
")",
">",
"limit",
"tuples",
"=",
"tuples",
"[",
":",
"limit",
"]",
"columns",
"=",
"heading",
".",
"names",
"widths",
"=",
"{",
"f",
":",
"min",
"(",
"max",
"(",
"[",
"len",
"(",
"f",
")",
"]",
"+",
"[",
"len",
"(",
"str",
"(",
"e",
")",
")",
"for",
"e",
"in",
"tuples",
"[",
"f",
"]",
"]",
"if",
"f",
"in",
"tuples",
".",
"dtype",
".",
"names",
"else",
"[",
"len",
"(",
"'=BLOB='",
")",
"]",
")",
"+",
"4",
",",
"width",
")",
"for",
"f",
"in",
"columns",
"}",
"templates",
"=",
"{",
"f",
":",
"'%%-%d.%ds'",
"%",
"(",
"widths",
"[",
"f",
"]",
",",
"widths",
"[",
"f",
"]",
")",
"for",
"f",
"in",
"columns",
"}",
"return",
"(",
"' '",
".",
"join",
"(",
"[",
"templates",
"[",
"f",
"]",
"%",
"(",
"'*'",
"+",
"f",
"if",
"f",
"in",
"rel",
".",
"primary_key",
"else",
"f",
")",
"for",
"f",
"in",
"columns",
"]",
")",
"+",
"'\\n'",
"+",
"' '",
".",
"join",
"(",
"[",
"'+'",
"+",
"'-'",
"*",
"(",
"widths",
"[",
"column",
"]",
"-",
"2",
")",
"+",
"'+'",
"for",
"column",
"in",
"columns",
"]",
")",
"+",
"'\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"' '",
".",
"join",
"(",
"templates",
"[",
"f",
"]",
"%",
"(",
"tup",
"[",
"f",
"]",
"if",
"f",
"in",
"tup",
".",
"dtype",
".",
"names",
"else",
"'=BLOB='",
")",
"for",
"f",
"in",
"columns",
")",
"for",
"tup",
"in",
"tuples",
")",
"+",
"(",
"'\\n ...\\n'",
"if",
"has_more",
"else",
"'\\n'",
")",
"+",
"(",
"' (Total: %d)\\n'",
"%",
"len",
"(",
"rel",
")",
"if",
"config",
"[",
"'display.show_tuple_count'",
"]",
"else",
"''",
")",
")"
] | returns a preview of the contents of the query. | [
"returns",
"a",
"preview",
"of",
"the",
"contents",
"of",
"the",
"query",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L382-L405 | train | 238,240 |
datajoint/datajoint-python | datajoint/expression.py | Join.make_argument_subquery | def make_argument_subquery(arg):
"""
Decide when a Join argument needs to be wrapped in a subquery
"""
return Subquery.create(arg) if isinstance(arg, (GroupBy, Projection)) or arg.restriction else arg | python | def make_argument_subquery(arg):
"""
Decide when a Join argument needs to be wrapped in a subquery
"""
return Subquery.create(arg) if isinstance(arg, (GroupBy, Projection)) or arg.restriction else arg | [
"def",
"make_argument_subquery",
"(",
"arg",
")",
":",
"return",
"Subquery",
".",
"create",
"(",
"arg",
")",
"if",
"isinstance",
"(",
"arg",
",",
"(",
"GroupBy",
",",
"Projection",
")",
")",
"or",
"arg",
".",
"restriction",
"else",
"arg"
] | Decide when a Join argument needs to be wrapped in a subquery | [
"Decide",
"when",
"a",
"Join",
"argument",
"needs",
"to",
"be",
"wrapped",
"in",
"a",
"subquery"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L606-L610 | train | 238,241 |
datajoint/datajoint-python | datajoint/expression.py | Projection._need_subquery | def _need_subquery(arg, attributes, named_attributes):
"""
Decide whether the projection argument needs to be wrapped in a subquery
"""
if arg.heading.expressions or arg.distinct: # argument has any renamed (computed) attributes
return True
restricting_attributes = arg.attributes_in_restriction()
return (not restricting_attributes.issubset(attributes) or # if any restricting attribute is projected out or
any(v.strip() in restricting_attributes for v in named_attributes.values())) | python | def _need_subquery(arg, attributes, named_attributes):
"""
Decide whether the projection argument needs to be wrapped in a subquery
"""
if arg.heading.expressions or arg.distinct: # argument has any renamed (computed) attributes
return True
restricting_attributes = arg.attributes_in_restriction()
return (not restricting_attributes.issubset(attributes) or # if any restricting attribute is projected out or
any(v.strip() in restricting_attributes for v in named_attributes.values())) | [
"def",
"_need_subquery",
"(",
"arg",
",",
"attributes",
",",
"named_attributes",
")",
":",
"if",
"arg",
".",
"heading",
".",
"expressions",
"or",
"arg",
".",
"distinct",
":",
"# argument has any renamed (computed) attributes",
"return",
"True",
"restricting_attributes",
"=",
"arg",
".",
"attributes_in_restriction",
"(",
")",
"return",
"(",
"not",
"restricting_attributes",
".",
"issubset",
"(",
"attributes",
")",
"or",
"# if any restricting attribute is projected out or",
"any",
"(",
"v",
".",
"strip",
"(",
")",
"in",
"restricting_attributes",
"for",
"v",
"in",
"named_attributes",
".",
"values",
"(",
")",
")",
")"
] | Decide whether the projection argument needs to be wrapped in a subquery | [
"Decide",
"whether",
"the",
"projection",
"argument",
"needs",
"to",
"be",
"wrapped",
"in",
"a",
"subquery"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L717-L725 | train | 238,242 |
datajoint/datajoint-python | datajoint/expression.py | Subquery.create | def create(cls, arg):
"""
construct a subquery from arg
"""
obj = cls()
obj._connection = arg.connection
obj._heading = arg.heading.make_subquery_heading()
obj._arg = arg
return obj | python | def create(cls, arg):
"""
construct a subquery from arg
"""
obj = cls()
obj._connection = arg.connection
obj._heading = arg.heading.make_subquery_heading()
obj._arg = arg
return obj | [
"def",
"create",
"(",
"cls",
",",
"arg",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"_connection",
"=",
"arg",
".",
"connection",
"obj",
".",
"_heading",
"=",
"arg",
".",
"heading",
".",
"make_subquery_heading",
"(",
")",
"obj",
".",
"_arg",
"=",
"arg",
"return",
"obj"
] | construct a subquery from arg | [
"construct",
"a",
"subquery",
"from",
"arg"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/expression.py#L800-L808 | train | 238,243 |
datajoint/datajoint-python | datajoint/utils.py | user_choice | def user_choice(prompt, choices=("yes", "no"), default=None):
"""
Prompts the user for confirmation. The default value, if any, is capitalized.
:param prompt: Information to display to the user.
:param choices: an iterable of possible choices.
:param default: default choice
:return: the user's choice
"""
assert default is None or default in choices
choice_list = ', '.join((choice.title() if choice == default else choice for choice in choices))
response = None
while response not in choices:
response = input(prompt + ' [' + choice_list + ']: ')
response = response.lower() if response else default
return response | python | def user_choice(prompt, choices=("yes", "no"), default=None):
"""
Prompts the user for confirmation. The default value, if any, is capitalized.
:param prompt: Information to display to the user.
:param choices: an iterable of possible choices.
:param default: default choice
:return: the user's choice
"""
assert default is None or default in choices
choice_list = ', '.join((choice.title() if choice == default else choice for choice in choices))
response = None
while response not in choices:
response = input(prompt + ' [' + choice_list + ']: ')
response = response.lower() if response else default
return response | [
"def",
"user_choice",
"(",
"prompt",
",",
"choices",
"=",
"(",
"\"yes\"",
",",
"\"no\"",
")",
",",
"default",
"=",
"None",
")",
":",
"assert",
"default",
"is",
"None",
"or",
"default",
"in",
"choices",
"choice_list",
"=",
"', '",
".",
"join",
"(",
"(",
"choice",
".",
"title",
"(",
")",
"if",
"choice",
"==",
"default",
"else",
"choice",
"for",
"choice",
"in",
"choices",
")",
")",
"response",
"=",
"None",
"while",
"response",
"not",
"in",
"choices",
":",
"response",
"=",
"input",
"(",
"prompt",
"+",
"' ['",
"+",
"choice_list",
"+",
"']: '",
")",
"response",
"=",
"response",
".",
"lower",
"(",
")",
"if",
"response",
"else",
"default",
"return",
"response"
] | Prompts the user for confirmation. The default value, if any, is capitalized.
:param prompt: Information to display to the user.
:param choices: an iterable of possible choices.
:param default: default choice
:return: the user's choice | [
"Prompts",
"the",
"user",
"for",
"confirmation",
".",
"The",
"default",
"value",
"if",
"any",
"is",
"capitalized",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/utils.py#L16-L31 | train | 238,244 |
datajoint/datajoint-python | datajoint/fetch.py | to_dicts | def to_dicts(recarray):
"""convert record array to a dictionaries"""
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist())) | python | def to_dicts(recarray):
"""convert record array to a dictionaries"""
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist())) | [
"def",
"to_dicts",
"(",
"recarray",
")",
":",
"for",
"rec",
"in",
"recarray",
":",
"yield",
"dict",
"(",
"zip",
"(",
"recarray",
".",
"dtype",
".",
"names",
",",
"rec",
".",
"tolist",
"(",
")",
")",
")"
] | convert record array to a dictionaries | [
"convert",
"record",
"array",
"to",
"a",
"dictionaries"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/fetch.py#L24-L27 | train | 238,245 |
datajoint/datajoint-python | datajoint/fetch.py | Fetch.keys | def keys(self, **kwargs):
"""
DEPRECATED
Iterator that returns primary keys as a sequence of dicts.
"""
warnings.warn('Use of `rel.fetch.keys()` notation is deprecated. '
'Please use `rel.fetch("KEY")` or `rel.fetch(dj.key)` for equivalent result', stacklevel=2)
yield from self._expression.proj().fetch(as_dict=True, **kwargs) | python | def keys(self, **kwargs):
"""
DEPRECATED
Iterator that returns primary keys as a sequence of dicts.
"""
warnings.warn('Use of `rel.fetch.keys()` notation is deprecated. '
'Please use `rel.fetch("KEY")` or `rel.fetch(dj.key)` for equivalent result', stacklevel=2)
yield from self._expression.proj().fetch(as_dict=True, **kwargs) | [
"def",
"keys",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'Use of `rel.fetch.keys()` notation is deprecated. '",
"'Please use `rel.fetch(\"KEY\")` or `rel.fetch(dj.key)` for equivalent result'",
",",
"stacklevel",
"=",
"2",
")",
"yield",
"from",
"self",
".",
"_expression",
".",
"proj",
"(",
")",
".",
"fetch",
"(",
"as_dict",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | DEPRECATED
Iterator that returns primary keys as a sequence of dicts. | [
"DEPRECATED",
"Iterator",
"that",
"returns",
"primary",
"keys",
"as",
"a",
"sequence",
"of",
"dicts",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/fetch.py#L131-L138 | train | 238,246 |
datajoint/datajoint-python | datajoint/hash.py | key_hash | def key_hash(key):
"""
32-byte hash used for lookup of primary keys of jobs
"""
hashed = hashlib.md5()
for k, v in sorted(key.items()):
hashed.update(str(v).encode())
return hashed.hexdigest() | python | def key_hash(key):
"""
32-byte hash used for lookup of primary keys of jobs
"""
hashed = hashlib.md5()
for k, v in sorted(key.items()):
hashed.update(str(v).encode())
return hashed.hexdigest() | [
"def",
"key_hash",
"(",
"key",
")",
":",
"hashed",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"key",
".",
"items",
"(",
")",
")",
":",
"hashed",
".",
"update",
"(",
"str",
"(",
"v",
")",
".",
"encode",
"(",
")",
")",
"return",
"hashed",
".",
"hexdigest",
"(",
")"
] | 32-byte hash used for lookup of primary keys of jobs | [
"32",
"-",
"byte",
"hash",
"used",
"for",
"lookup",
"of",
"primary",
"keys",
"of",
"jobs"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/hash.py#L5-L12 | train | 238,247 |
datajoint/datajoint-python | datajoint/connection.py | conn | def conn(host=None, user=None, password=None, init_fun=None, reset=False):
"""
Returns a persistent connection object to be shared by multiple modules.
If the connection is not yet established or reset=True, a new connection is set up.
If connection information is not provided, it is taken from config which takes the
information from dj_local_conf.json. If the password is not specified in that file
datajoint prompts for the password.
:param host: hostname
:param user: mysql user
:param password: mysql password
:param init_fun: initialization function
:param reset: whether the connection should be reset or not
"""
if not hasattr(conn, 'connection') or reset:
host = host if host is not None else config['database.host']
user = user if user is not None else config['database.user']
password = password if password is not None else config['database.password']
if user is None: # pragma: no cover
user = input("Please enter DataJoint username: ")
if password is None: # pragma: no cover
password = getpass(prompt="Please enter DataJoint password: ")
init_fun = init_fun if init_fun is not None else config['connection.init_function']
conn.connection = Connection(host, user, password, init_fun)
return conn.connection | python | def conn(host=None, user=None, password=None, init_fun=None, reset=False):
"""
Returns a persistent connection object to be shared by multiple modules.
If the connection is not yet established or reset=True, a new connection is set up.
If connection information is not provided, it is taken from config which takes the
information from dj_local_conf.json. If the password is not specified in that file
datajoint prompts for the password.
:param host: hostname
:param user: mysql user
:param password: mysql password
:param init_fun: initialization function
:param reset: whether the connection should be reset or not
"""
if not hasattr(conn, 'connection') or reset:
host = host if host is not None else config['database.host']
user = user if user is not None else config['database.user']
password = password if password is not None else config['database.password']
if user is None: # pragma: no cover
user = input("Please enter DataJoint username: ")
if password is None: # pragma: no cover
password = getpass(prompt="Please enter DataJoint password: ")
init_fun = init_fun if init_fun is not None else config['connection.init_function']
conn.connection = Connection(host, user, password, init_fun)
return conn.connection | [
"def",
"conn",
"(",
"host",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"init_fun",
"=",
"None",
",",
"reset",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"conn",
",",
"'connection'",
")",
"or",
"reset",
":",
"host",
"=",
"host",
"if",
"host",
"is",
"not",
"None",
"else",
"config",
"[",
"'database.host'",
"]",
"user",
"=",
"user",
"if",
"user",
"is",
"not",
"None",
"else",
"config",
"[",
"'database.user'",
"]",
"password",
"=",
"password",
"if",
"password",
"is",
"not",
"None",
"else",
"config",
"[",
"'database.password'",
"]",
"if",
"user",
"is",
"None",
":",
"# pragma: no cover",
"user",
"=",
"input",
"(",
"\"Please enter DataJoint username: \"",
")",
"if",
"password",
"is",
"None",
":",
"# pragma: no cover",
"password",
"=",
"getpass",
"(",
"prompt",
"=",
"\"Please enter DataJoint password: \"",
")",
"init_fun",
"=",
"init_fun",
"if",
"init_fun",
"is",
"not",
"None",
"else",
"config",
"[",
"'connection.init_function'",
"]",
"conn",
".",
"connection",
"=",
"Connection",
"(",
"host",
",",
"user",
",",
"password",
",",
"init_fun",
")",
"return",
"conn",
".",
"connection"
] | Returns a persistent connection object to be shared by multiple modules.
If the connection is not yet established or reset=True, a new connection is set up.
If connection information is not provided, it is taken from config which takes the
information from dj_local_conf.json. If the password is not specified in that file
datajoint prompts for the password.
:param host: hostname
:param user: mysql user
:param password: mysql password
:param init_fun: initialization function
:param reset: whether the connection should be reset or not | [
"Returns",
"a",
"persistent",
"connection",
"object",
"to",
"be",
"shared",
"by",
"multiple",
"modules",
".",
"If",
"the",
"connection",
"is",
"not",
"yet",
"established",
"or",
"reset",
"=",
"True",
"a",
"new",
"connection",
"is",
"set",
"up",
".",
"If",
"connection",
"information",
"is",
"not",
"provided",
"it",
"is",
"taken",
"from",
"config",
"which",
"takes",
"the",
"information",
"from",
"dj_local_conf",
".",
"json",
".",
"If",
"the",
"password",
"is",
"not",
"specified",
"in",
"that",
"file",
"datajoint",
"prompts",
"for",
"the",
"password",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/connection.py#L20-L44 | train | 238,248 |
datajoint/datajoint-python | datajoint/connection.py | Connection.connect | def connect(self):
"""
Connects to the database server.
"""
with warnings.catch_warnings():
warnings.filterwarnings('ignore', '.*deprecated.*')
self._conn = client.connect(
init_command=self.init_fun,
sql_mode="NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,"
"STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION",
charset=config['connection.charset'],
**self.conn_info)
self._conn.autocommit(True) | python | def connect(self):
"""
Connects to the database server.
"""
with warnings.catch_warnings():
warnings.filterwarnings('ignore', '.*deprecated.*')
self._conn = client.connect(
init_command=self.init_fun,
sql_mode="NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,"
"STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION",
charset=config['connection.charset'],
**self.conn_info)
self._conn.autocommit(True) | [
"def",
"connect",
"(",
"self",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
",",
"'.*deprecated.*'",
")",
"self",
".",
"_conn",
"=",
"client",
".",
"connect",
"(",
"init_command",
"=",
"self",
".",
"init_fun",
",",
"sql_mode",
"=",
"\"NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,\"",
"\"STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\"",
",",
"charset",
"=",
"config",
"[",
"'connection.charset'",
"]",
",",
"*",
"*",
"self",
".",
"conn_info",
")",
"self",
".",
"_conn",
".",
"autocommit",
"(",
"True",
")"
] | Connects to the database server. | [
"Connects",
"to",
"the",
"database",
"server",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/connection.py#L88-L100 | train | 238,249 |
datajoint/datajoint-python | datajoint/connection.py | Connection.start_transaction | def start_transaction(self):
"""
Starts a transaction error.
:raise DataJointError: if there is an ongoing transaction.
"""
if self.in_transaction:
raise DataJointError("Nested connections are not supported.")
self.query('START TRANSACTION WITH CONSISTENT SNAPSHOT')
self._in_transaction = True
logger.info("Transaction started") | python | def start_transaction(self):
"""
Starts a transaction error.
:raise DataJointError: if there is an ongoing transaction.
"""
if self.in_transaction:
raise DataJointError("Nested connections are not supported.")
self.query('START TRANSACTION WITH CONSISTENT SNAPSHOT')
self._in_transaction = True
logger.info("Transaction started") | [
"def",
"start_transaction",
"(",
"self",
")",
":",
"if",
"self",
".",
"in_transaction",
":",
"raise",
"DataJointError",
"(",
"\"Nested connections are not supported.\"",
")",
"self",
".",
"query",
"(",
"'START TRANSACTION WITH CONSISTENT SNAPSHOT'",
")",
"self",
".",
"_in_transaction",
"=",
"True",
"logger",
".",
"info",
"(",
"\"Transaction started\"",
")"
] | Starts a transaction error.
:raise DataJointError: if there is an ongoing transaction. | [
"Starts",
"a",
"transaction",
"error",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/connection.py#L185-L195 | train | 238,250 |
datajoint/datajoint-python | datajoint/settings.py | Config.save_global | def save_global(self, verbose=False):
"""
saves the settings in the global config file
"""
self.save(os.path.expanduser(os.path.join('~', GLOBALCONFIG)), verbose) | python | def save_global(self, verbose=False):
"""
saves the settings in the global config file
"""
self.save(os.path.expanduser(os.path.join('~', GLOBALCONFIG)), verbose) | [
"def",
"save_global",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"self",
".",
"save",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'~'",
",",
"GLOBALCONFIG",
")",
")",
",",
"verbose",
")"
] | saves the settings in the global config file | [
"saves",
"the",
"settings",
"in",
"the",
"global",
"config",
"file"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/settings.py#L121-L125 | train | 238,251 |
datajoint/datajoint-python | datajoint/heading.py | Attribute.todict | def todict(self):
"""Convert namedtuple to dict."""
return OrderedDict((name, self[i]) for i, name in enumerate(self._fields)) | python | def todict(self):
"""Convert namedtuple to dict."""
return OrderedDict((name, self[i]) for i, name in enumerate(self._fields)) | [
"def",
"todict",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"(",
"name",
",",
"self",
"[",
"i",
"]",
")",
"for",
"i",
",",
"name",
"in",
"enumerate",
"(",
"self",
".",
"_fields",
")",
")"
] | Convert namedtuple to dict. | [
"Convert",
"namedtuple",
"to",
"dict",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/heading.py#L20-L22 | train | 238,252 |
datajoint/datajoint-python | datajoint/heading.py | Heading.as_dtype | def as_dtype(self):
"""
represent the heading as a numpy dtype
"""
return np.dtype(dict(
names=self.names,
formats=[v.dtype for v in self.attributes.values()])) | python | def as_dtype(self):
"""
represent the heading as a numpy dtype
"""
return np.dtype(dict(
names=self.names,
formats=[v.dtype for v in self.attributes.values()])) | [
"def",
"as_dtype",
"(",
"self",
")",
":",
"return",
"np",
".",
"dtype",
"(",
"dict",
"(",
"names",
"=",
"self",
".",
"names",
",",
"formats",
"=",
"[",
"v",
".",
"dtype",
"for",
"v",
"in",
"self",
".",
"attributes",
".",
"values",
"(",
")",
"]",
")",
")"
] | represent the heading as a numpy dtype | [
"represent",
"the",
"heading",
"as",
"a",
"numpy",
"dtype"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/heading.py#L112-L118 | train | 238,253 |
datajoint/datajoint-python | datajoint/heading.py | Heading.as_sql | def as_sql(self):
"""
represent heading as SQL field list
"""
return ','.join('`%s`' % name if self.attributes[name].sql_expression is None
else '%s as `%s`' % (self.attributes[name].sql_expression, name)
for name in self.names) | python | def as_sql(self):
"""
represent heading as SQL field list
"""
return ','.join('`%s`' % name if self.attributes[name].sql_expression is None
else '%s as `%s`' % (self.attributes[name].sql_expression, name)
for name in self.names) | [
"def",
"as_sql",
"(",
"self",
")",
":",
"return",
"','",
".",
"join",
"(",
"'`%s`'",
"%",
"name",
"if",
"self",
".",
"attributes",
"[",
"name",
"]",
".",
"sql_expression",
"is",
"None",
"else",
"'%s as `%s`'",
"%",
"(",
"self",
".",
"attributes",
"[",
"name",
"]",
".",
"sql_expression",
",",
"name",
")",
"for",
"name",
"in",
"self",
".",
"names",
")"
] | represent heading as SQL field list | [
"represent",
"heading",
"as",
"SQL",
"field",
"list"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/heading.py#L121-L127 | train | 238,254 |
datajoint/datajoint-python | datajoint/heading.py | Heading.join | def join(self, other):
"""
Join two headings into a new one.
It assumes that self and other are headings that share no common dependent attributes.
"""
return Heading(
[self.attributes[name].todict() for name in self.primary_key] +
[other.attributes[name].todict() for name in other.primary_key if name not in self.primary_key] +
[self.attributes[name].todict() for name in self.dependent_attributes if name not in other.primary_key] +
[other.attributes[name].todict() for name in other.dependent_attributes if name not in self.primary_key]) | python | def join(self, other):
"""
Join two headings into a new one.
It assumes that self and other are headings that share no common dependent attributes.
"""
return Heading(
[self.attributes[name].todict() for name in self.primary_key] +
[other.attributes[name].todict() for name in other.primary_key if name not in self.primary_key] +
[self.attributes[name].todict() for name in self.dependent_attributes if name not in other.primary_key] +
[other.attributes[name].todict() for name in other.dependent_attributes if name not in self.primary_key]) | [
"def",
"join",
"(",
"self",
",",
"other",
")",
":",
"return",
"Heading",
"(",
"[",
"self",
".",
"attributes",
"[",
"name",
"]",
".",
"todict",
"(",
")",
"for",
"name",
"in",
"self",
".",
"primary_key",
"]",
"+",
"[",
"other",
".",
"attributes",
"[",
"name",
"]",
".",
"todict",
"(",
")",
"for",
"name",
"in",
"other",
".",
"primary_key",
"if",
"name",
"not",
"in",
"self",
".",
"primary_key",
"]",
"+",
"[",
"self",
".",
"attributes",
"[",
"name",
"]",
".",
"todict",
"(",
")",
"for",
"name",
"in",
"self",
".",
"dependent_attributes",
"if",
"name",
"not",
"in",
"other",
".",
"primary_key",
"]",
"+",
"[",
"other",
".",
"attributes",
"[",
"name",
"]",
".",
"todict",
"(",
")",
"for",
"name",
"in",
"other",
".",
"dependent_attributes",
"if",
"name",
"not",
"in",
"self",
".",
"primary_key",
"]",
")"
] | Join two headings into a new one.
It assumes that self and other are headings that share no common dependent attributes. | [
"Join",
"two",
"headings",
"into",
"a",
"new",
"one",
".",
"It",
"assumes",
"that",
"self",
"and",
"other",
"are",
"headings",
"that",
"share",
"no",
"common",
"dependent",
"attributes",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/heading.py#L271-L280 | train | 238,255 |
datajoint/datajoint-python | datajoint/heading.py | Heading.make_subquery_heading | def make_subquery_heading(self):
"""
Create a new heading with removed attribute sql_expressions.
Used by subqueries, which resolve the sql_expressions.
"""
return Heading(dict(v.todict(), sql_expression=None) for v in self.attributes.values()) | python | def make_subquery_heading(self):
"""
Create a new heading with removed attribute sql_expressions.
Used by subqueries, which resolve the sql_expressions.
"""
return Heading(dict(v.todict(), sql_expression=None) for v in self.attributes.values()) | [
"def",
"make_subquery_heading",
"(",
"self",
")",
":",
"return",
"Heading",
"(",
"dict",
"(",
"v",
".",
"todict",
"(",
")",
",",
"sql_expression",
"=",
"None",
")",
"for",
"v",
"in",
"self",
".",
"attributes",
".",
"values",
"(",
")",
")"
] | Create a new heading with removed attribute sql_expressions.
Used by subqueries, which resolve the sql_expressions. | [
"Create",
"a",
"new",
"heading",
"with",
"removed",
"attribute",
"sql_expressions",
".",
"Used",
"by",
"subqueries",
"which",
"resolve",
"the",
"sql_expressions",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/heading.py#L282-L287 | train | 238,256 |
datajoint/datajoint-python | datajoint/blob.py | BlobReader.squeeze | def squeeze(self, array):
"""
Simplify the given array as much as possible - squeeze out all singleton
dimensions and also convert a zero dimensional array into array scalar
"""
if not self._squeeze:
return array
array = array.copy()
array = array.squeeze()
if array.ndim == 0:
array = array[()]
return array | python | def squeeze(self, array):
"""
Simplify the given array as much as possible - squeeze out all singleton
dimensions and also convert a zero dimensional array into array scalar
"""
if not self._squeeze:
return array
array = array.copy()
array = array.squeeze()
if array.ndim == 0:
array = array[()]
return array | [
"def",
"squeeze",
"(",
"self",
",",
"array",
")",
":",
"if",
"not",
"self",
".",
"_squeeze",
":",
"return",
"array",
"array",
"=",
"array",
".",
"copy",
"(",
")",
"array",
"=",
"array",
".",
"squeeze",
"(",
")",
"if",
"array",
".",
"ndim",
"==",
"0",
":",
"array",
"=",
"array",
"[",
"(",
")",
"]",
"return",
"array"
] | Simplify the given array as much as possible - squeeze out all singleton
dimensions and also convert a zero dimensional array into array scalar | [
"Simplify",
"the",
"given",
"array",
"as",
"much",
"as",
"possible",
"-",
"squeeze",
"out",
"all",
"singleton",
"dimensions",
"and",
"also",
"convert",
"a",
"zero",
"dimensional",
"array",
"into",
"array",
"scalar"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/blob.py#L152-L163 | train | 238,257 |
datajoint/datajoint-python | datajoint/blob.py | BlobReader.read_string | def read_string(self, advance=True):
"""
Read a string terminated by null byte '\0'. The returned string
object is ASCII decoded, and will not include the terminating null byte.
"""
target = self._blob.find(b'\0', self.pos)
assert target >= self._pos
data = self._blob[self._pos:target]
if advance:
self._pos = target + 1
return data.decode('ascii') | python | def read_string(self, advance=True):
"""
Read a string terminated by null byte '\0'. The returned string
object is ASCII decoded, and will not include the terminating null byte.
"""
target = self._blob.find(b'\0', self.pos)
assert target >= self._pos
data = self._blob[self._pos:target]
if advance:
self._pos = target + 1
return data.decode('ascii') | [
"def",
"read_string",
"(",
"self",
",",
"advance",
"=",
"True",
")",
":",
"target",
"=",
"self",
".",
"_blob",
".",
"find",
"(",
"b'\\0'",
",",
"self",
".",
"pos",
")",
"assert",
"target",
">=",
"self",
".",
"_pos",
"data",
"=",
"self",
".",
"_blob",
"[",
"self",
".",
"_pos",
":",
"target",
"]",
"if",
"advance",
":",
"self",
".",
"_pos",
"=",
"target",
"+",
"1",
"return",
"data",
".",
"decode",
"(",
"'ascii'",
")"
] | Read a string terminated by null byte '\0'. The returned string
object is ASCII decoded, and will not include the terminating null byte. | [
"Read",
"a",
"string",
"terminated",
"by",
"null",
"byte",
"\\",
"0",
".",
"The",
"returned",
"string",
"object",
"is",
"ASCII",
"decoded",
"and",
"will",
"not",
"include",
"the",
"terminating",
"null",
"byte",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/blob.py#L180-L190 | train | 238,258 |
datajoint/datajoint-python | datajoint/blob.py | BlobReader.read_value | def read_value(self, dtype='uint64', count=1, advance=True):
"""
Read one or more scalars of the indicated dtype. Count specifies the number of
scalars to be read in.
"""
data = np.frombuffer(self._blob, dtype=dtype, count=count, offset=self.pos)
if advance:
# probably the same thing as data.nbytes * 8
self._pos += data.dtype.itemsize * data.size
if count == 1:
data = data[0]
return data | python | def read_value(self, dtype='uint64', count=1, advance=True):
"""
Read one or more scalars of the indicated dtype. Count specifies the number of
scalars to be read in.
"""
data = np.frombuffer(self._blob, dtype=dtype, count=count, offset=self.pos)
if advance:
# probably the same thing as data.nbytes * 8
self._pos += data.dtype.itemsize * data.size
if count == 1:
data = data[0]
return data | [
"def",
"read_value",
"(",
"self",
",",
"dtype",
"=",
"'uint64'",
",",
"count",
"=",
"1",
",",
"advance",
"=",
"True",
")",
":",
"data",
"=",
"np",
".",
"frombuffer",
"(",
"self",
".",
"_blob",
",",
"dtype",
"=",
"dtype",
",",
"count",
"=",
"count",
",",
"offset",
"=",
"self",
".",
"pos",
")",
"if",
"advance",
":",
"# probably the same thing as data.nbytes * 8",
"self",
".",
"_pos",
"+=",
"data",
".",
"dtype",
".",
"itemsize",
"*",
"data",
".",
"size",
"if",
"count",
"==",
"1",
":",
"data",
"=",
"data",
"[",
"0",
"]",
"return",
"data"
] | Read one or more scalars of the indicated dtype. Count specifies the number of
scalars to be read in. | [
"Read",
"one",
"or",
"more",
"scalars",
"of",
"the",
"indicated",
"dtype",
".",
"Count",
"specifies",
"the",
"number",
"of",
"scalars",
"to",
"be",
"read",
"in",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/blob.py#L192-L203 | train | 238,259 |
datajoint/datajoint-python | datajoint/external.py | ExternalTable.put | def put(self, store, obj):
"""
put an object in external store
"""
spec = self._get_store_spec(store)
blob = pack(obj)
blob_hash = long_hash(blob) + store[len('external-'):]
if spec['protocol'] == 'file':
folder = os.path.join(spec['location'], self.database)
full_path = os.path.join(folder, blob_hash)
if not os.path.isfile(full_path):
try:
safe_write(full_path, blob)
except FileNotFoundError:
os.makedirs(folder)
safe_write(full_path, blob)
elif spec['protocol'] == 's3':
S3Folder(database=self.database, **spec).put(blob_hash, blob)
else:
raise DataJointError('Unknown external storage protocol {protocol} for {store}'.format(
store=store, protocol=spec['protocol']))
# insert tracking info
self.connection.query(
"INSERT INTO {tab} (hash, size) VALUES ('{hash}', {size}) "
"ON DUPLICATE KEY UPDATE timestamp=CURRENT_TIMESTAMP".format(
tab=self.full_table_name,
hash=blob_hash,
size=len(blob)))
return blob_hash | python | def put(self, store, obj):
"""
put an object in external store
"""
spec = self._get_store_spec(store)
blob = pack(obj)
blob_hash = long_hash(blob) + store[len('external-'):]
if spec['protocol'] == 'file':
folder = os.path.join(spec['location'], self.database)
full_path = os.path.join(folder, blob_hash)
if not os.path.isfile(full_path):
try:
safe_write(full_path, blob)
except FileNotFoundError:
os.makedirs(folder)
safe_write(full_path, blob)
elif spec['protocol'] == 's3':
S3Folder(database=self.database, **spec).put(blob_hash, blob)
else:
raise DataJointError('Unknown external storage protocol {protocol} for {store}'.format(
store=store, protocol=spec['protocol']))
# insert tracking info
self.connection.query(
"INSERT INTO {tab} (hash, size) VALUES ('{hash}', {size}) "
"ON DUPLICATE KEY UPDATE timestamp=CURRENT_TIMESTAMP".format(
tab=self.full_table_name,
hash=blob_hash,
size=len(blob)))
return blob_hash | [
"def",
"put",
"(",
"self",
",",
"store",
",",
"obj",
")",
":",
"spec",
"=",
"self",
".",
"_get_store_spec",
"(",
"store",
")",
"blob",
"=",
"pack",
"(",
"obj",
")",
"blob_hash",
"=",
"long_hash",
"(",
"blob",
")",
"+",
"store",
"[",
"len",
"(",
"'external-'",
")",
":",
"]",
"if",
"spec",
"[",
"'protocol'",
"]",
"==",
"'file'",
":",
"folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"spec",
"[",
"'location'",
"]",
",",
"self",
".",
"database",
")",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"blob_hash",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"full_path",
")",
":",
"try",
":",
"safe_write",
"(",
"full_path",
",",
"blob",
")",
"except",
"FileNotFoundError",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"safe_write",
"(",
"full_path",
",",
"blob",
")",
"elif",
"spec",
"[",
"'protocol'",
"]",
"==",
"'s3'",
":",
"S3Folder",
"(",
"database",
"=",
"self",
".",
"database",
",",
"*",
"*",
"spec",
")",
".",
"put",
"(",
"blob_hash",
",",
"blob",
")",
"else",
":",
"raise",
"DataJointError",
"(",
"'Unknown external storage protocol {protocol} for {store}'",
".",
"format",
"(",
"store",
"=",
"store",
",",
"protocol",
"=",
"spec",
"[",
"'protocol'",
"]",
")",
")",
"# insert tracking info",
"self",
".",
"connection",
".",
"query",
"(",
"\"INSERT INTO {tab} (hash, size) VALUES ('{hash}', {size}) \"",
"\"ON DUPLICATE KEY UPDATE timestamp=CURRENT_TIMESTAMP\"",
".",
"format",
"(",
"tab",
"=",
"self",
".",
"full_table_name",
",",
"hash",
"=",
"blob_hash",
",",
"size",
"=",
"len",
"(",
"blob",
")",
")",
")",
"return",
"blob_hash"
] | put an object in external store | [
"put",
"an",
"object",
"in",
"external",
"store"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/external.py#L45-L74 | train | 238,260 |
datajoint/datajoint-python | datajoint/external.py | ExternalTable.get | def get(self, blob_hash):
"""
get an object from external store.
Does not need to check whether it's in the table.
"""
if blob_hash is None:
return None
store = blob_hash[STORE_HASH_LENGTH:]
store = 'external' + ('-' if store else '') + store
cache_folder = config.get('cache', None)
blob = None
if cache_folder:
try:
with open(os.path.join(cache_folder, blob_hash), 'rb') as f:
blob = f.read()
except FileNotFoundError:
pass
if blob is None:
spec = self._get_store_spec(store)
if spec['protocol'] == 'file':
full_path = os.path.join(spec['location'], self.database, blob_hash)
try:
with open(full_path, 'rb') as f:
blob = f.read()
except FileNotFoundError:
raise DataJointError('Lost access to external blob %s.' % full_path) from None
elif spec['protocol'] == 's3':
try:
blob = S3Folder(database=self.database, **spec).get(blob_hash)
except TypeError:
raise DataJointError('External store {store} configuration is incomplete.'.format(store=store))
else:
raise DataJointError('Unknown external storage protocol "%s"' % spec['protocol'])
if cache_folder:
if not os.path.exists(cache_folder):
os.makedirs(cache_folder)
safe_write(os.path.join(cache_folder, blob_hash), blob)
return unpack(blob) | python | def get(self, blob_hash):
"""
get an object from external store.
Does not need to check whether it's in the table.
"""
if blob_hash is None:
return None
store = blob_hash[STORE_HASH_LENGTH:]
store = 'external' + ('-' if store else '') + store
cache_folder = config.get('cache', None)
blob = None
if cache_folder:
try:
with open(os.path.join(cache_folder, blob_hash), 'rb') as f:
blob = f.read()
except FileNotFoundError:
pass
if blob is None:
spec = self._get_store_spec(store)
if spec['protocol'] == 'file':
full_path = os.path.join(spec['location'], self.database, blob_hash)
try:
with open(full_path, 'rb') as f:
blob = f.read()
except FileNotFoundError:
raise DataJointError('Lost access to external blob %s.' % full_path) from None
elif spec['protocol'] == 's3':
try:
blob = S3Folder(database=self.database, **spec).get(blob_hash)
except TypeError:
raise DataJointError('External store {store} configuration is incomplete.'.format(store=store))
else:
raise DataJointError('Unknown external storage protocol "%s"' % spec['protocol'])
if cache_folder:
if not os.path.exists(cache_folder):
os.makedirs(cache_folder)
safe_write(os.path.join(cache_folder, blob_hash), blob)
return unpack(blob) | [
"def",
"get",
"(",
"self",
",",
"blob_hash",
")",
":",
"if",
"blob_hash",
"is",
"None",
":",
"return",
"None",
"store",
"=",
"blob_hash",
"[",
"STORE_HASH_LENGTH",
":",
"]",
"store",
"=",
"'external'",
"+",
"(",
"'-'",
"if",
"store",
"else",
"''",
")",
"+",
"store",
"cache_folder",
"=",
"config",
".",
"get",
"(",
"'cache'",
",",
"None",
")",
"blob",
"=",
"None",
"if",
"cache_folder",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cache_folder",
",",
"blob_hash",
")",
",",
"'rb'",
")",
"as",
"f",
":",
"blob",
"=",
"f",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"pass",
"if",
"blob",
"is",
"None",
":",
"spec",
"=",
"self",
".",
"_get_store_spec",
"(",
"store",
")",
"if",
"spec",
"[",
"'protocol'",
"]",
"==",
"'file'",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"spec",
"[",
"'location'",
"]",
",",
"self",
".",
"database",
",",
"blob_hash",
")",
"try",
":",
"with",
"open",
"(",
"full_path",
",",
"'rb'",
")",
"as",
"f",
":",
"blob",
"=",
"f",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"raise",
"DataJointError",
"(",
"'Lost access to external blob %s.'",
"%",
"full_path",
")",
"from",
"None",
"elif",
"spec",
"[",
"'protocol'",
"]",
"==",
"'s3'",
":",
"try",
":",
"blob",
"=",
"S3Folder",
"(",
"database",
"=",
"self",
".",
"database",
",",
"*",
"*",
"spec",
")",
".",
"get",
"(",
"blob_hash",
")",
"except",
"TypeError",
":",
"raise",
"DataJointError",
"(",
"'External store {store} configuration is incomplete.'",
".",
"format",
"(",
"store",
"=",
"store",
")",
")",
"else",
":",
"raise",
"DataJointError",
"(",
"'Unknown external storage protocol \"%s\"'",
"%",
"spec",
"[",
"'protocol'",
"]",
")",
"if",
"cache_folder",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cache_folder",
")",
":",
"os",
".",
"makedirs",
"(",
"cache_folder",
")",
"safe_write",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cache_folder",
",",
"blob_hash",
")",
",",
"blob",
")",
"return",
"unpack",
"(",
"blob",
")"
] | get an object from external store.
Does not need to check whether it's in the table. | [
"get",
"an",
"object",
"from",
"external",
"store",
".",
"Does",
"not",
"need",
"to",
"check",
"whether",
"it",
"s",
"in",
"the",
"table",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/external.py#L76-L118 | train | 238,261 |
datajoint/datajoint-python | datajoint/external.py | ExternalTable.delete_garbage | def delete_garbage(self):
"""
Delete items that are no longer referenced.
This operation is safe to perform at any time.
"""
self.connection.query(
"DELETE FROM `{db}`.`{tab}` WHERE ".format(tab=self.table_name, db=self.database) +
" AND ".join(
'hash NOT IN (SELECT {column_name} FROM {referencing_table})'.format(**ref)
for ref in self.references) or "TRUE")
print('Deleted %d items' % self.connection.query("SELECT ROW_COUNT()").fetchone()[0]) | python | def delete_garbage(self):
"""
Delete items that are no longer referenced.
This operation is safe to perform at any time.
"""
self.connection.query(
"DELETE FROM `{db}`.`{tab}` WHERE ".format(tab=self.table_name, db=self.database) +
" AND ".join(
'hash NOT IN (SELECT {column_name} FROM {referencing_table})'.format(**ref)
for ref in self.references) or "TRUE")
print('Deleted %d items' % self.connection.query("SELECT ROW_COUNT()").fetchone()[0]) | [
"def",
"delete_garbage",
"(",
"self",
")",
":",
"self",
".",
"connection",
".",
"query",
"(",
"\"DELETE FROM `{db}`.`{tab}` WHERE \"",
".",
"format",
"(",
"tab",
"=",
"self",
".",
"table_name",
",",
"db",
"=",
"self",
".",
"database",
")",
"+",
"\" AND \"",
".",
"join",
"(",
"'hash NOT IN (SELECT {column_name} FROM {referencing_table})'",
".",
"format",
"(",
"*",
"*",
"ref",
")",
"for",
"ref",
"in",
"self",
".",
"references",
")",
"or",
"\"TRUE\"",
")",
"print",
"(",
"'Deleted %d items'",
"%",
"self",
".",
"connection",
".",
"query",
"(",
"\"SELECT ROW_COUNT()\"",
")",
".",
"fetchone",
"(",
")",
"[",
"0",
"]",
")"
] | Delete items that are no longer referenced.
This operation is safe to perform at any time. | [
"Delete",
"items",
"that",
"are",
"no",
"longer",
"referenced",
".",
"This",
"operation",
"is",
"safe",
"to",
"perform",
"at",
"any",
"time",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/external.py#L147-L157 | train | 238,262 |
datajoint/datajoint-python | datajoint/external.py | ExternalTable.clean_store | def clean_store(self, store, display_progress=True):
"""
Clean unused data in an external storage repository from unused blobs.
This must be performed after delete_garbage during low-usage periods to reduce risks of data loss.
"""
spec = self._get_store_spec(store)
progress = tqdm if display_progress else lambda x: x
if spec['protocol'] == 'file':
folder = os.path.join(spec['location'], self.database)
delete_list = set(os.listdir(folder)).difference(self.fetch('hash'))
print('Deleting %d unused items from %s' % (len(delete_list), folder), flush=True)
for f in progress(delete_list):
os.remove(os.path.join(folder, f))
elif spec['protocol'] == 's3':
try:
S3Folder(database=self.database, **spec).clean(self.fetch('hash'))
except TypeError:
raise DataJointError('External store {store} configuration is incomplete.'.format(store=store)) | python | def clean_store(self, store, display_progress=True):
"""
Clean unused data in an external storage repository from unused blobs.
This must be performed after delete_garbage during low-usage periods to reduce risks of data loss.
"""
spec = self._get_store_spec(store)
progress = tqdm if display_progress else lambda x: x
if spec['protocol'] == 'file':
folder = os.path.join(spec['location'], self.database)
delete_list = set(os.listdir(folder)).difference(self.fetch('hash'))
print('Deleting %d unused items from %s' % (len(delete_list), folder), flush=True)
for f in progress(delete_list):
os.remove(os.path.join(folder, f))
elif spec['protocol'] == 's3':
try:
S3Folder(database=self.database, **spec).clean(self.fetch('hash'))
except TypeError:
raise DataJointError('External store {store} configuration is incomplete.'.format(store=store)) | [
"def",
"clean_store",
"(",
"self",
",",
"store",
",",
"display_progress",
"=",
"True",
")",
":",
"spec",
"=",
"self",
".",
"_get_store_spec",
"(",
"store",
")",
"progress",
"=",
"tqdm",
"if",
"display_progress",
"else",
"lambda",
"x",
":",
"x",
"if",
"spec",
"[",
"'protocol'",
"]",
"==",
"'file'",
":",
"folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"spec",
"[",
"'location'",
"]",
",",
"self",
".",
"database",
")",
"delete_list",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"folder",
")",
")",
".",
"difference",
"(",
"self",
".",
"fetch",
"(",
"'hash'",
")",
")",
"print",
"(",
"'Deleting %d unused items from %s'",
"%",
"(",
"len",
"(",
"delete_list",
")",
",",
"folder",
")",
",",
"flush",
"=",
"True",
")",
"for",
"f",
"in",
"progress",
"(",
"delete_list",
")",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"f",
")",
")",
"elif",
"spec",
"[",
"'protocol'",
"]",
"==",
"'s3'",
":",
"try",
":",
"S3Folder",
"(",
"database",
"=",
"self",
".",
"database",
",",
"*",
"*",
"spec",
")",
".",
"clean",
"(",
"self",
".",
"fetch",
"(",
"'hash'",
")",
")",
"except",
"TypeError",
":",
"raise",
"DataJointError",
"(",
"'External store {store} configuration is incomplete.'",
".",
"format",
"(",
"store",
"=",
"store",
")",
")"
] | Clean unused data in an external storage repository from unused blobs.
This must be performed after delete_garbage during low-usage periods to reduce risks of data loss. | [
"Clean",
"unused",
"data",
"in",
"an",
"external",
"storage",
"repository",
"from",
"unused",
"blobs",
".",
"This",
"must",
"be",
"performed",
"after",
"delete_garbage",
"during",
"low",
"-",
"usage",
"periods",
"to",
"reduce",
"risks",
"of",
"data",
"loss",
"."
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/external.py#L159-L176 | train | 238,263 |
datajoint/datajoint-python | datajoint/errors.py | is_connection_error | def is_connection_error(e):
"""
Checks if error e pertains to a connection issue
"""
return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
(isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values()) | python | def is_connection_error(e):
"""
Checks if error e pertains to a connection issue
"""
return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
(isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values()) | [
"def",
"is_connection_error",
"(",
"e",
")",
":",
"return",
"(",
"isinstance",
"(",
"e",
",",
"err",
".",
"InterfaceError",
")",
"and",
"e",
".",
"args",
"[",
"0",
"]",
"==",
"\"(0, '')\"",
")",
"or",
"(",
"isinstance",
"(",
"e",
",",
"err",
".",
"OperationalError",
")",
"and",
"e",
".",
"args",
"[",
"0",
"]",
"in",
"operation_error_codes",
".",
"values",
"(",
")",
")"
] | Checks if error e pertains to a connection issue | [
"Checks",
"if",
"error",
"e",
"pertains",
"to",
"a",
"connection",
"issue"
] | 4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/errors.py#L18-L23 | train | 238,264 |
python-hyper/brotlipy | src/brotli/brotli.py | decompress | def decompress(data):
"""
Decompress a complete Brotli-compressed string.
:param data: A bytestring containing Brotli-compressed data.
"""
d = Decompressor()
data = d.decompress(data)
d.finish()
return data | python | def decompress(data):
"""
Decompress a complete Brotli-compressed string.
:param data: A bytestring containing Brotli-compressed data.
"""
d = Decompressor()
data = d.decompress(data)
d.finish()
return data | [
"def",
"decompress",
"(",
"data",
")",
":",
"d",
"=",
"Decompressor",
"(",
")",
"data",
"=",
"d",
".",
"decompress",
"(",
"data",
")",
"d",
".",
"finish",
"(",
")",
"return",
"data"
] | Decompress a complete Brotli-compressed string.
:param data: A bytestring containing Brotli-compressed data. | [
"Decompress",
"a",
"complete",
"Brotli",
"-",
"compressed",
"string",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L82-L91 | train | 238,265 |
python-hyper/brotlipy | src/brotli/brotli.py | compress | def compress(data,
mode=DEFAULT_MODE,
quality=lib.BROTLI_DEFAULT_QUALITY,
lgwin=lib.BROTLI_DEFAULT_WINDOW,
lgblock=0,
dictionary=b''):
"""
Compress a string using Brotli.
.. versionchanged:: 0.5.0
Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary``
parameters.
:param data: A bytestring containing the data to compress.
:type data: ``bytes``
:param mode: The encoder mode.
:type mode: :class:`BrotliEncoderMode` or ``int``
:param quality: Controls the compression-speed vs compression-density
tradeoffs. The higher the quality, the slower the compression. The
range of this value is 0 to 11.
:type quality: ``int``
:param lgwin: The base-2 logarithm of the sliding window size. The range of
this value is 10 to 24.
:type lgwin: ``int``
:param lgblock: The base-2 logarithm of the maximum input block size. The
range of this value is 16 to 24. If set to 0, the value will be set
based on ``quality``.
:type lgblock: ``int``
:param dictionary: A pre-set dictionary for LZ77. Please use this with
caution: if a dictionary is used for compression, the same dictionary
**must** be used for decompression!
:type dictionary: ``bytes``
:returns: The compressed bytestring.
:rtype: ``bytes``
"""
# This method uses private variables on the Compressor object, and
# generally does a whole lot of stuff that's not supported by the public
# API. The goal here is to minimise the number of allocations and copies
# we have to do. Users should prefer this method over the Compressor if
# they know they have single-shot data.
compressor = Compressor(
mode=mode,
quality=quality,
lgwin=lgwin,
lgblock=lgblock,
dictionary=dictionary
)
compressed_data = compressor._compress(data, lib.BROTLI_OPERATION_FINISH)
assert lib.BrotliEncoderIsFinished(compressor._encoder) == lib.BROTLI_TRUE
assert (
lib.BrotliEncoderHasMoreOutput(compressor._encoder) == lib.BROTLI_FALSE
)
return compressed_data | python | def compress(data,
mode=DEFAULT_MODE,
quality=lib.BROTLI_DEFAULT_QUALITY,
lgwin=lib.BROTLI_DEFAULT_WINDOW,
lgblock=0,
dictionary=b''):
"""
Compress a string using Brotli.
.. versionchanged:: 0.5.0
Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary``
parameters.
:param data: A bytestring containing the data to compress.
:type data: ``bytes``
:param mode: The encoder mode.
:type mode: :class:`BrotliEncoderMode` or ``int``
:param quality: Controls the compression-speed vs compression-density
tradeoffs. The higher the quality, the slower the compression. The
range of this value is 0 to 11.
:type quality: ``int``
:param lgwin: The base-2 logarithm of the sliding window size. The range of
this value is 10 to 24.
:type lgwin: ``int``
:param lgblock: The base-2 logarithm of the maximum input block size. The
range of this value is 16 to 24. If set to 0, the value will be set
based on ``quality``.
:type lgblock: ``int``
:param dictionary: A pre-set dictionary for LZ77. Please use this with
caution: if a dictionary is used for compression, the same dictionary
**must** be used for decompression!
:type dictionary: ``bytes``
:returns: The compressed bytestring.
:rtype: ``bytes``
"""
# This method uses private variables on the Compressor object, and
# generally does a whole lot of stuff that's not supported by the public
# API. The goal here is to minimise the number of allocations and copies
# we have to do. Users should prefer this method over the Compressor if
# they know they have single-shot data.
compressor = Compressor(
mode=mode,
quality=quality,
lgwin=lgwin,
lgblock=lgblock,
dictionary=dictionary
)
compressed_data = compressor._compress(data, lib.BROTLI_OPERATION_FINISH)
assert lib.BrotliEncoderIsFinished(compressor._encoder) == lib.BROTLI_TRUE
assert (
lib.BrotliEncoderHasMoreOutput(compressor._encoder) == lib.BROTLI_FALSE
)
return compressed_data | [
"def",
"compress",
"(",
"data",
",",
"mode",
"=",
"DEFAULT_MODE",
",",
"quality",
"=",
"lib",
".",
"BROTLI_DEFAULT_QUALITY",
",",
"lgwin",
"=",
"lib",
".",
"BROTLI_DEFAULT_WINDOW",
",",
"lgblock",
"=",
"0",
",",
"dictionary",
"=",
"b''",
")",
":",
"# This method uses private variables on the Compressor object, and",
"# generally does a whole lot of stuff that's not supported by the public",
"# API. The goal here is to minimise the number of allocations and copies",
"# we have to do. Users should prefer this method over the Compressor if",
"# they know they have single-shot data.",
"compressor",
"=",
"Compressor",
"(",
"mode",
"=",
"mode",
",",
"quality",
"=",
"quality",
",",
"lgwin",
"=",
"lgwin",
",",
"lgblock",
"=",
"lgblock",
",",
"dictionary",
"=",
"dictionary",
")",
"compressed_data",
"=",
"compressor",
".",
"_compress",
"(",
"data",
",",
"lib",
".",
"BROTLI_OPERATION_FINISH",
")",
"assert",
"lib",
".",
"BrotliEncoderIsFinished",
"(",
"compressor",
".",
"_encoder",
")",
"==",
"lib",
".",
"BROTLI_TRUE",
"assert",
"(",
"lib",
".",
"BrotliEncoderHasMoreOutput",
"(",
"compressor",
".",
"_encoder",
")",
"==",
"lib",
".",
"BROTLI_FALSE",
")",
"return",
"compressed_data"
] | Compress a string using Brotli.
.. versionchanged:: 0.5.0
Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary``
parameters.
:param data: A bytestring containing the data to compress.
:type data: ``bytes``
:param mode: The encoder mode.
:type mode: :class:`BrotliEncoderMode` or ``int``
:param quality: Controls the compression-speed vs compression-density
tradeoffs. The higher the quality, the slower the compression. The
range of this value is 0 to 11.
:type quality: ``int``
:param lgwin: The base-2 logarithm of the sliding window size. The range of
this value is 10 to 24.
:type lgwin: ``int``
:param lgblock: The base-2 logarithm of the maximum input block size. The
range of this value is 16 to 24. If set to 0, the value will be set
based on ``quality``.
:type lgblock: ``int``
:param dictionary: A pre-set dictionary for LZ77. Please use this with
caution: if a dictionary is used for compression, the same dictionary
**must** be used for decompression!
:type dictionary: ``bytes``
:returns: The compressed bytestring.
:rtype: ``bytes`` | [
"Compress",
"a",
"string",
"using",
"Brotli",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L94-L152 | train | 238,266 |
python-hyper/brotlipy | src/brotli/brotli.py | Compressor._compress | def _compress(self, data, operation):
"""
This private method compresses some data in a given mode. This is used
because almost all of the code uses the exact same setup. It wouldn't
have to, but it doesn't hurt at all.
"""
# The 'algorithm' for working out how big to make this buffer is from
# the Brotli source code, brotlimodule.cc.
original_output_size = int(
math.ceil(len(data) + (len(data) >> 2) + 10240)
)
available_out = ffi.new("size_t *")
available_out[0] = original_output_size
output_buffer = ffi.new("uint8_t []", available_out[0])
ptr_to_output_buffer = ffi.new("uint8_t **", output_buffer)
input_size = ffi.new("size_t *", len(data))
input_buffer = ffi.new("uint8_t []", data)
ptr_to_input_buffer = ffi.new("uint8_t **", input_buffer)
rc = lib.BrotliEncoderCompressStream(
self._encoder,
operation,
input_size,
ptr_to_input_buffer,
available_out,
ptr_to_output_buffer,
ffi.NULL
)
if rc != lib.BROTLI_TRUE: # pragma: no cover
raise Error("Error encountered compressing data.")
assert not input_size[0]
size_of_output = original_output_size - available_out[0]
return ffi.buffer(output_buffer, size_of_output)[:] | python | def _compress(self, data, operation):
"""
This private method compresses some data in a given mode. This is used
because almost all of the code uses the exact same setup. It wouldn't
have to, but it doesn't hurt at all.
"""
# The 'algorithm' for working out how big to make this buffer is from
# the Brotli source code, brotlimodule.cc.
original_output_size = int(
math.ceil(len(data) + (len(data) >> 2) + 10240)
)
available_out = ffi.new("size_t *")
available_out[0] = original_output_size
output_buffer = ffi.new("uint8_t []", available_out[0])
ptr_to_output_buffer = ffi.new("uint8_t **", output_buffer)
input_size = ffi.new("size_t *", len(data))
input_buffer = ffi.new("uint8_t []", data)
ptr_to_input_buffer = ffi.new("uint8_t **", input_buffer)
rc = lib.BrotliEncoderCompressStream(
self._encoder,
operation,
input_size,
ptr_to_input_buffer,
available_out,
ptr_to_output_buffer,
ffi.NULL
)
if rc != lib.BROTLI_TRUE: # pragma: no cover
raise Error("Error encountered compressing data.")
assert not input_size[0]
size_of_output = original_output_size - available_out[0]
return ffi.buffer(output_buffer, size_of_output)[:] | [
"def",
"_compress",
"(",
"self",
",",
"data",
",",
"operation",
")",
":",
"# The 'algorithm' for working out how big to make this buffer is from",
"# the Brotli source code, brotlimodule.cc.",
"original_output_size",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"data",
")",
"+",
"(",
"len",
"(",
"data",
")",
">>",
"2",
")",
"+",
"10240",
")",
")",
"available_out",
"=",
"ffi",
".",
"new",
"(",
"\"size_t *\"",
")",
"available_out",
"[",
"0",
"]",
"=",
"original_output_size",
"output_buffer",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t []\"",
",",
"available_out",
"[",
"0",
"]",
")",
"ptr_to_output_buffer",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t **\"",
",",
"output_buffer",
")",
"input_size",
"=",
"ffi",
".",
"new",
"(",
"\"size_t *\"",
",",
"len",
"(",
"data",
")",
")",
"input_buffer",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t []\"",
",",
"data",
")",
"ptr_to_input_buffer",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t **\"",
",",
"input_buffer",
")",
"rc",
"=",
"lib",
".",
"BrotliEncoderCompressStream",
"(",
"self",
".",
"_encoder",
",",
"operation",
",",
"input_size",
",",
"ptr_to_input_buffer",
",",
"available_out",
",",
"ptr_to_output_buffer",
",",
"ffi",
".",
"NULL",
")",
"if",
"rc",
"!=",
"lib",
".",
"BROTLI_TRUE",
":",
"# pragma: no cover",
"raise",
"Error",
"(",
"\"Error encountered compressing data.\"",
")",
"assert",
"not",
"input_size",
"[",
"0",
"]",
"size_of_output",
"=",
"original_output_size",
"-",
"available_out",
"[",
"0",
"]",
"return",
"ffi",
".",
"buffer",
"(",
"output_buffer",
",",
"size_of_output",
")",
"[",
":",
"]"
] | This private method compresses some data in a given mode. This is used
because almost all of the code uses the exact same setup. It wouldn't
have to, but it doesn't hurt at all. | [
"This",
"private",
"method",
"compresses",
"some",
"data",
"in",
"a",
"given",
"mode",
".",
"This",
"is",
"used",
"because",
"almost",
"all",
"of",
"the",
"code",
"uses",
"the",
"exact",
"same",
"setup",
".",
"It",
"wouldn",
"t",
"have",
"to",
"but",
"it",
"doesn",
"t",
"hurt",
"at",
"all",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L283-L317 | train | 238,267 |
python-hyper/brotlipy | src/brotli/brotli.py | Compressor.flush | def flush(self):
"""
Flush the compressor. This will emit the remaining output data, but
will not destroy the compressor. It can be used, for example, to ensure
that given chunks of content will decompress immediately.
"""
chunks = []
chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FLUSH))
while lib.BrotliEncoderHasMoreOutput(self._encoder) == lib.BROTLI_TRUE:
chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FLUSH))
return b''.join(chunks) | python | def flush(self):
"""
Flush the compressor. This will emit the remaining output data, but
will not destroy the compressor. It can be used, for example, to ensure
that given chunks of content will decompress immediately.
"""
chunks = []
chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FLUSH))
while lib.BrotliEncoderHasMoreOutput(self._encoder) == lib.BROTLI_TRUE:
chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FLUSH))
return b''.join(chunks) | [
"def",
"flush",
"(",
"self",
")",
":",
"chunks",
"=",
"[",
"]",
"chunks",
".",
"append",
"(",
"self",
".",
"_compress",
"(",
"b''",
",",
"lib",
".",
"BROTLI_OPERATION_FLUSH",
")",
")",
"while",
"lib",
".",
"BrotliEncoderHasMoreOutput",
"(",
"self",
".",
"_encoder",
")",
"==",
"lib",
".",
"BROTLI_TRUE",
":",
"chunks",
".",
"append",
"(",
"self",
".",
"_compress",
"(",
"b''",
",",
"lib",
".",
"BROTLI_OPERATION_FLUSH",
")",
")",
"return",
"b''",
".",
"join",
"(",
"chunks",
")"
] | Flush the compressor. This will emit the remaining output data, but
will not destroy the compressor. It can be used, for example, to ensure
that given chunks of content will decompress immediately. | [
"Flush",
"the",
"compressor",
".",
"This",
"will",
"emit",
"the",
"remaining",
"output",
"data",
"but",
"will",
"not",
"destroy",
"the",
"compressor",
".",
"It",
"can",
"be",
"used",
"for",
"example",
"to",
"ensure",
"that",
"given",
"chunks",
"of",
"content",
"will",
"decompress",
"immediately",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L330-L342 | train | 238,268 |
python-hyper/brotlipy | src/brotli/brotli.py | Compressor.finish | def finish(self):
"""
Finish the compressor. This will emit the remaining output data and
transition the compressor to a completed state. The compressor cannot
be used again after this point, and must be replaced.
"""
chunks = []
while lib.BrotliEncoderIsFinished(self._encoder) == lib.BROTLI_FALSE:
chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FINISH))
return b''.join(chunks) | python | def finish(self):
"""
Finish the compressor. This will emit the remaining output data and
transition the compressor to a completed state. The compressor cannot
be used again after this point, and must be replaced.
"""
chunks = []
while lib.BrotliEncoderIsFinished(self._encoder) == lib.BROTLI_FALSE:
chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FINISH))
return b''.join(chunks) | [
"def",
"finish",
"(",
"self",
")",
":",
"chunks",
"=",
"[",
"]",
"while",
"lib",
".",
"BrotliEncoderIsFinished",
"(",
"self",
".",
"_encoder",
")",
"==",
"lib",
".",
"BROTLI_FALSE",
":",
"chunks",
".",
"append",
"(",
"self",
".",
"_compress",
"(",
"b''",
",",
"lib",
".",
"BROTLI_OPERATION_FINISH",
")",
")",
"return",
"b''",
".",
"join",
"(",
"chunks",
")"
] | Finish the compressor. This will emit the remaining output data and
transition the compressor to a completed state. The compressor cannot
be used again after this point, and must be replaced. | [
"Finish",
"the",
"compressor",
".",
"This",
"will",
"emit",
"the",
"remaining",
"output",
"data",
"and",
"transition",
"the",
"compressor",
"to",
"a",
"completed",
"state",
".",
"The",
"compressor",
"cannot",
"be",
"used",
"again",
"after",
"this",
"point",
"and",
"must",
"be",
"replaced",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L344-L354 | train | 238,269 |
python-hyper/brotlipy | src/brotli/brotli.py | Decompressor.decompress | def decompress(self, data):
"""
Decompress part of a complete Brotli-compressed string.
:param data: A bytestring containing Brotli-compressed data.
:returns: A bytestring containing the decompressed data.
"""
chunks = []
available_in = ffi.new("size_t *", len(data))
in_buffer = ffi.new("uint8_t[]", data)
next_in = ffi.new("uint8_t **", in_buffer)
while True:
# Allocate a buffer that's hopefully overlarge, but if it's not we
# don't mind: we'll spin around again.
buffer_size = 5 * len(data)
available_out = ffi.new("size_t *", buffer_size)
out_buffer = ffi.new("uint8_t[]", buffer_size)
next_out = ffi.new("uint8_t **", out_buffer)
rc = lib.BrotliDecoderDecompressStream(self._decoder,
available_in,
next_in,
available_out,
next_out,
ffi.NULL)
# First, check for errors.
if rc == lib.BROTLI_DECODER_RESULT_ERROR:
error_code = lib.BrotliDecoderGetErrorCode(self._decoder)
error_message = lib.BrotliDecoderErrorString(error_code)
raise Error(
"Decompression error: %s" % ffi.string(error_message)
)
# Next, copy the result out.
chunk = ffi.buffer(out_buffer, buffer_size - available_out[0])[:]
chunks.append(chunk)
if rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
assert available_in[0] == 0
break
elif rc == lib.BROTLI_DECODER_RESULT_SUCCESS:
break
else:
# It's cool if we need more output, we just loop again.
assert rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT
return b''.join(chunks) | python | def decompress(self, data):
"""
Decompress part of a complete Brotli-compressed string.
:param data: A bytestring containing Brotli-compressed data.
:returns: A bytestring containing the decompressed data.
"""
chunks = []
available_in = ffi.new("size_t *", len(data))
in_buffer = ffi.new("uint8_t[]", data)
next_in = ffi.new("uint8_t **", in_buffer)
while True:
# Allocate a buffer that's hopefully overlarge, but if it's not we
# don't mind: we'll spin around again.
buffer_size = 5 * len(data)
available_out = ffi.new("size_t *", buffer_size)
out_buffer = ffi.new("uint8_t[]", buffer_size)
next_out = ffi.new("uint8_t **", out_buffer)
rc = lib.BrotliDecoderDecompressStream(self._decoder,
available_in,
next_in,
available_out,
next_out,
ffi.NULL)
# First, check for errors.
if rc == lib.BROTLI_DECODER_RESULT_ERROR:
error_code = lib.BrotliDecoderGetErrorCode(self._decoder)
error_message = lib.BrotliDecoderErrorString(error_code)
raise Error(
"Decompression error: %s" % ffi.string(error_message)
)
# Next, copy the result out.
chunk = ffi.buffer(out_buffer, buffer_size - available_out[0])[:]
chunks.append(chunk)
if rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
assert available_in[0] == 0
break
elif rc == lib.BROTLI_DECODER_RESULT_SUCCESS:
break
else:
# It's cool if we need more output, we just loop again.
assert rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT
return b''.join(chunks) | [
"def",
"decompress",
"(",
"self",
",",
"data",
")",
":",
"chunks",
"=",
"[",
"]",
"available_in",
"=",
"ffi",
".",
"new",
"(",
"\"size_t *\"",
",",
"len",
"(",
"data",
")",
")",
"in_buffer",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t[]\"",
",",
"data",
")",
"next_in",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t **\"",
",",
"in_buffer",
")",
"while",
"True",
":",
"# Allocate a buffer that's hopefully overlarge, but if it's not we",
"# don't mind: we'll spin around again.",
"buffer_size",
"=",
"5",
"*",
"len",
"(",
"data",
")",
"available_out",
"=",
"ffi",
".",
"new",
"(",
"\"size_t *\"",
",",
"buffer_size",
")",
"out_buffer",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t[]\"",
",",
"buffer_size",
")",
"next_out",
"=",
"ffi",
".",
"new",
"(",
"\"uint8_t **\"",
",",
"out_buffer",
")",
"rc",
"=",
"lib",
".",
"BrotliDecoderDecompressStream",
"(",
"self",
".",
"_decoder",
",",
"available_in",
",",
"next_in",
",",
"available_out",
",",
"next_out",
",",
"ffi",
".",
"NULL",
")",
"# First, check for errors.",
"if",
"rc",
"==",
"lib",
".",
"BROTLI_DECODER_RESULT_ERROR",
":",
"error_code",
"=",
"lib",
".",
"BrotliDecoderGetErrorCode",
"(",
"self",
".",
"_decoder",
")",
"error_message",
"=",
"lib",
".",
"BrotliDecoderErrorString",
"(",
"error_code",
")",
"raise",
"Error",
"(",
"\"Decompression error: %s\"",
"%",
"ffi",
".",
"string",
"(",
"error_message",
")",
")",
"# Next, copy the result out.",
"chunk",
"=",
"ffi",
".",
"buffer",
"(",
"out_buffer",
",",
"buffer_size",
"-",
"available_out",
"[",
"0",
"]",
")",
"[",
":",
"]",
"chunks",
".",
"append",
"(",
"chunk",
")",
"if",
"rc",
"==",
"lib",
".",
"BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT",
":",
"assert",
"available_in",
"[",
"0",
"]",
"==",
"0",
"break",
"elif",
"rc",
"==",
"lib",
".",
"BROTLI_DECODER_RESULT_SUCCESS",
":",
"break",
"else",
":",
"# It's cool if we need more output, we just loop again.",
"assert",
"rc",
"==",
"lib",
".",
"BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT",
"return",
"b''",
".",
"join",
"(",
"chunks",
")"
] | Decompress part of a complete Brotli-compressed string.
:param data: A bytestring containing Brotli-compressed data.
:returns: A bytestring containing the decompressed data. | [
"Decompress",
"part",
"of",
"a",
"complete",
"Brotli",
"-",
"compressed",
"string",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L386-L435 | train | 238,270 |
python-hyper/brotlipy | src/brotli/brotli.py | Decompressor.finish | def finish(self):
"""
Finish the decompressor. As the decompressor decompresses eagerly, this
will never actually emit any data. However, it will potentially throw
errors if a truncated or damaged data stream has been used.
Note that, once this method is called, the decompressor is no longer
safe for further use and must be thrown away.
"""
assert (
lib.BrotliDecoderHasMoreOutput(self._decoder) == lib.BROTLI_FALSE
)
if lib.BrotliDecoderIsFinished(self._decoder) == lib.BROTLI_FALSE:
raise Error("Decompression error: incomplete compressed stream.")
return b'' | python | def finish(self):
"""
Finish the decompressor. As the decompressor decompresses eagerly, this
will never actually emit any data. However, it will potentially throw
errors if a truncated or damaged data stream has been used.
Note that, once this method is called, the decompressor is no longer
safe for further use and must be thrown away.
"""
assert (
lib.BrotliDecoderHasMoreOutput(self._decoder) == lib.BROTLI_FALSE
)
if lib.BrotliDecoderIsFinished(self._decoder) == lib.BROTLI_FALSE:
raise Error("Decompression error: incomplete compressed stream.")
return b'' | [
"def",
"finish",
"(",
"self",
")",
":",
"assert",
"(",
"lib",
".",
"BrotliDecoderHasMoreOutput",
"(",
"self",
".",
"_decoder",
")",
"==",
"lib",
".",
"BROTLI_FALSE",
")",
"if",
"lib",
".",
"BrotliDecoderIsFinished",
"(",
"self",
".",
"_decoder",
")",
"==",
"lib",
".",
"BROTLI_FALSE",
":",
"raise",
"Error",
"(",
"\"Decompression error: incomplete compressed stream.\"",
")",
"return",
"b''"
] | Finish the decompressor. As the decompressor decompresses eagerly, this
will never actually emit any data. However, it will potentially throw
errors if a truncated or damaged data stream has been used.
Note that, once this method is called, the decompressor is no longer
safe for further use and must be thrown away. | [
"Finish",
"the",
"decompressor",
".",
"As",
"the",
"decompressor",
"decompresses",
"eagerly",
"this",
"will",
"never",
"actually",
"emit",
"any",
"data",
".",
"However",
"it",
"will",
"potentially",
"throw",
"errors",
"if",
"a",
"truncated",
"or",
"damaged",
"data",
"stream",
"has",
"been",
"used",
"."
] | ffddf2ea5adc584c8c353d246bb1077b7e781b63 | https://github.com/python-hyper/brotlipy/blob/ffddf2ea5adc584c8c353d246bb1077b7e781b63/src/brotli/brotli.py#L451-L466 | train | 238,271 |
adafruit/Adafruit_Python_CharLCD | examples/char_lcd_rgb_pwm.py | hsv_to_rgb | def hsv_to_rgb(hsv):
"""Converts a tuple of hue, saturation, value to a tuple of red, green blue.
Hue should be an angle from 0.0 to 359.0. Saturation and value should be a
value from 0.0 to 1.0, where saturation controls the intensity of the hue and
value controls the brightness.
"""
# Algorithm adapted from http://www.cs.rit.edu/~ncs/color/t_convert.html
h, s, v = hsv
if s == 0:
return (v, v, v)
h /= 60.0
i = math.floor(h)
f = h-i
p = v*(1.0-s)
q = v*(1.0-s*f)
t = v*(1.0-s*(1.0-f))
if i == 0:
return (v, t, p)
elif i == 1:
return (q, v, p)
elif i == 2:
return (p, v, t)
elif i == 3:
return (p, q, v)
elif i == 4:
return (t, p, v)
else:
return (v, p, q) | python | def hsv_to_rgb(hsv):
"""Converts a tuple of hue, saturation, value to a tuple of red, green blue.
Hue should be an angle from 0.0 to 359.0. Saturation and value should be a
value from 0.0 to 1.0, where saturation controls the intensity of the hue and
value controls the brightness.
"""
# Algorithm adapted from http://www.cs.rit.edu/~ncs/color/t_convert.html
h, s, v = hsv
if s == 0:
return (v, v, v)
h /= 60.0
i = math.floor(h)
f = h-i
p = v*(1.0-s)
q = v*(1.0-s*f)
t = v*(1.0-s*(1.0-f))
if i == 0:
return (v, t, p)
elif i == 1:
return (q, v, p)
elif i == 2:
return (p, v, t)
elif i == 3:
return (p, q, v)
elif i == 4:
return (t, p, v)
else:
return (v, p, q) | [
"def",
"hsv_to_rgb",
"(",
"hsv",
")",
":",
"# Algorithm adapted from http://www.cs.rit.edu/~ncs/color/t_convert.html",
"h",
",",
"s",
",",
"v",
"=",
"hsv",
"if",
"s",
"==",
"0",
":",
"return",
"(",
"v",
",",
"v",
",",
"v",
")",
"h",
"/=",
"60.0",
"i",
"=",
"math",
".",
"floor",
"(",
"h",
")",
"f",
"=",
"h",
"-",
"i",
"p",
"=",
"v",
"*",
"(",
"1.0",
"-",
"s",
")",
"q",
"=",
"v",
"*",
"(",
"1.0",
"-",
"s",
"*",
"f",
")",
"t",
"=",
"v",
"*",
"(",
"1.0",
"-",
"s",
"*",
"(",
"1.0",
"-",
"f",
")",
")",
"if",
"i",
"==",
"0",
":",
"return",
"(",
"v",
",",
"t",
",",
"p",
")",
"elif",
"i",
"==",
"1",
":",
"return",
"(",
"q",
",",
"v",
",",
"p",
")",
"elif",
"i",
"==",
"2",
":",
"return",
"(",
"p",
",",
"v",
",",
"t",
")",
"elif",
"i",
"==",
"3",
":",
"return",
"(",
"p",
",",
"q",
",",
"v",
")",
"elif",
"i",
"==",
"4",
":",
"return",
"(",
"t",
",",
"p",
",",
"v",
")",
"else",
":",
"return",
"(",
"v",
",",
"p",
",",
"q",
")"
] | Converts a tuple of hue, saturation, value to a tuple of red, green blue.
Hue should be an angle from 0.0 to 359.0. Saturation and value should be a
value from 0.0 to 1.0, where saturation controls the intensity of the hue and
value controls the brightness. | [
"Converts",
"a",
"tuple",
"of",
"hue",
"saturation",
"value",
"to",
"a",
"tuple",
"of",
"red",
"green",
"blue",
".",
"Hue",
"should",
"be",
"an",
"angle",
"from",
"0",
".",
"0",
"to",
"359",
".",
"0",
".",
"Saturation",
"and",
"value",
"should",
"be",
"a",
"value",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"where",
"saturation",
"controls",
"the",
"intensity",
"of",
"the",
"hue",
"and",
"value",
"controls",
"the",
"brightness",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/examples/char_lcd_rgb_pwm.py#L9-L36 | train | 238,272 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.set_cursor | def set_cursor(self, col, row):
"""Move the cursor to an explicit column and row position."""
# Clamp row to the last row of the display.
if row > self._lines:
row = self._lines - 1
# Set location.
self.write8(LCD_SETDDRAMADDR | (col + LCD_ROW_OFFSETS[row])) | python | def set_cursor(self, col, row):
"""Move the cursor to an explicit column and row position."""
# Clamp row to the last row of the display.
if row > self._lines:
row = self._lines - 1
# Set location.
self.write8(LCD_SETDDRAMADDR | (col + LCD_ROW_OFFSETS[row])) | [
"def",
"set_cursor",
"(",
"self",
",",
"col",
",",
"row",
")",
":",
"# Clamp row to the last row of the display.",
"if",
"row",
">",
"self",
".",
"_lines",
":",
"row",
"=",
"self",
".",
"_lines",
"-",
"1",
"# Set location.",
"self",
".",
"write8",
"(",
"LCD_SETDDRAMADDR",
"|",
"(",
"col",
"+",
"LCD_ROW_OFFSETS",
"[",
"row",
"]",
")",
")"
] | Move the cursor to an explicit column and row position. | [
"Move",
"the",
"cursor",
"to",
"an",
"explicit",
"column",
"and",
"row",
"position",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L183-L189 | train | 238,273 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.enable_display | def enable_display(self, enable):
"""Enable or disable the display. Set enable to True to enable."""
if enable:
self.displaycontrol |= LCD_DISPLAYON
else:
self.displaycontrol &= ~LCD_DISPLAYON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | python | def enable_display(self, enable):
"""Enable or disable the display. Set enable to True to enable."""
if enable:
self.displaycontrol |= LCD_DISPLAYON
else:
self.displaycontrol &= ~LCD_DISPLAYON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | [
"def",
"enable_display",
"(",
"self",
",",
"enable",
")",
":",
"if",
"enable",
":",
"self",
".",
"displaycontrol",
"|=",
"LCD_DISPLAYON",
"else",
":",
"self",
".",
"displaycontrol",
"&=",
"~",
"LCD_DISPLAYON",
"self",
".",
"write8",
"(",
"LCD_DISPLAYCONTROL",
"|",
"self",
".",
"displaycontrol",
")"
] | Enable or disable the display. Set enable to True to enable. | [
"Enable",
"or",
"disable",
"the",
"display",
".",
"Set",
"enable",
"to",
"True",
"to",
"enable",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L191-L197 | train | 238,274 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.show_cursor | def show_cursor(self, show):
"""Show or hide the cursor. Cursor is shown if show is True."""
if show:
self.displaycontrol |= LCD_CURSORON
else:
self.displaycontrol &= ~LCD_CURSORON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | python | def show_cursor(self, show):
"""Show or hide the cursor. Cursor is shown if show is True."""
if show:
self.displaycontrol |= LCD_CURSORON
else:
self.displaycontrol &= ~LCD_CURSORON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | [
"def",
"show_cursor",
"(",
"self",
",",
"show",
")",
":",
"if",
"show",
":",
"self",
".",
"displaycontrol",
"|=",
"LCD_CURSORON",
"else",
":",
"self",
".",
"displaycontrol",
"&=",
"~",
"LCD_CURSORON",
"self",
".",
"write8",
"(",
"LCD_DISPLAYCONTROL",
"|",
"self",
".",
"displaycontrol",
")"
] | Show or hide the cursor. Cursor is shown if show is True. | [
"Show",
"or",
"hide",
"the",
"cursor",
".",
"Cursor",
"is",
"shown",
"if",
"show",
"is",
"True",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L199-L205 | train | 238,275 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.blink | def blink(self, blink):
"""Turn on or off cursor blinking. Set blink to True to enable blinking."""
if blink:
self.displaycontrol |= LCD_BLINKON
else:
self.displaycontrol &= ~LCD_BLINKON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | python | def blink(self, blink):
"""Turn on or off cursor blinking. Set blink to True to enable blinking."""
if blink:
self.displaycontrol |= LCD_BLINKON
else:
self.displaycontrol &= ~LCD_BLINKON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | [
"def",
"blink",
"(",
"self",
",",
"blink",
")",
":",
"if",
"blink",
":",
"self",
".",
"displaycontrol",
"|=",
"LCD_BLINKON",
"else",
":",
"self",
".",
"displaycontrol",
"&=",
"~",
"LCD_BLINKON",
"self",
".",
"write8",
"(",
"LCD_DISPLAYCONTROL",
"|",
"self",
".",
"displaycontrol",
")"
] | Turn on or off cursor blinking. Set blink to True to enable blinking. | [
"Turn",
"on",
"or",
"off",
"cursor",
"blinking",
".",
"Set",
"blink",
"to",
"True",
"to",
"enable",
"blinking",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L207-L213 | train | 238,276 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.set_left_to_right | def set_left_to_right(self):
"""Set text direction left to right."""
self.displaymode |= LCD_ENTRYLEFT
self.write8(LCD_ENTRYMODESET | self.displaymode) | python | def set_left_to_right(self):
"""Set text direction left to right."""
self.displaymode |= LCD_ENTRYLEFT
self.write8(LCD_ENTRYMODESET | self.displaymode) | [
"def",
"set_left_to_right",
"(",
"self",
")",
":",
"self",
".",
"displaymode",
"|=",
"LCD_ENTRYLEFT",
"self",
".",
"write8",
"(",
"LCD_ENTRYMODESET",
"|",
"self",
".",
"displaymode",
")"
] | Set text direction left to right. | [
"Set",
"text",
"direction",
"left",
"to",
"right",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L223-L226 | train | 238,277 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.set_right_to_left | def set_right_to_left(self):
"""Set text direction right to left."""
self.displaymode &= ~LCD_ENTRYLEFT
self.write8(LCD_ENTRYMODESET | self.displaymode) | python | def set_right_to_left(self):
"""Set text direction right to left."""
self.displaymode &= ~LCD_ENTRYLEFT
self.write8(LCD_ENTRYMODESET | self.displaymode) | [
"def",
"set_right_to_left",
"(",
"self",
")",
":",
"self",
".",
"displaymode",
"&=",
"~",
"LCD_ENTRYLEFT",
"self",
".",
"write8",
"(",
"LCD_ENTRYMODESET",
"|",
"self",
".",
"displaymode",
")"
] | Set text direction right to left. | [
"Set",
"text",
"direction",
"right",
"to",
"left",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L228-L231 | train | 238,278 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.autoscroll | def autoscroll(self, autoscroll):
"""Autoscroll will 'right justify' text from the cursor if set True,
otherwise it will 'left justify' the text.
"""
if autoscroll:
self.displaymode |= LCD_ENTRYSHIFTINCREMENT
else:
self.displaymode &= ~LCD_ENTRYSHIFTINCREMENT
self.write8(LCD_ENTRYMODESET | self.displaymode) | python | def autoscroll(self, autoscroll):
"""Autoscroll will 'right justify' text from the cursor if set True,
otherwise it will 'left justify' the text.
"""
if autoscroll:
self.displaymode |= LCD_ENTRYSHIFTINCREMENT
else:
self.displaymode &= ~LCD_ENTRYSHIFTINCREMENT
self.write8(LCD_ENTRYMODESET | self.displaymode) | [
"def",
"autoscroll",
"(",
"self",
",",
"autoscroll",
")",
":",
"if",
"autoscroll",
":",
"self",
".",
"displaymode",
"|=",
"LCD_ENTRYSHIFTINCREMENT",
"else",
":",
"self",
".",
"displaymode",
"&=",
"~",
"LCD_ENTRYSHIFTINCREMENT",
"self",
".",
"write8",
"(",
"LCD_ENTRYMODESET",
"|",
"self",
".",
"displaymode",
")"
] | Autoscroll will 'right justify' text from the cursor if set True,
otherwise it will 'left justify' the text. | [
"Autoscroll",
"will",
"right",
"justify",
"text",
"from",
"the",
"cursor",
"if",
"set",
"True",
"otherwise",
"it",
"will",
"left",
"justify",
"the",
"text",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L233-L241 | train | 238,279 |
adafruit/Adafruit_Python_CharLCD | Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.message | def message(self, text):
"""Write text to display. Note that text can include newlines."""
line = 0
# Iterate through each character.
for char in text:
# Advance to next line if character is a new line.
if char == '\n':
line += 1
# Move to left or right side depending on text direction.
col = 0 if self.displaymode & LCD_ENTRYLEFT > 0 else self._cols-1
self.set_cursor(col, line)
# Write the character to the display.
else:
self.write8(ord(char), True) | python | def message(self, text):
"""Write text to display. Note that text can include newlines."""
line = 0
# Iterate through each character.
for char in text:
# Advance to next line if character is a new line.
if char == '\n':
line += 1
# Move to left or right side depending on text direction.
col = 0 if self.displaymode & LCD_ENTRYLEFT > 0 else self._cols-1
self.set_cursor(col, line)
# Write the character to the display.
else:
self.write8(ord(char), True) | [
"def",
"message",
"(",
"self",
",",
"text",
")",
":",
"line",
"=",
"0",
"# Iterate through each character.",
"for",
"char",
"in",
"text",
":",
"# Advance to next line if character is a new line.",
"if",
"char",
"==",
"'\\n'",
":",
"line",
"+=",
"1",
"# Move to left or right side depending on text direction.",
"col",
"=",
"0",
"if",
"self",
".",
"displaymode",
"&",
"LCD_ENTRYLEFT",
">",
"0",
"else",
"self",
".",
"_cols",
"-",
"1",
"self",
".",
"set_cursor",
"(",
"col",
",",
"line",
")",
"# Write the character to the display.",
"else",
":",
"self",
".",
"write8",
"(",
"ord",
"(",
"char",
")",
",",
"True",
")"
] | Write text to display. Note that text can include newlines. | [
"Write",
"text",
"to",
"display",
".",
"Note",
"that",
"text",
"can",
"include",
"newlines",
"."
] | c126e6b673074c12a03f4bd36afb2fe40272341e | https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L243-L256 | train | 238,280 |
i3visio/osrframework | osrframework/utils/regexp.py | RegexpObject.findExp | def findExp(self, data):
'''
Method to look for the current regular expression in the provided string.
:param data: string containing the text where the expressions will be looked for.
:return: a list of verified regular expressions.
'''
temp = []
for r in self.reg_exp:
try:
temp += re.findall(r, data)
except:
print self.name
print r
print "CABOOOOM!"
verifiedExp = []
# verification
for t in temp:
# Remember: the regexps include two extra charactes (before and later) that should be removed now.
if self.isValidExp(t):
if t not in verifiedExp:
verifiedExp.append(t)
return self.getResults(verifiedExp) | python | def findExp(self, data):
'''
Method to look for the current regular expression in the provided string.
:param data: string containing the text where the expressions will be looked for.
:return: a list of verified regular expressions.
'''
temp = []
for r in self.reg_exp:
try:
temp += re.findall(r, data)
except:
print self.name
print r
print "CABOOOOM!"
verifiedExp = []
# verification
for t in temp:
# Remember: the regexps include two extra charactes (before and later) that should be removed now.
if self.isValidExp(t):
if t not in verifiedExp:
verifiedExp.append(t)
return self.getResults(verifiedExp) | [
"def",
"findExp",
"(",
"self",
",",
"data",
")",
":",
"temp",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"reg_exp",
":",
"try",
":",
"temp",
"+=",
"re",
".",
"findall",
"(",
"r",
",",
"data",
")",
"except",
":",
"print",
"self",
".",
"name",
"print",
"r",
"print",
"\"CABOOOOM!\"",
"verifiedExp",
"=",
"[",
"]",
"# verification",
"for",
"t",
"in",
"temp",
":",
"# Remember: the regexps include two extra charactes (before and later) that should be removed now.",
"if",
"self",
".",
"isValidExp",
"(",
"t",
")",
":",
"if",
"t",
"not",
"in",
"verifiedExp",
":",
"verifiedExp",
".",
"append",
"(",
"t",
")",
"return",
"self",
".",
"getResults",
"(",
"verifiedExp",
")"
] | Method to look for the current regular expression in the provided string.
:param data: string containing the text where the expressions will be looked for.
:return: a list of verified regular expressions. | [
"Method",
"to",
"look",
"for",
"the",
"current",
"regular",
"expression",
"in",
"the",
"provided",
"string",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/regexp.py#L125-L150 | train | 238,281 |
i3visio/osrframework | osrframework/utils/general.py | exportUsufy | def exportUsufy(data, ext, fileH):
"""
Method that exports the different structures onto different formats.
Args:
-----
data: Data to export.
ext: One of the following: csv, excel, json, ods.
fileH: Fileheader for the output files.
Returns:
--------
Performs the export as requested by parameter.
"""
if ext == "csv":
usufyToCsvExport(data, fileH+"."+ext)
elif ext == "gml":
usufyToGmlExport(data, fileH+"."+ext)
elif ext == "json":
usufyToJsonExport(data, fileH+"."+ext)
elif ext == "ods":
usufyToOdsExport(data, fileH+"."+ext)
elif ext == "png":
usufyToPngExport(data, fileH+"."+ext)
elif ext == "txt":
usufyToTextExport(data, fileH+"."+ext)
elif ext == "xls":
usufyToXlsExport(data, fileH+"."+ext)
elif ext == "xlsx":
usufyToXlsxExport(data, fileH+"."+ext) | python | def exportUsufy(data, ext, fileH):
"""
Method that exports the different structures onto different formats.
Args:
-----
data: Data to export.
ext: One of the following: csv, excel, json, ods.
fileH: Fileheader for the output files.
Returns:
--------
Performs the export as requested by parameter.
"""
if ext == "csv":
usufyToCsvExport(data, fileH+"."+ext)
elif ext == "gml":
usufyToGmlExport(data, fileH+"."+ext)
elif ext == "json":
usufyToJsonExport(data, fileH+"."+ext)
elif ext == "ods":
usufyToOdsExport(data, fileH+"."+ext)
elif ext == "png":
usufyToPngExport(data, fileH+"."+ext)
elif ext == "txt":
usufyToTextExport(data, fileH+"."+ext)
elif ext == "xls":
usufyToXlsExport(data, fileH+"."+ext)
elif ext == "xlsx":
usufyToXlsxExport(data, fileH+"."+ext) | [
"def",
"exportUsufy",
"(",
"data",
",",
"ext",
",",
"fileH",
")",
":",
"if",
"ext",
"==",
"\"csv\"",
":",
"usufyToCsvExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"gml\"",
":",
"usufyToGmlExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"json\"",
":",
"usufyToJsonExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"ods\"",
":",
"usufyToOdsExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"png\"",
":",
"usufyToPngExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"txt\"",
":",
"usufyToTextExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"xls\"",
":",
"usufyToXlsExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")",
"elif",
"ext",
"==",
"\"xlsx\"",
":",
"usufyToXlsxExport",
"(",
"data",
",",
"fileH",
"+",
"\".\"",
"+",
"ext",
")"
] | Method that exports the different structures onto different formats.
Args:
-----
data: Data to export.
ext: One of the following: csv, excel, json, ods.
fileH: Fileheader for the output files.
Returns:
--------
Performs the export as requested by parameter. | [
"Method",
"that",
"exports",
"the",
"different",
"structures",
"onto",
"different",
"formats",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L40-L69 | train | 238,282 |
i3visio/osrframework | osrframework/utils/general.py | _generateTabularData | def _generateTabularData(res, oldTabularData = {}, isTerminal=False, canUnicode=True):
"""
Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
-----
res: New data to export.
oldTabularData: The previous data stored.
{
"OSRFramework": [
[
"i3visio.alias",
"i3visio.platform",
"i3visio.uri"
],
[
"i3visio",
"Twitter",
"https://twitter.com/i3visio",
]
]
}
isTerminal: If isTerminal is activated, only information related to
relevant utils will be shown.
canUnicode: Variable that stores if the printed output can deal with
Unicode characters.
Returns:
--------
The values, as a dictionary containing all the information stored.
Values is like:
{
"OSRFramework": [
[
"i3visio.alias",
"i3visio.platform",
"i3visio.uri"
],
[
"i3visio",
"Twitter",
"https://twitter.com/i3visio",
],
[
"i3visio",
"Github",
"https://github.com/i3visio",
]
]
}
"""
def _grabbingNewHeader(h):
"""
Updates the headers to be general.
Changing the starting @ for a '_' and changing the "i3visio." for
"i3visio_". Changed in 0.9.4+.
Args:
-----
h: A header to be sanitised.
Returns:
--------
string: The modified header.
"""
if h[0] == "@":
h = h.replace("@", "_")
elif "i3visio." in h:
h = h.replace("i3visio.", "i3visio_")
return h
# Entities allowed for the output in terminal
allowedInTerminal = [
"i3visio_alias",
"i3visio_uri",
"i3visio_platform",
"i3visio_email",
"i3visio_ipv4",
"i3visio_phone",
"i3visio_dni",
"i3visio_domain",
"i3visio_platform_leaked",
#"_source"
]
# List of profiles found
values = {}
headers = ["_id"]
try:
if not isTerminal:
# Recovering the headers in the first line of the old Data
headers = oldTabularData["OSRFramework"][0]
else:
# Recovering only the printable headers if in Terminal mode
oldHeaders = oldTabularData["OSRFramework"][0]
headers = []
for h in oldHeaders:
h = _grabbingNewHeader(h)
if h in allowedInTerminal:
# Set to simplify the table shown in mailfy for leaked platforms
if h in ["i3visio_domain", "i3visio_alias"] and "_source" in old_headers:
pass
else:
headers.append(h)
# Changing the starting @ for a '_' and changing the "i3visio." for "i3visio_". Changed in 0.9.4+
for i, h in enumerate(headers):
h = _grabbingNewHeader(h)
# Replacing the header
headers[i] = h
except:
# No previous files... Easy...
headers = ["_id"]
# We are assuming that we received a list of profiles.
for p in res:
# Creating the dictionaries
values[p["value"]] = {}
attributes = p["attributes"]
# Processing all the attributes found
for a in attributes:
# Grabbing the type in the new format
h = _grabbingNewHeader(a["type"])
# Default behaviour for the output methods
if not isTerminal:
values[p["value"]][h] = a["value"]
# Appending the column if not already included
if str(h) not in headers:
headers.append(str(h))
# Specific table construction for the terminal output
else:
if h in allowedInTerminal:
values[p["value"]][h] = a["value"]
# Appending the column if not already included
if str(h) not in headers:
headers.append(str(h))
data = {}
# Note that each row should be a list!
workingSheet = []
# Appending the headers
workingSheet.append(headers)
# First, we will iterate through the previously stored values
try:
for dataRow in oldTabularData["OSRFramework"][1:]:
# Recovering the previous data
newRow = []
for cell in dataRow:
newRow.append(cell)
# Now, we will fill the rest of the cells with "N/A" values
for i in range(len(headers)-len(dataRow)):
# Printing a Not Applicable value
newRow.append("[N/A]")
# Appending the newRow to the data structure
workingSheet.append(newRow)
except Exception, e:
# No previous value found!
pass
# After having all the previous data stored an updated... We will go through the rest:
for prof in values.keys():
# Creating an empty structure
newRow = []
for i, col in enumerate(headers):
try:
if col == "_id":
newRow.append(len(workingSheet))
else:
if canUnicode:
newRow.append(unicode(values[prof][col]))
else:
newRow.append(str(values[prof][col]))
except UnicodeEncodeError as e:
# Printing that an error was found
newRow.append("[WARNING: Unicode Encode]")
except:
# Printing that this is not applicable value
newRow.append("[N/A]")
# Appending the newRow to the data structure
workingSheet.append(newRow)
# Storing the workingSheet onto the data structure to be stored
data.update({"OSRFramework": workingSheet})
return data | python | def _generateTabularData(res, oldTabularData = {}, isTerminal=False, canUnicode=True):
"""
Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
-----
res: New data to export.
oldTabularData: The previous data stored.
{
"OSRFramework": [
[
"i3visio.alias",
"i3visio.platform",
"i3visio.uri"
],
[
"i3visio",
"Twitter",
"https://twitter.com/i3visio",
]
]
}
isTerminal: If isTerminal is activated, only information related to
relevant utils will be shown.
canUnicode: Variable that stores if the printed output can deal with
Unicode characters.
Returns:
--------
The values, as a dictionary containing all the information stored.
Values is like:
{
"OSRFramework": [
[
"i3visio.alias",
"i3visio.platform",
"i3visio.uri"
],
[
"i3visio",
"Twitter",
"https://twitter.com/i3visio",
],
[
"i3visio",
"Github",
"https://github.com/i3visio",
]
]
}
"""
def _grabbingNewHeader(h):
"""
Updates the headers to be general.
Changing the starting @ for a '_' and changing the "i3visio." for
"i3visio_". Changed in 0.9.4+.
Args:
-----
h: A header to be sanitised.
Returns:
--------
string: The modified header.
"""
if h[0] == "@":
h = h.replace("@", "_")
elif "i3visio." in h:
h = h.replace("i3visio.", "i3visio_")
return h
# Entities allowed for the output in terminal
allowedInTerminal = [
"i3visio_alias",
"i3visio_uri",
"i3visio_platform",
"i3visio_email",
"i3visio_ipv4",
"i3visio_phone",
"i3visio_dni",
"i3visio_domain",
"i3visio_platform_leaked",
#"_source"
]
# List of profiles found
values = {}
headers = ["_id"]
try:
if not isTerminal:
# Recovering the headers in the first line of the old Data
headers = oldTabularData["OSRFramework"][0]
else:
# Recovering only the printable headers if in Terminal mode
oldHeaders = oldTabularData["OSRFramework"][0]
headers = []
for h in oldHeaders:
h = _grabbingNewHeader(h)
if h in allowedInTerminal:
# Set to simplify the table shown in mailfy for leaked platforms
if h in ["i3visio_domain", "i3visio_alias"] and "_source" in old_headers:
pass
else:
headers.append(h)
# Changing the starting @ for a '_' and changing the "i3visio." for "i3visio_". Changed in 0.9.4+
for i, h in enumerate(headers):
h = _grabbingNewHeader(h)
# Replacing the header
headers[i] = h
except:
# No previous files... Easy...
headers = ["_id"]
# We are assuming that we received a list of profiles.
for p in res:
# Creating the dictionaries
values[p["value"]] = {}
attributes = p["attributes"]
# Processing all the attributes found
for a in attributes:
# Grabbing the type in the new format
h = _grabbingNewHeader(a["type"])
# Default behaviour for the output methods
if not isTerminal:
values[p["value"]][h] = a["value"]
# Appending the column if not already included
if str(h) not in headers:
headers.append(str(h))
# Specific table construction for the terminal output
else:
if h in allowedInTerminal:
values[p["value"]][h] = a["value"]
# Appending the column if not already included
if str(h) not in headers:
headers.append(str(h))
data = {}
# Note that each row should be a list!
workingSheet = []
# Appending the headers
workingSheet.append(headers)
# First, we will iterate through the previously stored values
try:
for dataRow in oldTabularData["OSRFramework"][1:]:
# Recovering the previous data
newRow = []
for cell in dataRow:
newRow.append(cell)
# Now, we will fill the rest of the cells with "N/A" values
for i in range(len(headers)-len(dataRow)):
# Printing a Not Applicable value
newRow.append("[N/A]")
# Appending the newRow to the data structure
workingSheet.append(newRow)
except Exception, e:
# No previous value found!
pass
# After having all the previous data stored an updated... We will go through the rest:
for prof in values.keys():
# Creating an empty structure
newRow = []
for i, col in enumerate(headers):
try:
if col == "_id":
newRow.append(len(workingSheet))
else:
if canUnicode:
newRow.append(unicode(values[prof][col]))
else:
newRow.append(str(values[prof][col]))
except UnicodeEncodeError as e:
# Printing that an error was found
newRow.append("[WARNING: Unicode Encode]")
except:
# Printing that this is not applicable value
newRow.append("[N/A]")
# Appending the newRow to the data structure
workingSheet.append(newRow)
# Storing the workingSheet onto the data structure to be stored
data.update({"OSRFramework": workingSheet})
return data | [
"def",
"_generateTabularData",
"(",
"res",
",",
"oldTabularData",
"=",
"{",
"}",
",",
"isTerminal",
"=",
"False",
",",
"canUnicode",
"=",
"True",
")",
":",
"def",
"_grabbingNewHeader",
"(",
"h",
")",
":",
"\"\"\"\n Updates the headers to be general.\n\n Changing the starting @ for a '_' and changing the \"i3visio.\" for\n \"i3visio_\". Changed in 0.9.4+.\n\n Args:\n -----\n h: A header to be sanitised.\n\n Returns:\n --------\n string: The modified header.\n \"\"\"",
"if",
"h",
"[",
"0",
"]",
"==",
"\"@\"",
":",
"h",
"=",
"h",
".",
"replace",
"(",
"\"@\"",
",",
"\"_\"",
")",
"elif",
"\"i3visio.\"",
"in",
"h",
":",
"h",
"=",
"h",
".",
"replace",
"(",
"\"i3visio.\"",
",",
"\"i3visio_\"",
")",
"return",
"h",
"# Entities allowed for the output in terminal",
"allowedInTerminal",
"=",
"[",
"\"i3visio_alias\"",
",",
"\"i3visio_uri\"",
",",
"\"i3visio_platform\"",
",",
"\"i3visio_email\"",
",",
"\"i3visio_ipv4\"",
",",
"\"i3visio_phone\"",
",",
"\"i3visio_dni\"",
",",
"\"i3visio_domain\"",
",",
"\"i3visio_platform_leaked\"",
",",
"#\"_source\"",
"]",
"# List of profiles found",
"values",
"=",
"{",
"}",
"headers",
"=",
"[",
"\"_id\"",
"]",
"try",
":",
"if",
"not",
"isTerminal",
":",
"# Recovering the headers in the first line of the old Data",
"headers",
"=",
"oldTabularData",
"[",
"\"OSRFramework\"",
"]",
"[",
"0",
"]",
"else",
":",
"# Recovering only the printable headers if in Terminal mode",
"oldHeaders",
"=",
"oldTabularData",
"[",
"\"OSRFramework\"",
"]",
"[",
"0",
"]",
"headers",
"=",
"[",
"]",
"for",
"h",
"in",
"oldHeaders",
":",
"h",
"=",
"_grabbingNewHeader",
"(",
"h",
")",
"if",
"h",
"in",
"allowedInTerminal",
":",
"# Set to simplify the table shown in mailfy for leaked platforms",
"if",
"h",
"in",
"[",
"\"i3visio_domain\"",
",",
"\"i3visio_alias\"",
"]",
"and",
"\"_source\"",
"in",
"old_headers",
":",
"pass",
"else",
":",
"headers",
".",
"append",
"(",
"h",
")",
"# Changing the starting @ for a '_' and changing the \"i3visio.\" for \"i3visio_\". Changed in 0.9.4+",
"for",
"i",
",",
"h",
"in",
"enumerate",
"(",
"headers",
")",
":",
"h",
"=",
"_grabbingNewHeader",
"(",
"h",
")",
"# Replacing the header",
"headers",
"[",
"i",
"]",
"=",
"h",
"except",
":",
"# No previous files... Easy...",
"headers",
"=",
"[",
"\"_id\"",
"]",
"# We are assuming that we received a list of profiles.",
"for",
"p",
"in",
"res",
":",
"# Creating the dictionaries",
"values",
"[",
"p",
"[",
"\"value\"",
"]",
"]",
"=",
"{",
"}",
"attributes",
"=",
"p",
"[",
"\"attributes\"",
"]",
"# Processing all the attributes found",
"for",
"a",
"in",
"attributes",
":",
"# Grabbing the type in the new format",
"h",
"=",
"_grabbingNewHeader",
"(",
"a",
"[",
"\"type\"",
"]",
")",
"# Default behaviour for the output methods",
"if",
"not",
"isTerminal",
":",
"values",
"[",
"p",
"[",
"\"value\"",
"]",
"]",
"[",
"h",
"]",
"=",
"a",
"[",
"\"value\"",
"]",
"# Appending the column if not already included",
"if",
"str",
"(",
"h",
")",
"not",
"in",
"headers",
":",
"headers",
".",
"append",
"(",
"str",
"(",
"h",
")",
")",
"# Specific table construction for the terminal output",
"else",
":",
"if",
"h",
"in",
"allowedInTerminal",
":",
"values",
"[",
"p",
"[",
"\"value\"",
"]",
"]",
"[",
"h",
"]",
"=",
"a",
"[",
"\"value\"",
"]",
"# Appending the column if not already included",
"if",
"str",
"(",
"h",
")",
"not",
"in",
"headers",
":",
"headers",
".",
"append",
"(",
"str",
"(",
"h",
")",
")",
"data",
"=",
"{",
"}",
"# Note that each row should be a list!",
"workingSheet",
"=",
"[",
"]",
"# Appending the headers",
"workingSheet",
".",
"append",
"(",
"headers",
")",
"# First, we will iterate through the previously stored values",
"try",
":",
"for",
"dataRow",
"in",
"oldTabularData",
"[",
"\"OSRFramework\"",
"]",
"[",
"1",
":",
"]",
":",
"# Recovering the previous data",
"newRow",
"=",
"[",
"]",
"for",
"cell",
"in",
"dataRow",
":",
"newRow",
".",
"append",
"(",
"cell",
")",
"# Now, we will fill the rest of the cells with \"N/A\" values",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"headers",
")",
"-",
"len",
"(",
"dataRow",
")",
")",
":",
"# Printing a Not Applicable value",
"newRow",
".",
"append",
"(",
"\"[N/A]\"",
")",
"# Appending the newRow to the data structure",
"workingSheet",
".",
"append",
"(",
"newRow",
")",
"except",
"Exception",
",",
"e",
":",
"# No previous value found!",
"pass",
"# After having all the previous data stored an updated... We will go through the rest:",
"for",
"prof",
"in",
"values",
".",
"keys",
"(",
")",
":",
"# Creating an empty structure",
"newRow",
"=",
"[",
"]",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"headers",
")",
":",
"try",
":",
"if",
"col",
"==",
"\"_id\"",
":",
"newRow",
".",
"append",
"(",
"len",
"(",
"workingSheet",
")",
")",
"else",
":",
"if",
"canUnicode",
":",
"newRow",
".",
"append",
"(",
"unicode",
"(",
"values",
"[",
"prof",
"]",
"[",
"col",
"]",
")",
")",
"else",
":",
"newRow",
".",
"append",
"(",
"str",
"(",
"values",
"[",
"prof",
"]",
"[",
"col",
"]",
")",
")",
"except",
"UnicodeEncodeError",
"as",
"e",
":",
"# Printing that an error was found",
"newRow",
".",
"append",
"(",
"\"[WARNING: Unicode Encode]\"",
")",
"except",
":",
"# Printing that this is not applicable value",
"newRow",
".",
"append",
"(",
"\"[N/A]\"",
")",
"# Appending the newRow to the data structure",
"workingSheet",
".",
"append",
"(",
"newRow",
")",
"# Storing the workingSheet onto the data structure to be stored",
"data",
".",
"update",
"(",
"{",
"\"OSRFramework\"",
":",
"workingSheet",
"}",
")",
"return",
"data"
] | Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
-----
res: New data to export.
oldTabularData: The previous data stored.
{
"OSRFramework": [
[
"i3visio.alias",
"i3visio.platform",
"i3visio.uri"
],
[
"i3visio",
"Twitter",
"https://twitter.com/i3visio",
]
]
}
isTerminal: If isTerminal is activated, only information related to
relevant utils will be shown.
canUnicode: Variable that stores if the printed output can deal with
Unicode characters.
Returns:
--------
The values, as a dictionary containing all the information stored.
Values is like:
{
"OSRFramework": [
[
"i3visio.alias",
"i3visio.platform",
"i3visio.uri"
],
[
"i3visio",
"Twitter",
"https://twitter.com/i3visio",
],
[
"i3visio",
"Github",
"https://github.com/i3visio",
]
]
} | [
"Method",
"that",
"recovers",
"the",
"values",
"and",
"columns",
"from",
"the",
"current",
"structure"
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L72-L266 | train | 238,283 |
i3visio/osrframework | osrframework/utils/general.py | usufyToJsonExport | def usufyToJsonExport(d, fPath):
"""
Workaround to export to a json file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
oldData = []
try:
with open (fPath) as iF:
oldText = iF.read()
if oldText != "":
oldData = json.loads(oldText)
except:
# No file found, so we will create it...
pass
jsonText = json.dumps(oldData+d, indent=2, sort_keys=True)
with open (fPath, "w") as oF:
oF.write(jsonText) | python | def usufyToJsonExport(d, fPath):
"""
Workaround to export to a json file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
oldData = []
try:
with open (fPath) as iF:
oldText = iF.read()
if oldText != "":
oldData = json.loads(oldText)
except:
# No file found, so we will create it...
pass
jsonText = json.dumps(oldData+d, indent=2, sort_keys=True)
with open (fPath, "w") as oF:
oF.write(jsonText) | [
"def",
"usufyToJsonExport",
"(",
"d",
",",
"fPath",
")",
":",
"oldData",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"fPath",
")",
"as",
"iF",
":",
"oldText",
"=",
"iF",
".",
"read",
"(",
")",
"if",
"oldText",
"!=",
"\"\"",
":",
"oldData",
"=",
"json",
".",
"loads",
"(",
"oldText",
")",
"except",
":",
"# No file found, so we will create it...",
"pass",
"jsonText",
"=",
"json",
".",
"dumps",
"(",
"oldData",
"+",
"d",
",",
"indent",
"=",
"2",
",",
"sort_keys",
"=",
"True",
")",
"with",
"open",
"(",
"fPath",
",",
"\"w\"",
")",
"as",
"oF",
":",
"oF",
".",
"write",
"(",
"jsonText",
")"
] | Workaround to export to a json file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"to",
"a",
"json",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L269-L291 | train | 238,284 |
i3visio/osrframework | osrframework/utils/general.py | usufyToTextExport | def usufyToTextExport(d, fPath=None):
"""
Workaround to export to a .txt file or to show the information.
Args:
-----
d: Data to export.
fPath: File path for the output file. If None was provided, it will
assume that it has to print it.
Returns:
--------
unicode: It sometimes returns a unicode representation of the Sheet
received.
"""
# Manual check...
if d == []:
return "+------------------+\n| No data found... |\n+------------------+"
import pyexcel as pe
import pyexcel.ext.text as text
if fPath == None:
isTerminal = True
else:
isTerminal = False
try:
oldData = get_data(fPath)
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, {"OSRFramework":[[]]}, True, canUnicode=False)
# The tabular data contains a dict representing the whole book and we need only the sheet!!
sheet = pe.Sheet(tabularData["OSRFramework"])
sheet.name = "Profiles recovered (" + getCurrentStrDatetime() +")."
# Defining the headers
sheet.name_columns_by_row(0)
text.TABLEFMT = "grid"
try:
with open(fPath, "w") as oF:
oF.write(str(sheet))
except Exception as e:
# If a fPath was not provided... We will only print the info:
return unicode(sheet) | python | def usufyToTextExport(d, fPath=None):
"""
Workaround to export to a .txt file or to show the information.
Args:
-----
d: Data to export.
fPath: File path for the output file. If None was provided, it will
assume that it has to print it.
Returns:
--------
unicode: It sometimes returns a unicode representation of the Sheet
received.
"""
# Manual check...
if d == []:
return "+------------------+\n| No data found... |\n+------------------+"
import pyexcel as pe
import pyexcel.ext.text as text
if fPath == None:
isTerminal = True
else:
isTerminal = False
try:
oldData = get_data(fPath)
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, {"OSRFramework":[[]]}, True, canUnicode=False)
# The tabular data contains a dict representing the whole book and we need only the sheet!!
sheet = pe.Sheet(tabularData["OSRFramework"])
sheet.name = "Profiles recovered (" + getCurrentStrDatetime() +")."
# Defining the headers
sheet.name_columns_by_row(0)
text.TABLEFMT = "grid"
try:
with open(fPath, "w") as oF:
oF.write(str(sheet))
except Exception as e:
# If a fPath was not provided... We will only print the info:
return unicode(sheet) | [
"def",
"usufyToTextExport",
"(",
"d",
",",
"fPath",
"=",
"None",
")",
":",
"# Manual check...",
"if",
"d",
"==",
"[",
"]",
":",
"return",
"\"+------------------+\\n| No data found... |\\n+------------------+\"",
"import",
"pyexcel",
"as",
"pe",
"import",
"pyexcel",
".",
"ext",
".",
"text",
"as",
"text",
"if",
"fPath",
"==",
"None",
":",
"isTerminal",
"=",
"True",
"else",
":",
"isTerminal",
"=",
"False",
"try",
":",
"oldData",
"=",
"get_data",
"(",
"fPath",
")",
"except",
":",
"# No information has been recovered",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"[",
"]",
"}",
"# Generating the new tabular data",
"tabularData",
"=",
"_generateTabularData",
"(",
"d",
",",
"{",
"\"OSRFramework\"",
":",
"[",
"[",
"]",
"]",
"}",
",",
"True",
",",
"canUnicode",
"=",
"False",
")",
"# The tabular data contains a dict representing the whole book and we need only the sheet!!",
"sheet",
"=",
"pe",
".",
"Sheet",
"(",
"tabularData",
"[",
"\"OSRFramework\"",
"]",
")",
"sheet",
".",
"name",
"=",
"\"Profiles recovered (\"",
"+",
"getCurrentStrDatetime",
"(",
")",
"+",
"\").\"",
"# Defining the headers",
"sheet",
".",
"name_columns_by_row",
"(",
"0",
")",
"text",
".",
"TABLEFMT",
"=",
"\"grid\"",
"try",
":",
"with",
"open",
"(",
"fPath",
",",
"\"w\"",
")",
"as",
"oF",
":",
"oF",
".",
"write",
"(",
"str",
"(",
"sheet",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"# If a fPath was not provided... We will only print the info:",
"return",
"unicode",
"(",
"sheet",
")"
] | Workaround to export to a .txt file or to show the information.
Args:
-----
d: Data to export.
fPath: File path for the output file. If None was provided, it will
assume that it has to print it.
Returns:
--------
unicode: It sometimes returns a unicode representation of the Sheet
received. | [
"Workaround",
"to",
"export",
"to",
"a",
".",
"txt",
"file",
"or",
"to",
"show",
"the",
"information",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L294-L342 | train | 238,285 |
i3visio/osrframework | osrframework/utils/general.py | usufyToCsvExport | def usufyToCsvExport(d, fPath):
"""
Workaround to export to a CSV file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_io import get_data
try:
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data.
tabularData = _generateTabularData(d, oldData)
from pyexcel_io import save_data
# Storing the file
# NOTE: when working with CSV files it is no longer a dict because it is a one-sheet-format
save_data(fPath, tabularData["OSRFramework"]) | python | def usufyToCsvExport(d, fPath):
"""
Workaround to export to a CSV file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_io import get_data
try:
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data.
tabularData = _generateTabularData(d, oldData)
from pyexcel_io import save_data
# Storing the file
# NOTE: when working with CSV files it is no longer a dict because it is a one-sheet-format
save_data(fPath, tabularData["OSRFramework"]) | [
"def",
"usufyToCsvExport",
"(",
"d",
",",
"fPath",
")",
":",
"from",
"pyexcel_io",
"import",
"get_data",
"try",
":",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"get_data",
"(",
"fPath",
")",
"}",
"except",
":",
"# No information has been recovered",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"[",
"]",
"}",
"# Generating the new tabular data.",
"tabularData",
"=",
"_generateTabularData",
"(",
"d",
",",
"oldData",
")",
"from",
"pyexcel_io",
"import",
"save_data",
"# Storing the file",
"# NOTE: when working with CSV files it is no longer a dict because it is a one-sheet-format",
"save_data",
"(",
"fPath",
",",
"tabularData",
"[",
"\"OSRFramework\"",
"]",
")"
] | Workaround to export to a CSV file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"to",
"a",
"CSV",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L345-L368 | train | 238,286 |
i3visio/osrframework | osrframework/utils/general.py | usufyToOdsExport | def usufyToOdsExport(d, fPath):
"""
Workaround to export to a .ods file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_ods import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an array of arrays if there is only one sheet.
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, oldData)
from pyexcel_ods import save_data
# Storing the file
save_data(fPath, tabularData) | python | def usufyToOdsExport(d, fPath):
"""
Workaround to export to a .ods file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_ods import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an array of arrays if there is only one sheet.
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, oldData)
from pyexcel_ods import save_data
# Storing the file
save_data(fPath, tabularData) | [
"def",
"usufyToOdsExport",
"(",
"d",
",",
"fPath",
")",
":",
"from",
"pyexcel_ods",
"import",
"get_data",
"try",
":",
"#oldData = get_data(fPath)",
"# A change in the API now returns only an array of arrays if there is only one sheet.",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"get_data",
"(",
"fPath",
")",
"}",
"except",
":",
"# No information has been recovered",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"[",
"]",
"}",
"# Generating the new tabular data",
"tabularData",
"=",
"_generateTabularData",
"(",
"d",
",",
"oldData",
")",
"from",
"pyexcel_ods",
"import",
"save_data",
"# Storing the file",
"save_data",
"(",
"fPath",
",",
"tabularData",
")"
] | Workaround to export to a .ods file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"to",
"a",
".",
"ods",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L371-L394 | train | 238,287 |
i3visio/osrframework | osrframework/utils/general.py | usufyToXlsExport | def usufyToXlsExport(d, fPath):
"""
Workaround to export to a .xls file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_xls import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an array of arrays if there is only one sheet.
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, oldData)
from pyexcel_xls import save_data
# Storing the file
save_data(fPath, tabularData) | python | def usufyToXlsExport(d, fPath):
"""
Workaround to export to a .xls file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_xls import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an array of arrays if there is only one sheet.
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, oldData)
from pyexcel_xls import save_data
# Storing the file
save_data(fPath, tabularData) | [
"def",
"usufyToXlsExport",
"(",
"d",
",",
"fPath",
")",
":",
"from",
"pyexcel_xls",
"import",
"get_data",
"try",
":",
"#oldData = get_data(fPath)",
"# A change in the API now returns only an array of arrays if there is only one sheet.",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"get_data",
"(",
"fPath",
")",
"}",
"except",
":",
"# No information has been recovered",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"[",
"]",
"}",
"# Generating the new tabular data",
"tabularData",
"=",
"_generateTabularData",
"(",
"d",
",",
"oldData",
")",
"from",
"pyexcel_xls",
"import",
"save_data",
"# Storing the file",
"save_data",
"(",
"fPath",
",",
"tabularData",
")"
] | Workaround to export to a .xls file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"to",
"a",
".",
"xls",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L397-L419 | train | 238,288 |
i3visio/osrframework | osrframework/utils/general.py | usufyToXlsxExport | def usufyToXlsxExport(d, fPath):
"""
Workaround to export to a .xlsx file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_xlsx import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an array of arrays if there is only one sheet.
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, oldData)
from pyexcel_xlsx import save_data
# Storing the file
save_data(fPath, tabularData) | python | def usufyToXlsxExport(d, fPath):
"""
Workaround to export to a .xlsx file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
from pyexcel_xlsx import get_data
try:
#oldData = get_data(fPath)
# A change in the API now returns only an array of arrays if there is only one sheet.
oldData = {"OSRFramework": get_data(fPath) }
except:
# No information has been recovered
oldData = {"OSRFramework":[]}
# Generating the new tabular data
tabularData = _generateTabularData(d, oldData)
from pyexcel_xlsx import save_data
# Storing the file
save_data(fPath, tabularData) | [
"def",
"usufyToXlsxExport",
"(",
"d",
",",
"fPath",
")",
":",
"from",
"pyexcel_xlsx",
"import",
"get_data",
"try",
":",
"#oldData = get_data(fPath)",
"# A change in the API now returns only an array of arrays if there is only one sheet.",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"get_data",
"(",
"fPath",
")",
"}",
"except",
":",
"# No information has been recovered",
"oldData",
"=",
"{",
"\"OSRFramework\"",
":",
"[",
"]",
"}",
"# Generating the new tabular data",
"tabularData",
"=",
"_generateTabularData",
"(",
"d",
",",
"oldData",
")",
"from",
"pyexcel_xlsx",
"import",
"save_data",
"# Storing the file",
"save_data",
"(",
"fPath",
",",
"tabularData",
")"
] | Workaround to export to a .xlsx file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"to",
"a",
".",
"xlsx",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L422-L445 | train | 238,289 |
i3visio/osrframework | osrframework/utils/general.py | _generateGraphData | def _generateGraphData(data, oldData=nx.Graph()):
"""
Processing the data from i3visio structures to generate nodes and edges
This function uses the networkx graph library. It will create a new node
for each and i3visio.<something> entities while it will add properties for
all the attribute starting with "@".
Args:
-----
d: The i3visio structures containing a list of
oldData: A graph structure representing the previous information.
Returns:
--------
A graph structure representing the updated information.
"""
def _addNewNode(ent, g):
"""
Wraps the creation of a node
Args:
-----
ent: The hi3visio-like entities to be used as the identifier.
ent = {
"value":"i3visio",
"type":"i3visio.alias,
}
g: The graph in which the entity will be stored.
Returns:
-------
The label used to represent this element.
"""
try:
label = unicode(ent["value"])
except UnicodeEncodeError as e:
# Printing that an error was found
label = str(ent["value"])
g.add_node(label)
g.node[label]["type"] = ent["type"]
return label
def _processAttributes(elems, g):
"""
Function that processes a list of elements to obtain new attributes.
Args:
-----
elems: List of i3visio-like entities.
g: The graph in which the entity will be stored.
Returns:
--------
newAtts: Dict of attributes (to be stored as attributes for the
given entity).
newEntities: List of new Entities (to be stored as attributes for
the given entity).
"""
newAtts = {}
newEntities= []
for att in elems:
# If it is an attribute
if att["type"][0] == "@":
# Removing the @ and the _ of the attributes
attName = str(att["type"][1:]).replace('_', '')
try:
newAtts[attName] = int(att["value"])
except:
newAtts[attName] = att["value"]
elif att["type"][:8] == "i3visio.":
# Creating a dict to represent the pair: type, value entity.
ent = {
"value":att["value"],
"type":att["type"].replace("i3visio.", "i3visio_"),
}
# Appending the new Entity to the entity list
newEntities.append(ent)
# Appending the new node
hashLabel = _addNewNode(ent, g)
# Make this recursive to link the attributes in each and every att
newAttsInAttributes, newEntitiesInAttributes = _processAttributes(att["attributes"], g)
# Updating the attributes to the current entity
g.node[hashLabel].update(newAttsInAttributes)
# Creating the edges (the new entities have also been created in the _processAttributes
for new in newEntitiesInAttributes:
graphData.add_edge(hashLabel, json.dumps(new))
try:
# Here, we would add the properties of the edge
#graphData.edge[hashLabel][json.dumps(new)]["@times_seen"] +=1
pass
except:
# If the attribute does not exist, we would initialize it
#graphData.edge[hashLabel][json.dumps(new)]["@times_seen"] = 1
pass
else:
# An unexpected type
pass
return newAtts, newEntities
graphData = oldData
# Iterating through the results
for elem in data:
# Creating a dict to represent the pair: type, value entity.
ent = {
"value":elem["value"],
"type":elem["type"],
}
# Appending the new node
new_node = _addNewNode(ent, graphData)
# Processing the attributes to grab the attributes (starting with "@..." and entities)
newAtts, newEntities = _processAttributes(elem["attributes"], graphData)
# Updating the attributes to the current entity
graphData.node[new_node].update(newAtts)
# Creating the edges (the new entities have also been created in the _processAttributes
for other_node in newEntities:
# Serializing the second entity
serEnt = json.dumps(new_node)
try:
other_node = unicode(other_node["value"])
except UnicodeEncodeError as e:
# Printing that an error was found
other_node = str(other_node["value"])
# Adding the edge
graphData.add_edge(new_node, other_node)
try:
# Here, we would add the properties of the edge
#graphData.edge[hashLabel][hashLabelSeconds]["times_seen"] +=1
pass
except:
# If the attribute does not exist, we would initialize it
#graphData.edge[hashLabel][hashLabelSeconds]["times_seen"] = 1
pass
return graphData | python | def _generateGraphData(data, oldData=nx.Graph()):
"""
Processing the data from i3visio structures to generate nodes and edges
This function uses the networkx graph library. It will create a new node
for each and i3visio.<something> entities while it will add properties for
all the attribute starting with "@".
Args:
-----
d: The i3visio structures containing a list of
oldData: A graph structure representing the previous information.
Returns:
--------
A graph structure representing the updated information.
"""
def _addNewNode(ent, g):
"""
Wraps the creation of a node
Args:
-----
ent: The hi3visio-like entities to be used as the identifier.
ent = {
"value":"i3visio",
"type":"i3visio.alias,
}
g: The graph in which the entity will be stored.
Returns:
-------
The label used to represent this element.
"""
try:
label = unicode(ent["value"])
except UnicodeEncodeError as e:
# Printing that an error was found
label = str(ent["value"])
g.add_node(label)
g.node[label]["type"] = ent["type"]
return label
def _processAttributes(elems, g):
"""
Function that processes a list of elements to obtain new attributes.
Args:
-----
elems: List of i3visio-like entities.
g: The graph in which the entity will be stored.
Returns:
--------
newAtts: Dict of attributes (to be stored as attributes for the
given entity).
newEntities: List of new Entities (to be stored as attributes for
the given entity).
"""
newAtts = {}
newEntities= []
for att in elems:
# If it is an attribute
if att["type"][0] == "@":
# Removing the @ and the _ of the attributes
attName = str(att["type"][1:]).replace('_', '')
try:
newAtts[attName] = int(att["value"])
except:
newAtts[attName] = att["value"]
elif att["type"][:8] == "i3visio.":
# Creating a dict to represent the pair: type, value entity.
ent = {
"value":att["value"],
"type":att["type"].replace("i3visio.", "i3visio_"),
}
# Appending the new Entity to the entity list
newEntities.append(ent)
# Appending the new node
hashLabel = _addNewNode(ent, g)
# Make this recursive to link the attributes in each and every att
newAttsInAttributes, newEntitiesInAttributes = _processAttributes(att["attributes"], g)
# Updating the attributes to the current entity
g.node[hashLabel].update(newAttsInAttributes)
# Creating the edges (the new entities have also been created in the _processAttributes
for new in newEntitiesInAttributes:
graphData.add_edge(hashLabel, json.dumps(new))
try:
# Here, we would add the properties of the edge
#graphData.edge[hashLabel][json.dumps(new)]["@times_seen"] +=1
pass
except:
# If the attribute does not exist, we would initialize it
#graphData.edge[hashLabel][json.dumps(new)]["@times_seen"] = 1
pass
else:
# An unexpected type
pass
return newAtts, newEntities
graphData = oldData
# Iterating through the results
for elem in data:
# Creating a dict to represent the pair: type, value entity.
ent = {
"value":elem["value"],
"type":elem["type"],
}
# Appending the new node
new_node = _addNewNode(ent, graphData)
# Processing the attributes to grab the attributes (starting with "@..." and entities)
newAtts, newEntities = _processAttributes(elem["attributes"], graphData)
# Updating the attributes to the current entity
graphData.node[new_node].update(newAtts)
# Creating the edges (the new entities have also been created in the _processAttributes
for other_node in newEntities:
# Serializing the second entity
serEnt = json.dumps(new_node)
try:
other_node = unicode(other_node["value"])
except UnicodeEncodeError as e:
# Printing that an error was found
other_node = str(other_node["value"])
# Adding the edge
graphData.add_edge(new_node, other_node)
try:
# Here, we would add the properties of the edge
#graphData.edge[hashLabel][hashLabelSeconds]["times_seen"] +=1
pass
except:
# If the attribute does not exist, we would initialize it
#graphData.edge[hashLabel][hashLabelSeconds]["times_seen"] = 1
pass
return graphData | [
"def",
"_generateGraphData",
"(",
"data",
",",
"oldData",
"=",
"nx",
".",
"Graph",
"(",
")",
")",
":",
"def",
"_addNewNode",
"(",
"ent",
",",
"g",
")",
":",
"\"\"\"\n Wraps the creation of a node\n\n Args:\n -----\n ent: The hi3visio-like entities to be used as the identifier.\n ent = {\n \"value\":\"i3visio\",\n \"type\":\"i3visio.alias,\n }\n g: The graph in which the entity will be stored.\n\n Returns:\n -------\n The label used to represent this element.\n \"\"\"",
"try",
":",
"label",
"=",
"unicode",
"(",
"ent",
"[",
"\"value\"",
"]",
")",
"except",
"UnicodeEncodeError",
"as",
"e",
":",
"# Printing that an error was found",
"label",
"=",
"str",
"(",
"ent",
"[",
"\"value\"",
"]",
")",
"g",
".",
"add_node",
"(",
"label",
")",
"g",
".",
"node",
"[",
"label",
"]",
"[",
"\"type\"",
"]",
"=",
"ent",
"[",
"\"type\"",
"]",
"return",
"label",
"def",
"_processAttributes",
"(",
"elems",
",",
"g",
")",
":",
"\"\"\"\n Function that processes a list of elements to obtain new attributes.\n\n Args:\n -----\n elems: List of i3visio-like entities.\n g: The graph in which the entity will be stored.\n\n Returns:\n --------\n newAtts: Dict of attributes (to be stored as attributes for the\n given entity).\n newEntities: List of new Entities (to be stored as attributes for\n the given entity).\n \"\"\"",
"newAtts",
"=",
"{",
"}",
"newEntities",
"=",
"[",
"]",
"for",
"att",
"in",
"elems",
":",
"# If it is an attribute",
"if",
"att",
"[",
"\"type\"",
"]",
"[",
"0",
"]",
"==",
"\"@\"",
":",
"# Removing the @ and the _ of the attributes",
"attName",
"=",
"str",
"(",
"att",
"[",
"\"type\"",
"]",
"[",
"1",
":",
"]",
")",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
"try",
":",
"newAtts",
"[",
"attName",
"]",
"=",
"int",
"(",
"att",
"[",
"\"value\"",
"]",
")",
"except",
":",
"newAtts",
"[",
"attName",
"]",
"=",
"att",
"[",
"\"value\"",
"]",
"elif",
"att",
"[",
"\"type\"",
"]",
"[",
":",
"8",
"]",
"==",
"\"i3visio.\"",
":",
"# Creating a dict to represent the pair: type, value entity.",
"ent",
"=",
"{",
"\"value\"",
":",
"att",
"[",
"\"value\"",
"]",
",",
"\"type\"",
":",
"att",
"[",
"\"type\"",
"]",
".",
"replace",
"(",
"\"i3visio.\"",
",",
"\"i3visio_\"",
")",
",",
"}",
"# Appending the new Entity to the entity list",
"newEntities",
".",
"append",
"(",
"ent",
")",
"# Appending the new node",
"hashLabel",
"=",
"_addNewNode",
"(",
"ent",
",",
"g",
")",
"# Make this recursive to link the attributes in each and every att",
"newAttsInAttributes",
",",
"newEntitiesInAttributes",
"=",
"_processAttributes",
"(",
"att",
"[",
"\"attributes\"",
"]",
",",
"g",
")",
"# Updating the attributes to the current entity",
"g",
".",
"node",
"[",
"hashLabel",
"]",
".",
"update",
"(",
"newAttsInAttributes",
")",
"# Creating the edges (the new entities have also been created in the _processAttributes",
"for",
"new",
"in",
"newEntitiesInAttributes",
":",
"graphData",
".",
"add_edge",
"(",
"hashLabel",
",",
"json",
".",
"dumps",
"(",
"new",
")",
")",
"try",
":",
"# Here, we would add the properties of the edge",
"#graphData.edge[hashLabel][json.dumps(new)][\"@times_seen\"] +=1",
"pass",
"except",
":",
"# If the attribute does not exist, we would initialize it",
"#graphData.edge[hashLabel][json.dumps(new)][\"@times_seen\"] = 1",
"pass",
"else",
":",
"# An unexpected type",
"pass",
"return",
"newAtts",
",",
"newEntities",
"graphData",
"=",
"oldData",
"# Iterating through the results",
"for",
"elem",
"in",
"data",
":",
"# Creating a dict to represent the pair: type, value entity.",
"ent",
"=",
"{",
"\"value\"",
":",
"elem",
"[",
"\"value\"",
"]",
",",
"\"type\"",
":",
"elem",
"[",
"\"type\"",
"]",
",",
"}",
"# Appending the new node",
"new_node",
"=",
"_addNewNode",
"(",
"ent",
",",
"graphData",
")",
"# Processing the attributes to grab the attributes (starting with \"@...\" and entities)",
"newAtts",
",",
"newEntities",
"=",
"_processAttributes",
"(",
"elem",
"[",
"\"attributes\"",
"]",
",",
"graphData",
")",
"# Updating the attributes to the current entity",
"graphData",
".",
"node",
"[",
"new_node",
"]",
".",
"update",
"(",
"newAtts",
")",
"# Creating the edges (the new entities have also been created in the _processAttributes",
"for",
"other_node",
"in",
"newEntities",
":",
"# Serializing the second entity",
"serEnt",
"=",
"json",
".",
"dumps",
"(",
"new_node",
")",
"try",
":",
"other_node",
"=",
"unicode",
"(",
"other_node",
"[",
"\"value\"",
"]",
")",
"except",
"UnicodeEncodeError",
"as",
"e",
":",
"# Printing that an error was found",
"other_node",
"=",
"str",
"(",
"other_node",
"[",
"\"value\"",
"]",
")",
"# Adding the edge",
"graphData",
".",
"add_edge",
"(",
"new_node",
",",
"other_node",
")",
"try",
":",
"# Here, we would add the properties of the edge",
"#graphData.edge[hashLabel][hashLabelSeconds][\"times_seen\"] +=1",
"pass",
"except",
":",
"# If the attribute does not exist, we would initialize it",
"#graphData.edge[hashLabel][hashLabelSeconds][\"times_seen\"] = 1",
"pass",
"return",
"graphData"
] | Processing the data from i3visio structures to generate nodes and edges
This function uses the networkx graph library. It will create a new node
for each and i3visio.<something> entities while it will add properties for
all the attribute starting with "@".
Args:
-----
d: The i3visio structures containing a list of
oldData: A graph structure representing the previous information.
Returns:
--------
A graph structure representing the updated information. | [
"Processing",
"the",
"data",
"from",
"i3visio",
"structures",
"to",
"generate",
"nodes",
"and",
"edges"
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L448-L594 | train | 238,290 |
i3visio/osrframework | osrframework/utils/general.py | usufyToGmlExport | def usufyToGmlExport(d, fPath):
"""
Workaround to export data to a .gml file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
# Reading the previous gml file
try:
oldData=nx.read_gml(fPath)
except UnicodeDecodeError as e:
print("UnicodeDecodeError:\t" + str(e))
print("Something went wrong when reading the .gml file relating to the decoding of UNICODE.")
import time as time
fPath+="_" +str(time.time())
print("To avoid losing data, the output file will be renamed to use the timestamp as:\n" + fPath + "_" + str(time.time()))
print()
# No information has been recovered
oldData = nx.Graph()
except Exception as e:
# No information has been recovered
oldData = nx.Graph()
newGraph = _generateGraphData(d, oldData)
# Writing the gml file
nx.write_gml(newGraph,fPath) | python | def usufyToGmlExport(d, fPath):
"""
Workaround to export data to a .gml file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
# Reading the previous gml file
try:
oldData=nx.read_gml(fPath)
except UnicodeDecodeError as e:
print("UnicodeDecodeError:\t" + str(e))
print("Something went wrong when reading the .gml file relating to the decoding of UNICODE.")
import time as time
fPath+="_" +str(time.time())
print("To avoid losing data, the output file will be renamed to use the timestamp as:\n" + fPath + "_" + str(time.time()))
print()
# No information has been recovered
oldData = nx.Graph()
except Exception as e:
# No information has been recovered
oldData = nx.Graph()
newGraph = _generateGraphData(d, oldData)
# Writing the gml file
nx.write_gml(newGraph,fPath) | [
"def",
"usufyToGmlExport",
"(",
"d",
",",
"fPath",
")",
":",
"# Reading the previous gml file",
"try",
":",
"oldData",
"=",
"nx",
".",
"read_gml",
"(",
"fPath",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"print",
"(",
"\"UnicodeDecodeError:\\t\"",
"+",
"str",
"(",
"e",
")",
")",
"print",
"(",
"\"Something went wrong when reading the .gml file relating to the decoding of UNICODE.\"",
")",
"import",
"time",
"as",
"time",
"fPath",
"+=",
"\"_\"",
"+",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
"print",
"(",
"\"To avoid losing data, the output file will be renamed to use the timestamp as:\\n\"",
"+",
"fPath",
"+",
"\"_\"",
"+",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"print",
"(",
")",
"# No information has been recovered",
"oldData",
"=",
"nx",
".",
"Graph",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"# No information has been recovered",
"oldData",
"=",
"nx",
".",
"Graph",
"(",
")",
"newGraph",
"=",
"_generateGraphData",
"(",
"d",
",",
"oldData",
")",
"# Writing the gml file",
"nx",
".",
"write_gml",
"(",
"newGraph",
",",
"fPath",
")"
] | Workaround to export data to a .gml file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"data",
"to",
"a",
".",
"gml",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L597-L625 | train | 238,291 |
i3visio/osrframework | osrframework/utils/general.py | usufyToPngExport | def usufyToPngExport(d, fPath):
"""
Workaround to export to a png file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
newGraph = _generateGraphData(d)
import matplotlib.pyplot as plt
# Writing the png file
nx.draw(newGraph)
plt.savefig(fPath) | python | def usufyToPngExport(d, fPath):
"""
Workaround to export to a png file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
newGraph = _generateGraphData(d)
import matplotlib.pyplot as plt
# Writing the png file
nx.draw(newGraph)
plt.savefig(fPath) | [
"def",
"usufyToPngExport",
"(",
"d",
",",
"fPath",
")",
":",
"newGraph",
"=",
"_generateGraphData",
"(",
"d",
")",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# Writing the png file",
"nx",
".",
"draw",
"(",
"newGraph",
")",
"plt",
".",
"savefig",
"(",
"fPath",
")"
] | Workaround to export to a png file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | [
"Workaround",
"to",
"export",
"to",
"a",
"png",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L628-L642 | train | 238,292 |
i3visio/osrframework | osrframework/utils/general.py | fileToMD5 | def fileToMD5(filename, block_size=256*128, binary=False):
"""
A function that calculates the MD5 hash of a file.
Args:
-----
filename: Path to the file.
block_size: Chunks of suitable size. Block size directly depends on
the block size of your filesystem to avoid performances issues.
Blocks of 4096 octets (Default NTFS).
binary: A boolean representing whether the returned info is in binary
format or not.
Returns:
--------
string: The MD5 hash of the file.
"""
md5 = hashlib.md5()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
if not binary:
return md5.hexdigest()
return md5.digest() | python | def fileToMD5(filename, block_size=256*128, binary=False):
"""
A function that calculates the MD5 hash of a file.
Args:
-----
filename: Path to the file.
block_size: Chunks of suitable size. Block size directly depends on
the block size of your filesystem to avoid performances issues.
Blocks of 4096 octets (Default NTFS).
binary: A boolean representing whether the returned info is in binary
format or not.
Returns:
--------
string: The MD5 hash of the file.
"""
md5 = hashlib.md5()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
if not binary:
return md5.hexdigest()
return md5.digest() | [
"def",
"fileToMD5",
"(",
"filename",
",",
"block_size",
"=",
"256",
"*",
"128",
",",
"binary",
"=",
"False",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"block_size",
")",
",",
"b''",
")",
":",
"md5",
".",
"update",
"(",
"chunk",
")",
"if",
"not",
"binary",
":",
"return",
"md5",
".",
"hexdigest",
"(",
")",
"return",
"md5",
".",
"digest",
"(",
")"
] | A function that calculates the MD5 hash of a file.
Args:
-----
filename: Path to the file.
block_size: Chunks of suitable size. Block size directly depends on
the block size of your filesystem to avoid performances issues.
Blocks of 4096 octets (Default NTFS).
binary: A boolean representing whether the returned info is in binary
format or not.
Returns:
--------
string: The MD5 hash of the file. | [
"A",
"function",
"that",
"calculates",
"the",
"MD5",
"hash",
"of",
"a",
"file",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L645-L668 | train | 238,293 |
i3visio/osrframework | osrframework/utils/general.py | getCurrentStrDatetime | def getCurrentStrDatetime():
"""
Generating the current Datetime with a given format
Returns:
--------
string: The string of a date.
"""
# Generating current time
i = datetime.datetime.now()
strTime = "%s-%s-%s_%sh%sm" % (i.year, i.month, i.day, i.hour, i.minute)
return strTime | python | def getCurrentStrDatetime():
"""
Generating the current Datetime with a given format
Returns:
--------
string: The string of a date.
"""
# Generating current time
i = datetime.datetime.now()
strTime = "%s-%s-%s_%sh%sm" % (i.year, i.month, i.day, i.hour, i.minute)
return strTime | [
"def",
"getCurrentStrDatetime",
"(",
")",
":",
"# Generating current time",
"i",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"strTime",
"=",
"\"%s-%s-%s_%sh%sm\"",
"%",
"(",
"i",
".",
"year",
",",
"i",
".",
"month",
",",
"i",
".",
"day",
",",
"i",
".",
"hour",
",",
"i",
".",
"minute",
")",
"return",
"strTime"
] | Generating the current Datetime with a given format
Returns:
--------
string: The string of a date. | [
"Generating",
"the",
"current",
"Datetime",
"with",
"a",
"given",
"format"
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L671-L682 | train | 238,294 |
i3visio/osrframework | osrframework/utils/general.py | getFilesFromAFolder | def getFilesFromAFolder(path):
"""
Getting all the files in a folder.
Args:
-----
path: The path in which looking for the files
Returns:
--------
list: The list of filenames found.
"""
from os import listdir
from os.path import isfile, join
#onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
onlyFiles = []
for f in listdir(path):
if isfile(join(path, f)):
onlyFiles.append(f)
return onlyFiles | python | def getFilesFromAFolder(path):
"""
Getting all the files in a folder.
Args:
-----
path: The path in which looking for the files
Returns:
--------
list: The list of filenames found.
"""
from os import listdir
from os.path import isfile, join
#onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]
onlyFiles = []
for f in listdir(path):
if isfile(join(path, f)):
onlyFiles.append(f)
return onlyFiles | [
"def",
"getFilesFromAFolder",
"(",
"path",
")",
":",
"from",
"os",
"import",
"listdir",
"from",
"os",
".",
"path",
"import",
"isfile",
",",
"join",
"#onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ]",
"onlyFiles",
"=",
"[",
"]",
"for",
"f",
"in",
"listdir",
"(",
"path",
")",
":",
"if",
"isfile",
"(",
"join",
"(",
"path",
",",
"f",
")",
")",
":",
"onlyFiles",
".",
"append",
"(",
"f",
")",
"return",
"onlyFiles"
] | Getting all the files in a folder.
Args:
-----
path: The path in which looking for the files
Returns:
--------
list: The list of filenames found. | [
"Getting",
"all",
"the",
"files",
"in",
"a",
"folder",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L685-L704 | train | 238,295 |
i3visio/osrframework | osrframework/utils/general.py | urisToBrowser | def urisToBrowser(uris=[], autoraise=True):
"""
Method that launches the URI in the default browser of the system
This function temporally deactivates the standard ouptut and errors to
prevent the system to show unwanted messages. This method is based on this
question from Stackoverflow.
https://stackoverflow.com/questions/2323080/how-can-i-disable-the-webbrowser-message-in-python
Args:
-----
uri: a list of strings representing the URI to be opened in the browser.
"""
# Cloning stdout (1) and stderr (2)
savout1 = os.dup(1)
savout2 = os.dup(2)
# Closing them
os.close(1)
os.close(2)
os.open(os.devnull, os.O_RDWR)
try:
for uri in uris:
# Opening the Tor URI using onion.cab proxy
if ".onion" in uri:
wb.open(uri.replace(".onion", ".onion.city"), new=2, autoraise=autoraise)
else:
wb.open(uri, new=2, autoraise=autoraise)
finally:
# Reopening them...
os.dup2(savout1, 1)
os.dup2(savout2, 2) | python | def urisToBrowser(uris=[], autoraise=True):
"""
Method that launches the URI in the default browser of the system
This function temporally deactivates the standard ouptut and errors to
prevent the system to show unwanted messages. This method is based on this
question from Stackoverflow.
https://stackoverflow.com/questions/2323080/how-can-i-disable-the-webbrowser-message-in-python
Args:
-----
uri: a list of strings representing the URI to be opened in the browser.
"""
# Cloning stdout (1) and stderr (2)
savout1 = os.dup(1)
savout2 = os.dup(2)
# Closing them
os.close(1)
os.close(2)
os.open(os.devnull, os.O_RDWR)
try:
for uri in uris:
# Opening the Tor URI using onion.cab proxy
if ".onion" in uri:
wb.open(uri.replace(".onion", ".onion.city"), new=2, autoraise=autoraise)
else:
wb.open(uri, new=2, autoraise=autoraise)
finally:
# Reopening them...
os.dup2(savout1, 1)
os.dup2(savout2, 2) | [
"def",
"urisToBrowser",
"(",
"uris",
"=",
"[",
"]",
",",
"autoraise",
"=",
"True",
")",
":",
"# Cloning stdout (1) and stderr (2)",
"savout1",
"=",
"os",
".",
"dup",
"(",
"1",
")",
"savout2",
"=",
"os",
".",
"dup",
"(",
"2",
")",
"# Closing them",
"os",
".",
"close",
"(",
"1",
")",
"os",
".",
"close",
"(",
"2",
")",
"os",
".",
"open",
"(",
"os",
".",
"devnull",
",",
"os",
".",
"O_RDWR",
")",
"try",
":",
"for",
"uri",
"in",
"uris",
":",
"# Opening the Tor URI using onion.cab proxy",
"if",
"\".onion\"",
"in",
"uri",
":",
"wb",
".",
"open",
"(",
"uri",
".",
"replace",
"(",
"\".onion\"",
",",
"\".onion.city\"",
")",
",",
"new",
"=",
"2",
",",
"autoraise",
"=",
"autoraise",
")",
"else",
":",
"wb",
".",
"open",
"(",
"uri",
",",
"new",
"=",
"2",
",",
"autoraise",
"=",
"autoraise",
")",
"finally",
":",
"# Reopening them...",
"os",
".",
"dup2",
"(",
"savout1",
",",
"1",
")",
"os",
".",
"dup2",
"(",
"savout2",
",",
"2",
")"
] | Method that launches the URI in the default browser of the system
This function temporally deactivates the standard ouptut and errors to
prevent the system to show unwanted messages. This method is based on this
question from Stackoverflow.
https://stackoverflow.com/questions/2323080/how-can-i-disable-the-webbrowser-message-in-python
Args:
-----
uri: a list of strings representing the URI to be opened in the browser. | [
"Method",
"that",
"launches",
"the",
"URI",
"in",
"the",
"default",
"browser",
"of",
"the",
"system"
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L707-L740 | train | 238,296 |
i3visio/osrframework | osrframework/utils/general.py | openResultsInBrowser | def openResultsInBrowser(res):
"""
Method that collects the URI from a list of entities and opens them
Args:
-----
res: A list containing several i3visio entities.
"""
print(emphasis("\n\tOpening URIs in the default web browser..."))
urisToBrowser(["https://github.com/i3visio/osrframework"], autoraise=False)
# Waiting 2 seconds to confirm that the browser is opened and prevent the OS from opening several windows
time.sleep(2)
uris = []
for r in res:
for att in r["attributes"]:
if att["type"] == "i3visio.uri":
uris.append(att["value"])
urisToBrowser(uris) | python | def openResultsInBrowser(res):
"""
Method that collects the URI from a list of entities and opens them
Args:
-----
res: A list containing several i3visio entities.
"""
print(emphasis("\n\tOpening URIs in the default web browser..."))
urisToBrowser(["https://github.com/i3visio/osrframework"], autoraise=False)
# Waiting 2 seconds to confirm that the browser is opened and prevent the OS from opening several windows
time.sleep(2)
uris = []
for r in res:
for att in r["attributes"]:
if att["type"] == "i3visio.uri":
uris.append(att["value"])
urisToBrowser(uris) | [
"def",
"openResultsInBrowser",
"(",
"res",
")",
":",
"print",
"(",
"emphasis",
"(",
"\"\\n\\tOpening URIs in the default web browser...\"",
")",
")",
"urisToBrowser",
"(",
"[",
"\"https://github.com/i3visio/osrframework\"",
"]",
",",
"autoraise",
"=",
"False",
")",
"# Waiting 2 seconds to confirm that the browser is opened and prevent the OS from opening several windows",
"time",
".",
"sleep",
"(",
"2",
")",
"uris",
"=",
"[",
"]",
"for",
"r",
"in",
"res",
":",
"for",
"att",
"in",
"r",
"[",
"\"attributes\"",
"]",
":",
"if",
"att",
"[",
"\"type\"",
"]",
"==",
"\"i3visio.uri\"",
":",
"uris",
".",
"append",
"(",
"att",
"[",
"\"value\"",
"]",
")",
"urisToBrowser",
"(",
"uris",
")"
] | Method that collects the URI from a list of entities and opens them
Args:
-----
res: A list containing several i3visio entities. | [
"Method",
"that",
"collects",
"the",
"URI",
"from",
"a",
"list",
"of",
"entities",
"and",
"opens",
"them"
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L743-L763 | train | 238,297 |
i3visio/osrframework | osrframework/utils/general.py | colorize | def colorize(text, messageType=None):
"""
Function that colorizes a message.
Args:
-----
text: The string to be colorized.
messageType: Possible options include "ERROR", "WARNING", "SUCCESS",
"INFO" or "BOLD".
Returns:
--------
string: Colorized if the option is correct, including a tag at the end
to reset the formatting.
"""
formattedText = str(text)
# Set colors
if "ERROR" in messageType:
formattedText = colorama.Fore.RED + formattedText
elif "WARNING" in messageType:
formattedText = colorama.Fore.YELLOW + formattedText
elif "SUCCESS" in messageType:
formattedText = colorama.Fore.GREEN + formattedText
elif "INFO" in messageType:
formattedText = colorama.Fore.BLUE + formattedText
# Set emphashis mode
if "BOLD" in messageType:
formattedText = colorama.Style.BRIGHT + formattedText
return formattedText + colorama.Style.RESET_ALL | python | def colorize(text, messageType=None):
"""
Function that colorizes a message.
Args:
-----
text: The string to be colorized.
messageType: Possible options include "ERROR", "WARNING", "SUCCESS",
"INFO" or "BOLD".
Returns:
--------
string: Colorized if the option is correct, including a tag at the end
to reset the formatting.
"""
formattedText = str(text)
# Set colors
if "ERROR" in messageType:
formattedText = colorama.Fore.RED + formattedText
elif "WARNING" in messageType:
formattedText = colorama.Fore.YELLOW + formattedText
elif "SUCCESS" in messageType:
formattedText = colorama.Fore.GREEN + formattedText
elif "INFO" in messageType:
formattedText = colorama.Fore.BLUE + formattedText
# Set emphashis mode
if "BOLD" in messageType:
formattedText = colorama.Style.BRIGHT + formattedText
return formattedText + colorama.Style.RESET_ALL | [
"def",
"colorize",
"(",
"text",
",",
"messageType",
"=",
"None",
")",
":",
"formattedText",
"=",
"str",
"(",
"text",
")",
"# Set colors",
"if",
"\"ERROR\"",
"in",
"messageType",
":",
"formattedText",
"=",
"colorama",
".",
"Fore",
".",
"RED",
"+",
"formattedText",
"elif",
"\"WARNING\"",
"in",
"messageType",
":",
"formattedText",
"=",
"colorama",
".",
"Fore",
".",
"YELLOW",
"+",
"formattedText",
"elif",
"\"SUCCESS\"",
"in",
"messageType",
":",
"formattedText",
"=",
"colorama",
".",
"Fore",
".",
"GREEN",
"+",
"formattedText",
"elif",
"\"INFO\"",
"in",
"messageType",
":",
"formattedText",
"=",
"colorama",
".",
"Fore",
".",
"BLUE",
"+",
"formattedText",
"# Set emphashis mode",
"if",
"\"BOLD\"",
"in",
"messageType",
":",
"formattedText",
"=",
"colorama",
".",
"Style",
".",
"BRIGHT",
"+",
"formattedText",
"return",
"formattedText",
"+",
"colorama",
".",
"Style",
".",
"RESET_ALL"
] | Function that colorizes a message.
Args:
-----
text: The string to be colorized.
messageType: Possible options include "ERROR", "WARNING", "SUCCESS",
"INFO" or "BOLD".
Returns:
--------
string: Colorized if the option is correct, including a tag at the end
to reset the formatting. | [
"Function",
"that",
"colorizes",
"a",
"message",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L766-L796 | train | 238,298 |
i3visio/osrframework | osrframework/utils/general.py | showLicense | def showLicense():
"""
Method that prints the license if requested.
It tries to find the license online and manually download it. This method
only prints its contents in plain text.
"""
print("Trying to recover the contents of the license...\n")
try:
# Grab the license online and print it.
text = urllib.urlopen(LICENSE_URL).read()
print("License retrieved from " + emphasis(LICENSE_URL) + ".")
raw_input("\n\tPress " + emphasis("<ENTER>") + " to print it.\n")
print(text)
except:
print(warning("The license could not be downloaded and printed.")) | python | def showLicense():
"""
Method that prints the license if requested.
It tries to find the license online and manually download it. This method
only prints its contents in plain text.
"""
print("Trying to recover the contents of the license...\n")
try:
# Grab the license online and print it.
text = urllib.urlopen(LICENSE_URL).read()
print("License retrieved from " + emphasis(LICENSE_URL) + ".")
raw_input("\n\tPress " + emphasis("<ENTER>") + " to print it.\n")
print(text)
except:
print(warning("The license could not be downloaded and printed.")) | [
"def",
"showLicense",
"(",
")",
":",
"print",
"(",
"\"Trying to recover the contents of the license...\\n\"",
")",
"try",
":",
"# Grab the license online and print it.",
"text",
"=",
"urllib",
".",
"urlopen",
"(",
"LICENSE_URL",
")",
".",
"read",
"(",
")",
"print",
"(",
"\"License retrieved from \"",
"+",
"emphasis",
"(",
"LICENSE_URL",
")",
"+",
"\".\"",
")",
"raw_input",
"(",
"\"\\n\\tPress \"",
"+",
"emphasis",
"(",
"\"<ENTER>\"",
")",
"+",
"\" to print it.\\n\"",
")",
"print",
"(",
"text",
")",
"except",
":",
"print",
"(",
"warning",
"(",
"\"The license could not be downloaded and printed.\"",
")",
")"
] | Method that prints the license if requested.
It tries to find the license online and manually download it. This method
only prints its contents in plain text. | [
"Method",
"that",
"prints",
"the",
"license",
"if",
"requested",
"."
] | 83437f4c14c9c08cb80a896bd9834c77f6567871 | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L823-L838 | train | 238,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.