repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Parquery/icontract | icontract/_checkers.py | _capture_snapshot | def _capture_snapshot(a_snapshot: Snapshot, resolved_kwargs: Mapping[str, Any]) -> Any:
"""
Capture the snapshot from the keyword arguments resolved before the function call (including the default values).
:param a_snapshot: snapshot to be captured
:param resolved_kwargs: resolved keyword arguments (in... | python | def _capture_snapshot(a_snapshot: Snapshot, resolved_kwargs: Mapping[str, Any]) -> Any:
"""
Capture the snapshot from the keyword arguments resolved before the function call (including the default values).
:param a_snapshot: snapshot to be captured
:param resolved_kwargs: resolved keyword arguments (in... | [
"def",
"_capture_snapshot",
"(",
"a_snapshot",
":",
"Snapshot",
",",
"resolved_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"if",
"a_snapshot",
".",
"arg",
"is",
"not",
"None",
":",
"if",
"a_snapshot",
".",
"arg",
"not",
... | Capture the snapshot from the keyword arguments resolved before the function call (including the default values).
:param a_snapshot: snapshot to be captured
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return: captured value | [
"Capture",
"the",
"snapshot",
"from",
"the",
"keyword",
"arguments",
"resolved",
"before",
"the",
"function",
"call",
"(",
"including",
"the",
"default",
"values",
")",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L153-L171 |
Parquery/icontract | icontract/_checkers.py | decorate_with_checker | def decorate_with_checker(func: CallableT) -> CallableT:
"""Decorate the function with a checker that verifies the preconditions and postconditions."""
assert not hasattr(func, "__preconditions__"), \
"Expected func to have no list of preconditions (there should be only a single contract checker per fun... | python | def decorate_with_checker(func: CallableT) -> CallableT:
"""Decorate the function with a checker that verifies the preconditions and postconditions."""
assert not hasattr(func, "__preconditions__"), \
"Expected func to have no list of preconditions (there should be only a single contract checker per fun... | [
"def",
"decorate_with_checker",
"(",
"func",
":",
"CallableT",
")",
"->",
"CallableT",
":",
"assert",
"not",
"hasattr",
"(",
"func",
",",
"\"__preconditions__\"",
")",
",",
"\"Expected func to have no list of preconditions (there should be only a single contract checker per fun... | Decorate the function with a checker that verifies the preconditions and postconditions. | [
"Decorate",
"the",
"function",
"with",
"a",
"checker",
"that",
"verifies",
"the",
"preconditions",
"and",
"postconditions",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L252-L346 |
Parquery/icontract | icontract/_checkers.py | _find_self | def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
"""Find the instance of ``self`` in the arguments."""
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return in... | python | def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
"""Find the instance of ``self`` in the arguments."""
instance_i = param_names.index("self")
if instance_i < len(args):
instance = args[instance_i]
else:
instance = kwargs["self"]
return in... | [
"def",
"_find_self",
"(",
"param_names",
":",
"List",
"[",
"str",
"]",
",",
"args",
":",
"Tuple",
"[",
"Any",
",",
"...",
"]",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"instance_i",
"=",
"param_names",
".",
... | Find the instance of ``self`` in the arguments. | [
"Find",
"the",
"instance",
"of",
"self",
"in",
"the",
"arguments",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L349-L357 |
Parquery/icontract | icontract/_checkers.py | _decorate_with_invariants | def _decorate_with_invariants(func: CallableT, is_init: bool) -> CallableT:
"""
Decorate the function ``func`` of the class ``cls`` with invariant checks.
If the function has been already decorated with invariant checks, the function returns immediately.
:param func: function to be wrapped
:param ... | python | def _decorate_with_invariants(func: CallableT, is_init: bool) -> CallableT:
"""
Decorate the function ``func`` of the class ``cls`` with invariant checks.
If the function has been already decorated with invariant checks, the function returns immediately.
:param func: function to be wrapped
:param ... | [
"def",
"_decorate_with_invariants",
"(",
"func",
":",
"CallableT",
",",
"is_init",
":",
"bool",
")",
"->",
"CallableT",
":",
"if",
"_already_decorated_with_invariants",
"(",
"func",
"=",
"func",
")",
":",
"return",
"func",
"sign",
"=",
"inspect",
".",
"signatu... | Decorate the function ``func`` of the class ``cls`` with invariant checks.
If the function has been already decorated with invariant checks, the function returns immediately.
:param func: function to be wrapped
:param is_init: True if the ``func`` is __init__
:return: function wrapped with invariant c... | [
"Decorate",
"the",
"function",
"func",
"of",
"the",
"class",
"cls",
"with",
"invariant",
"checks",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L360-L407 |
Parquery/icontract | icontract/_checkers.py | _already_decorated_with_invariants | def _already_decorated_with_invariants(func: CallableT) -> bool:
"""Check if the function has been already decorated with an invariant check by going through its decorator stack."""
already_decorated = False
for a_decorator in _walk_decorator_stack(func=func):
if getattr(a_decorator, "__is_invariant... | python | def _already_decorated_with_invariants(func: CallableT) -> bool:
"""Check if the function has been already decorated with an invariant check by going through its decorator stack."""
already_decorated = False
for a_decorator in _walk_decorator_stack(func=func):
if getattr(a_decorator, "__is_invariant... | [
"def",
"_already_decorated_with_invariants",
"(",
"func",
":",
"CallableT",
")",
"->",
"bool",
":",
"already_decorated",
"=",
"False",
"for",
"a_decorator",
"in",
"_walk_decorator_stack",
"(",
"func",
"=",
"func",
")",
":",
"if",
"getattr",
"(",
"a_decorator",
"... | Check if the function has been already decorated with an invariant check by going through its decorator stack. | [
"Check",
"if",
"the",
"function",
"has",
"been",
"already",
"decorated",
"with",
"an",
"invariant",
"check",
"by",
"going",
"through",
"its",
"decorator",
"stack",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L417-L425 |
Parquery/icontract | icontract/_checkers.py | add_invariant_checks | def add_invariant_checks(cls: type) -> None:
"""Decorate each of the class functions with invariant checks if not already decorated."""
# Candidates for the decoration as list of (name, dir() value)
init_name_func = None # type: Optional[Tuple[str, Callable[..., None]]]
names_funcs = [] # type: List[T... | python | def add_invariant_checks(cls: type) -> None:
"""Decorate each of the class functions with invariant checks if not already decorated."""
# Candidates for the decoration as list of (name, dir() value)
init_name_func = None # type: Optional[Tuple[str, Callable[..., None]]]
names_funcs = [] # type: List[T... | [
"def",
"add_invariant_checks",
"(",
"cls",
":",
"type",
")",
"->",
"None",
":",
"# Candidates for the decoration as list of (name, dir() value)",
"init_name_func",
"=",
"None",
"# type: Optional[Tuple[str, Callable[..., None]]]",
"names_funcs",
"=",
"[",
"]",
"# type: List[Tupl... | Decorate each of the class functions with invariant checks if not already decorated. | [
"Decorate",
"each",
"of",
"the",
"class",
"functions",
"with",
"invariant",
"checks",
"if",
"not",
"already",
"decorated",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L428-L486 |
Parquery/icontract | benchmarks/import_cost/measure.py | main | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--module", help="name of the module to import",
choices=[
"functions_100_with_no_contract",
"functi... | python | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--module", help="name of the module to import",
choices=[
"functions_100_with_no_contract",
"functi... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"--module\"",
",",
"help",
"=",
"\"name of the module to import\"",
",",
"choices",
"="... | Execute the main routine. | [
"Execute",
"the",
"main",
"routine",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/benchmarks/import_cost/measure.py#L13-L114 |
Parquery/icontract | benchmarks/import_cost/runme.py | main | def main() -> None:
""""Execute the main routine."""
modules = [
"functions_100_with_no_contract",
"functions_100_with_1_contract",
"functions_100_with_5_contracts",
"functions_100_with_10_contracts",
"functions_100_with_1_disabled_contract",
"functions_100_with... | python | def main() -> None:
""""Execute the main routine."""
modules = [
"functions_100_with_no_contract",
"functions_100_with_1_contract",
"functions_100_with_5_contracts",
"functions_100_with_10_contracts",
"functions_100_with_1_disabled_contract",
"functions_100_with... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"modules",
"=",
"[",
"\"functions_100_with_no_contract\"",
",",
"\"functions_100_with_1_contract\"",
",",
"\"functions_100_with_5_contracts\"",
",",
"\"functions_100_with_10_contracts\"",
",",
"\"functions_100_with_1_disabled_contract\"... | Execute the main routine. | [
"Execute",
"the",
"main",
"routine",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/benchmarks/import_cost/runme.py#L10-L42 |
Parquery/icontract | benchmarks/import_cost/generate.py | main | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__))
args = parser.parse_args()
outdir = pathlib.Path(args.outdir)
if not outdir.exists():
ra... | python | def main() -> None:
""""Execute the main routine."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__))
args = parser.parse_args()
outdir = pathlib.Path(args.outdir)
if not outdir.exists():
ra... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"--outdir\"",
",",
"help",
"=",
"\"output directory\"",
",",
"default",
"=",
"os",
... | Execute the main routine. | [
"Execute",
"the",
"main",
"routine",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/benchmarks/import_cost/generate.py#L60-L108 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Num | def visit_Num(self, node: ast.Num) -> Union[int, float]:
"""Recompute the value as the number at the node."""
result = node.n
self.recomputed_values[node] = result
return result | python | def visit_Num(self, node: ast.Num) -> Union[int, float]:
"""Recompute the value as the number at the node."""
result = node.n
self.recomputed_values[node] = result
return result | [
"def",
"visit_Num",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Num",
")",
"->",
"Union",
"[",
"int",
",",
"float",
"]",
":",
"result",
"=",
"node",
".",
"n",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"result"
] | Recompute the value as the number at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"number",
"at",
"the",
"node",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L48-L53 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Str | def visit_Str(self, node: ast.Str) -> str:
"""Recompute the value as the string at the node."""
result = node.s
self.recomputed_values[node] = result
return result | python | def visit_Str(self, node: ast.Str) -> str:
"""Recompute the value as the string at the node."""
result = node.s
self.recomputed_values[node] = result
return result | [
"def",
"visit_Str",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Str",
")",
"->",
"str",
":",
"result",
"=",
"node",
".",
"s",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"result"
] | Recompute the value as the string at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"string",
"at",
"the",
"node",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L55-L60 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Bytes | def visit_Bytes(self, node: ast.Bytes) -> bytes:
"""Recompute the value as the bytes at the node."""
result = node.s
self.recomputed_values[node] = result
return node.s | python | def visit_Bytes(self, node: ast.Bytes) -> bytes:
"""Recompute the value as the bytes at the node."""
result = node.s
self.recomputed_values[node] = result
return node.s | [
"def",
"visit_Bytes",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Bytes",
")",
"->",
"bytes",
":",
"result",
"=",
"node",
".",
"s",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"return",
"node",
".",
"s"
] | Recompute the value as the bytes at the node. | [
"Recompute",
"the",
"value",
"as",
"the",
"bytes",
"at",
"the",
"node",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L62-L67 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_List | def visit_List(self, node: ast.List) -> List[Any]:
"""Visit the elements and assemble the results into a list."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a list")
result = [self.visit(node=elt) for elt in node.elts]
... | python | def visit_List(self, node: ast.List) -> List[Any]:
"""Visit the elements and assemble the results into a list."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a list")
result = [self.visit(node=elt) for elt in node.elts]
... | [
"def",
"visit_List",
"(",
"self",
",",
"node",
":",
"ast",
".",
"List",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"if",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Store",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Can not compute th... | Visit the elements and assemble the results into a list. | [
"Visit",
"the",
"elements",
"and",
"assemble",
"the",
"results",
"into",
"a",
"list",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L69-L77 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Tuple | def visit_Tuple(self, node: ast.Tuple) -> Tuple[Any, ...]:
"""Visit the elements and assemble the results into a tuple."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a tuple")
result = tuple(self.visit(node=elt) for elt in ... | python | def visit_Tuple(self, node: ast.Tuple) -> Tuple[Any, ...]:
"""Visit the elements and assemble the results into a tuple."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a tuple")
result = tuple(self.visit(node=elt) for elt in ... | [
"def",
"visit_Tuple",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Tuple",
")",
"->",
"Tuple",
"[",
"Any",
",",
"...",
"]",
":",
"if",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Store",
")",
":",
"raise",
"NotImplementedError",
"(",
"\... | Visit the elements and assemble the results into a tuple. | [
"Visit",
"the",
"elements",
"and",
"assemble",
"the",
"results",
"into",
"a",
"tuple",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L79-L87 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Set | def visit_Set(self, node: ast.Set) -> Set[Any]:
"""Visit the elements and assemble the results into a set."""
result = set(self.visit(node=elt) for elt in node.elts)
self.recomputed_values[node] = result
return result | python | def visit_Set(self, node: ast.Set) -> Set[Any]:
"""Visit the elements and assemble the results into a set."""
result = set(self.visit(node=elt) for elt in node.elts)
self.recomputed_values[node] = result
return result | [
"def",
"visit_Set",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Set",
")",
"->",
"Set",
"[",
"Any",
"]",
":",
"result",
"=",
"set",
"(",
"self",
".",
"visit",
"(",
"node",
"=",
"elt",
")",
"for",
"elt",
"in",
"node",
".",
"elts",
")",
"self",
... | Visit the elements and assemble the results into a set. | [
"Visit",
"the",
"elements",
"and",
"assemble",
"the",
"results",
"into",
"a",
"set",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L89-L94 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Dict | def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]:
"""Visit keys and values and assemble a dictionary with the results."""
recomputed_dict = dict() # type: Dict[Any, Any]
for key, val in zip(node.keys, node.values):
recomputed_dict[self.visit(node=key)] = self.visit(node=val)
... | python | def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]:
"""Visit keys and values and assemble a dictionary with the results."""
recomputed_dict = dict() # type: Dict[Any, Any]
for key, val in zip(node.keys, node.values):
recomputed_dict[self.visit(node=key)] = self.visit(node=val)
... | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Dict",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"recomputed_dict",
"=",
"dict",
"(",
")",
"# type: Dict[Any, Any]",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"node",
".",
... | Visit keys and values and assemble a dictionary with the results. | [
"Visit",
"keys",
"and",
"values",
"and",
"assemble",
"a",
"dictionary",
"with",
"the",
"results",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L96-L103 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_NameConstant | def visit_NameConstant(self, node: ast.NameConstant) -> Any:
"""Forward the node value as a result."""
self.recomputed_values[node] = node.value
return node.value | python | def visit_NameConstant(self, node: ast.NameConstant) -> Any:
"""Forward the node value as a result."""
self.recomputed_values[node] = node.value
return node.value | [
"def",
"visit_NameConstant",
"(",
"self",
",",
"node",
":",
"ast",
".",
"NameConstant",
")",
"->",
"Any",
":",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"node",
".",
"value",
"return",
"node",
".",
"value"
] | Forward the node value as a result. | [
"Forward",
"the",
"node",
"value",
"as",
"a",
"result",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L105-L108 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Name | def visit_Name(self, node: ast.Name) -> Any:
"""Load the variable by looking it up in the variable look-up and in the built-ins."""
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format(
no... | python | def visit_Name(self, node: ast.Name) -> Any:
"""Load the variable by looking it up in the variable look-up and in the built-ins."""
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format(
no... | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Name",
")",
"->",
"Any",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Load",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Can only compute a value of Load o... | Load the variable by looking it up in the variable look-up and in the built-ins. | [
"Load",
"the",
"variable",
"by",
"looking",
"it",
"up",
"in",
"the",
"variable",
"look",
"-",
"up",
"and",
"in",
"the",
"built",
"-",
"ins",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L110-L130 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Expr | def visit_Expr(self, node: ast.Expr) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | python | def visit_Expr(self, node: ast.Expr) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | [
"def",
"visit_Expr",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Expr",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"value",
")",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"ret... | Visit the node's ``value``. | [
"Visit",
"the",
"node",
"s",
"value",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L132-L137 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_UnaryOp | def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
"""Visit the node operand and apply the operation on the result."""
if isinstance(node.op, ast.UAdd):
result = +self.visit(node=node.operand)
elif isinstance(node.op, ast.USub):
result = -self.visit(node=node.operand)
... | python | def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
"""Visit the node operand and apply the operation on the result."""
if isinstance(node.op, ast.UAdd):
result = +self.visit(node=node.operand)
elif isinstance(node.op, ast.USub):
result = -self.visit(node=node.operand)
... | [
"def",
"visit_UnaryOp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"UnaryOp",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"UAdd",
")",
":",
"result",
"=",
"+",
"self",
".",
"visit",
"(",
"node",
"=",
"node"... | Visit the node operand and apply the operation on the result. | [
"Visit",
"the",
"node",
"operand",
"and",
"apply",
"the",
"operation",
"on",
"the",
"result",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L139-L153 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_BinOp | def visit_BinOp(self, node: ast.BinOp) -> Any:
"""Recursively visit the left and right operand, respectively, and apply the operation on the results."""
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
right = self.visit(node=node.right)
if isinstance(node.o... | python | def visit_BinOp(self, node: ast.BinOp) -> Any:
"""Recursively visit the left and right operand, respectively, and apply the operation on the results."""
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
right = self.visit(node=node.right)
if isinstance(node.o... | [
"def",
"visit_BinOp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"BinOp",
")",
"->",
"Any",
":",
"# pylint: disable=too-many-branches",
"left",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"left",
")",
"right",
"=",
"self",
".",
"visit",
"... | Recursively visit the left and right operand, respectively, and apply the operation on the results. | [
"Recursively",
"visit",
"the",
"left",
"and",
"right",
"operand",
"respectively",
"and",
"apply",
"the",
"operation",
"on",
"the",
"results",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L155-L191 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_BoolOp | def visit_BoolOp(self, node: ast.BoolOp) -> Any:
"""Recursively visit the operands and apply the operation on them."""
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, value... | python | def visit_BoolOp(self, node: ast.BoolOp) -> Any:
"""Recursively visit the operands and apply the operation on them."""
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, value... | [
"def",
"visit_BoolOp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"BoolOp",
")",
"->",
"Any",
":",
"values",
"=",
"[",
"self",
".",
"visit",
"(",
"value_node",
")",
"for",
"value_node",
"in",
"node",
".",
"values",
"]",
"if",
"isinstance",
"(",
"node... | Recursively visit the operands and apply the operation on them. | [
"Recursively",
"visit",
"the",
"operands",
"and",
"apply",
"the",
"operation",
"on",
"them",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L193-L205 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Compare | def visit_Compare(self, node: ast.Compare) -> Any:
"""Recursively visit the comparators and apply the operations on them."""
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
comparators = [self.visit(node=comparator) for comparator in node.comparators]
resu... | python | def visit_Compare(self, node: ast.Compare) -> Any:
"""Recursively visit the comparators and apply the operations on them."""
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
comparators = [self.visit(node=comparator) for comparator in node.comparators]
resu... | [
"def",
"visit_Compare",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Compare",
")",
"->",
"Any",
":",
"# pylint: disable=too-many-branches",
"left",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"left",
")",
"comparators",
"=",
"[",
"self",
".... | Recursively visit the comparators and apply the operations on them. | [
"Recursively",
"visit",
"the",
"comparators",
"and",
"apply",
"the",
"operations",
"on",
"them",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L207-L247 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Call | def visit_Call(self, node: ast.Call) -> Any:
"""Visit the function and the arguments and finally make the function call with them."""
func = self.visit(node=node.func)
args = [] # type: List[Any]
for arg_node in node.args:
if isinstance(arg_node, ast.Starred):
... | python | def visit_Call(self, node: ast.Call) -> Any:
"""Visit the function and the arguments and finally make the function call with them."""
func = self.visit(node=node.func)
args = [] # type: List[Any]
for arg_node in node.args:
if isinstance(arg_node, ast.Starred):
... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Call",
")",
"->",
"Any",
":",
"func",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"func",
")",
"args",
"=",
"[",
"]",
"# type: List[Any]",
"for",
"arg_node",
"in",
"node... | Visit the function and the arguments and finally make the function call with them. | [
"Visit",
"the",
"function",
"and",
"the",
"arguments",
"and",
"finally",
"make",
"the",
"function",
"call",
"with",
"them",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L249-L273 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_IfExp | def visit_IfExp(self, node: ast.IfExp) -> Any:
"""Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``."""
test = self.visit(node=node.test)
if test:
result = self.visit(node=node.body)
else:
result = self.visit(node=node.orelse)
... | python | def visit_IfExp(self, node: ast.IfExp) -> Any:
"""Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``."""
test = self.visit(node=node.test)
if test:
result = self.visit(node=node.body)
else:
result = self.visit(node=node.orelse)
... | [
"def",
"visit_IfExp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"IfExp",
")",
"->",
"Any",
":",
"test",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"test",
")",
"if",
"test",
":",
"result",
"=",
"self",
".",
"visit",
"(",
"node",
... | Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``. | [
"Visit",
"the",
"test",
"and",
"depending",
"on",
"its",
"outcome",
"the",
"body",
"or",
"orelse",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L275-L285 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Attribute | def visit_Attribute(self, node: ast.Attribute) -> Any:
"""Visit the node's ``value`` and get the attribute from the result."""
value = self.visit(node=node.value)
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError(
"Can only compute a value of Load on th... | python | def visit_Attribute(self, node: ast.Attribute) -> Any:
"""Visit the node's ``value`` and get the attribute from the result."""
value = self.visit(node=node.value)
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError(
"Can only compute a value of Load on th... | [
"def",
"visit_Attribute",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Attribute",
")",
"->",
"Any",
":",
"value",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"value",
")",
"if",
"not",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast"... | Visit the node's ``value`` and get the attribute from the result. | [
"Visit",
"the",
"node",
"s",
"value",
"and",
"get",
"the",
"attribute",
"from",
"the",
"result",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L287-L297 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Index | def visit_Index(self, node: ast.Index) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | python | def visit_Index(self, node: ast.Index) -> Any:
"""Visit the node's ``value``."""
result = self.visit(node=node.value)
self.recomputed_values[node] = result
return result | [
"def",
"visit_Index",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Index",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"value",
")",
"self",
".",
"recomputed_values",
"[",
"node",
"]",
"=",
"result",
"r... | Visit the node's ``value``. | [
"Visit",
"the",
"node",
"s",
"value",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L299-L304 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Slice | def visit_Slice(self, node: ast.Slice) -> slice:
"""Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``."""
lower = None # type: Optional[int]
if node.lower is not None:
lower = self.visit(node=node.lower)
upper = None # type: Optional[int]
... | python | def visit_Slice(self, node: ast.Slice) -> slice:
"""Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``."""
lower = None # type: Optional[int]
if node.lower is not None:
lower = self.visit(node=node.lower)
upper = None # type: Optional[int]
... | [
"def",
"visit_Slice",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Slice",
")",
"->",
"slice",
":",
"lower",
"=",
"None",
"# type: Optional[int]",
"if",
"node",
".",
"lower",
"is",
"not",
"None",
":",
"lower",
"=",
"self",
".",
"visit",
"(",
"node",
"... | Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``. | [
"Visit",
"lower",
"upper",
"and",
"step",
"and",
"recompute",
"the",
"node",
"as",
"a",
"slice",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L306-L323 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_ExtSlice | def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]:
"""Visit each dimension of the advanced slicing and assemble the dimensions in a tuple."""
result = tuple(self.visit(node=dim) for dim in node.dims)
self.recomputed_values[node] = result
return result | python | def visit_ExtSlice(self, node: ast.ExtSlice) -> Tuple[Any, ...]:
"""Visit each dimension of the advanced slicing and assemble the dimensions in a tuple."""
result = tuple(self.visit(node=dim) for dim in node.dims)
self.recomputed_values[node] = result
return result | [
"def",
"visit_ExtSlice",
"(",
"self",
",",
"node",
":",
"ast",
".",
"ExtSlice",
")",
"->",
"Tuple",
"[",
"Any",
",",
"...",
"]",
":",
"result",
"=",
"tuple",
"(",
"self",
".",
"visit",
"(",
"node",
"=",
"dim",
")",
"for",
"dim",
"in",
"node",
"."... | Visit each dimension of the advanced slicing and assemble the dimensions in a tuple. | [
"Visit",
"each",
"dimension",
"of",
"the",
"advanced",
"slicing",
"and",
"assemble",
"the",
"dimensions",
"in",
"a",
"tuple",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L325-L330 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Subscript | def visit_Subscript(self, node: ast.Subscript) -> Any:
"""Visit the ``slice`` and a ``value`` and get the element."""
value = self.visit(node=node.value)
a_slice = self.visit(node=node.slice)
result = value[a_slice]
self.recomputed_values[node] = result
return result | python | def visit_Subscript(self, node: ast.Subscript) -> Any:
"""Visit the ``slice`` and a ``value`` and get the element."""
value = self.visit(node=node.value)
a_slice = self.visit(node=node.slice)
result = value[a_slice]
self.recomputed_values[node] = result
return result | [
"def",
"visit_Subscript",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Subscript",
")",
"->",
"Any",
":",
"value",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node",
".",
"value",
")",
"a_slice",
"=",
"self",
".",
"visit",
"(",
"node",
"=",
"node"... | Visit the ``slice`` and a ``value`` and get the element. | [
"Visit",
"the",
"slice",
"and",
"a",
"value",
"and",
"get",
"the",
"element",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L332-L340 |
Parquery/icontract | icontract/_recompute.py | Visitor._execute_comprehension | def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any:
"""Compile the generator or comprehension from the node and execute the compiled code."""
args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())]
func_def_node = as... | python | def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any:
"""Compile the generator or comprehension from the node and execute the compiled code."""
args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())]
func_def_node = as... | [
"def",
"_execute_comprehension",
"(",
"self",
",",
"node",
":",
"Union",
"[",
"ast",
".",
"ListComp",
",",
"ast",
".",
"SetComp",
",",
"ast",
".",
"GeneratorExp",
",",
"ast",
".",
"DictComp",
"]",
")",
"->",
"Any",
":",
"args",
"=",
"[",
"ast",
".",
... | Compile the generator or comprehension from the node and execute the compiled code. | [
"Compile",
"the",
"generator",
"or",
"comprehension",
"from",
"the",
"node",
"and",
"execute",
"the",
"compiled",
"code",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L342-L364 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_GeneratorExp | def visit_GeneratorExp(self, node: ast.GeneratorExp) -> Any:
"""Compile the generator expression as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
# Do not set the computed value of the... | python | def visit_GeneratorExp(self, node: ast.GeneratorExp) -> Any:
"""Compile the generator expression as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
# Do not set the computed value of the... | [
"def",
"visit_GeneratorExp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"GeneratorExp",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"_execute_comprehension",
"(",
"node",
"=",
"node",
")",
"for",
"generator",
"in",
"node",
".",
"generators",
":",
... | Compile the generator expression as a function and call it. | [
"Compile",
"the",
"generator",
"expression",
"as",
"a",
"function",
"and",
"call",
"it",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L366-L374 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_ListComp | def visit_ListComp(self, node: ast.ListComp) -> Any:
"""Compile the list comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
re... | python | def visit_ListComp(self, node: ast.ListComp) -> Any:
"""Compile the list comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
re... | [
"def",
"visit_ListComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"ListComp",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"_execute_comprehension",
"(",
"node",
"=",
"node",
")",
"for",
"generator",
"in",
"node",
".",
"generators",
":",
"self",
... | Compile the list comprehension as a function and call it. | [
"Compile",
"the",
"list",
"comprehension",
"as",
"a",
"function",
"and",
"call",
"it",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L376-L384 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_SetComp | def visit_SetComp(self, node: ast.SetComp) -> Any:
"""Compile the set comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
retur... | python | def visit_SetComp(self, node: ast.SetComp) -> Any:
"""Compile the set comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
retur... | [
"def",
"visit_SetComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"SetComp",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"_execute_comprehension",
"(",
"node",
"=",
"node",
")",
"for",
"generator",
"in",
"node",
".",
"generators",
":",
"self",
... | Compile the set comprehension as a function and call it. | [
"Compile",
"the",
"set",
"comprehension",
"as",
"a",
"function",
"and",
"call",
"it",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L386-L394 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_DictComp | def visit_DictComp(self, node: ast.DictComp) -> Any:
"""Compile the dictionary comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
... | python | def visit_DictComp(self, node: ast.DictComp) -> Any:
"""Compile the dictionary comprehension as a function and call it."""
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
... | [
"def",
"visit_DictComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"DictComp",
")",
"->",
"Any",
":",
"result",
"=",
"self",
".",
"_execute_comprehension",
"(",
"node",
"=",
"node",
")",
"for",
"generator",
"in",
"node",
".",
"generators",
":",
"self",
... | Compile the dictionary comprehension as a function and call it. | [
"Compile",
"the",
"dictionary",
"comprehension",
"as",
"a",
"function",
"and",
"call",
"it",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L396-L404 |
Parquery/icontract | icontract/_recompute.py | Visitor.visit_Return | def visit_Return(self, node: ast.Return) -> Any: # pylint: disable=no-self-use
"""Raise an exception that this node is unexpected."""
raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node))) | python | def visit_Return(self, node: ast.Return) -> Any: # pylint: disable=no-self-use
"""Raise an exception that this node is unexpected."""
raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node))) | [
"def",
"visit_Return",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Return",
")",
"->",
"Any",
":",
"# pylint: disable=no-self-use",
"raise",
"AssertionError",
"(",
"\"Unexpected return node during the re-computation: {}\"",
".",
"format",
"(",
"ast",
".",
"dump",
"(... | Raise an exception that this node is unexpected. | [
"Raise",
"an",
"exception",
"that",
"this",
"node",
"is",
"unexpected",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L413-L415 |
Parquery/icontract | icontract/_recompute.py | Visitor.generic_visit | def generic_visit(self, node: ast.AST) -> None:
"""Raise an exception that this node has not been handled."""
raise NotImplementedError("Unhandled recomputation of the node: {} {}".format(type(node), node)) | python | def generic_visit(self, node: ast.AST) -> None:
"""Raise an exception that this node has not been handled."""
raise NotImplementedError("Unhandled recomputation of the node: {} {}".format(type(node), node)) | [
"def",
"generic_visit",
"(",
"self",
",",
"node",
":",
"ast",
".",
"AST",
")",
"->",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Unhandled recomputation of the node: {} {}\"",
".",
"format",
"(",
"type",
"(",
"node",
")",
",",
"node",
")",
")"
] | Raise an exception that this node has not been handled. | [
"Raise",
"an",
"exception",
"that",
"this",
"node",
"has",
"not",
"been",
"handled",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L417-L419 |
lang-uk/tokenize-uk | tokenize_uk/tokenize_uk.py | tokenize_words | def tokenize_words(string):
"""
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
"""
string = six.text_type(string)
return re.findall(WORD_TOKENIZATION_RULES, string) | python | def tokenize_words(string):
"""
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
"""
string = six.text_type(string)
return re.findall(WORD_TOKENIZATION_RULES, string) | [
"def",
"tokenize_words",
"(",
"string",
")",
":",
"string",
"=",
"six",
".",
"text_type",
"(",
"string",
")",
"return",
"re",
".",
"findall",
"(",
"WORD_TOKENIZATION_RULES",
",",
"string",
")"
] | Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings | [
"Tokenize",
"input",
"text",
"to",
"words",
"."
] | train | https://github.com/lang-uk/tokenize-uk/blob/52769b0f43af29d4a5863a7836364b3b9c10dd09/tokenize_uk/tokenize_uk.py#L44-L54 |
lang-uk/tokenize-uk | tokenize_uk/tokenize_uk.py | tokenize_sents | def tokenize_sents(string):
"""
Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings
"""
string = six.text_type(string)
spans = []
for match in re.finditer('[^\s]+', string):
spans.appe... | python | def tokenize_sents(string):
"""
Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings
"""
string = six.text_type(string)
spans = []
for match in re.finditer('[^\s]+', string):
spans.appe... | [
"def",
"tokenize_sents",
"(",
"string",
")",
":",
"string",
"=",
"six",
".",
"text_type",
"(",
"string",
")",
"spans",
"=",
"[",
"]",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"'[^\\s]+'",
",",
"string",
")",
":",
"spans",
".",
"append",
"(",... | Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings | [
"Tokenize",
"input",
"text",
"to",
"sentences",
"."
] | train | https://github.com/lang-uk/tokenize-uk/blob/52769b0f43af29d4a5863a7836364b3b9c10dd09/tokenize_uk/tokenize_uk.py#L57-L91 |
lang-uk/tokenize-uk | tokenize_uk/tokenize_uk.py | tokenize_text | def tokenize_text(string):
"""
Tokenize input text to paragraphs, sentences and words.
Tokenization to paragraphs is done using simple Newline algorithm
For sentences and words tokenizers above are used
:param string: Text to tokenize
:type string: str or unicode
:return: text, tokenized i... | python | def tokenize_text(string):
"""
Tokenize input text to paragraphs, sentences and words.
Tokenization to paragraphs is done using simple Newline algorithm
For sentences and words tokenizers above are used
:param string: Text to tokenize
:type string: str or unicode
:return: text, tokenized i... | [
"def",
"tokenize_text",
"(",
"string",
")",
":",
"string",
"=",
"six",
".",
"text_type",
"(",
"string",
")",
"rez",
"=",
"[",
"]",
"for",
"part",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"par",
"=",
"[",
"]",
"for",
"sent",
"in",
"to... | Tokenize input text to paragraphs, sentences and words.
Tokenization to paragraphs is done using simple Newline algorithm
For sentences and words tokenizers above are used
:param string: Text to tokenize
:type string: str or unicode
:return: text, tokenized into paragraphs, sentences and words
... | [
"Tokenize",
"input",
"text",
"to",
"paragraphs",
"sentences",
"and",
"words",
"."
] | train | https://github.com/lang-uk/tokenize-uk/blob/52769b0f43af29d4a5863a7836364b3b9c10dd09/tokenize_uk/tokenize_uk.py#L94-L114 |
interedition/collatex | collatex-pythonport/collatex/experimental_astar_aligner.py | ExperimentalAstarAligner.collate | def collate(self, graph, collation):
'''
:type graph: VariantGraph
:type collation: Collation
'''
# Build the variant graph for the first witness
# this is easy: generate a vertex for every token
first_witness = collation.witnesses[0]
tokens = first_witnes... | python | def collate(self, graph, collation):
'''
:type graph: VariantGraph
:type collation: Collation
'''
# Build the variant graph for the first witness
# this is easy: generate a vertex for every token
first_witness = collation.witnesses[0]
tokens = first_witnes... | [
"def",
"collate",
"(",
"self",
",",
"graph",
",",
"collation",
")",
":",
"# Build the variant graph for the first witness",
"# this is easy: generate a vertex for every token",
"first_witness",
"=",
"collation",
".",
"witnesses",
"[",
"0",
"]",
"tokens",
"=",
"first_witne... | :type graph: VariantGraph
:type collation: Collation | [
":",
"type",
"graph",
":",
"VariantGraph",
":",
"type",
"collation",
":",
"Collation"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/experimental_astar_aligner.py#L21-L64 |
interedition/collatex | collatex-pythonport/collatex/experimental_astar_aligner.py | Aligner.align | def align(self):
'''
Every step we have 3 choices:
1) Move pointer witness a --> omission
2) Move pointer witness b --> addition
3) Move pointer of both witness a/b --> match
Note: a replacement is omission followed by an addition or the other way around
Choice ... | python | def align(self):
'''
Every step we have 3 choices:
1) Move pointer witness a --> omission
2) Move pointer witness b --> addition
3) Move pointer of both witness a/b --> match
Note: a replacement is omission followed by an addition or the other way around
Choice ... | [
"def",
"align",
"(",
"self",
")",
":",
"# extract tokens from witness (note that this can be done in a streaming manner if desired)",
"tokens_a",
"=",
"self",
".",
"witness_a",
".",
"tokens",
"(",
")",
"tokens_b",
"=",
"self",
".",
"witness_b",
".",
"tokens",
"(",
")"... | Every step we have 3 choices:
1) Move pointer witness a --> omission
2) Move pointer witness b --> addition
3) Move pointer of both witness a/b --> match
Note: a replacement is omission followed by an addition or the other way around
Choice 1 and 2 are only possible if token a ... | [
"Every",
"step",
"we",
"have",
"3",
"choices",
":",
"1",
")",
"Move",
"pointer",
"witness",
"a",
"--",
">",
"omission",
"2",
")",
"Move",
"pointer",
"witness",
"b",
"--",
">",
"addition",
"3",
")",
"Move",
"pointer",
"of",
"both",
"witness",
"a",
"/"... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/experimental_astar_aligner.py#L276-L299 |
interedition/collatex | collatex-pythonport/collatex/core_classes.py | VariantGraph.connect | def connect(self, source, target, witnesses):
"""
:type source: integer
:type target: integer
"""
# print("Adding Edge: "+source+":"+target)
if self.graph.has_edge(source, target):
self.graph[source][target]["label"] += ", " + str(witnesses)
else:
... | python | def connect(self, source, target, witnesses):
"""
:type source: integer
:type target: integer
"""
# print("Adding Edge: "+source+":"+target)
if self.graph.has_edge(source, target):
self.graph[source][target]["label"] += ", " + str(witnesses)
else:
... | [
"def",
"connect",
"(",
"self",
",",
"source",
",",
"target",
",",
"witnesses",
")",
":",
"# print(\"Adding Edge: \"+source+\":\"+target)",
"if",
"self",
".",
"graph",
".",
"has_edge",
"(",
"source",
",",
"target",
")",
":",
"self",
".",
"graph",
"[",
"source... | :type source: integer
:type target: integer | [
":",
"type",
"source",
":",
"integer",
":",
"type",
"target",
":",
"integer"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/core_classes.py#L238-L247 |
interedition/collatex | collatex-pythonport/collatex/core_classes.py | VariantGraph.connect_near | def connect_near(self, source, target, weight):
# Near edges are added to self.near_graph, not self.graph, to avoid cycles
"""
:type source: integer
:type target: integer
"""
self.near_graph.add_edge(source, target, weight = weight, type='near') | python | def connect_near(self, source, target, weight):
# Near edges are added to self.near_graph, not self.graph, to avoid cycles
"""
:type source: integer
:type target: integer
"""
self.near_graph.add_edge(source, target, weight = weight, type='near') | [
"def",
"connect_near",
"(",
"self",
",",
"source",
",",
"target",
",",
"weight",
")",
":",
"# Near edges are added to self.near_graph, not self.graph, to avoid cycles",
"self",
".",
"near_graph",
".",
"add_edge",
"(",
"source",
",",
"target",
",",
"weight",
"=",
"we... | :type source: integer
:type target: integer | [
":",
"type",
"source",
":",
"integer",
":",
"type",
"target",
":",
"integer"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/core_classes.py#L249-L255 |
interedition/collatex | collatex-pythonport/collatex/core_classes.py | CollationAlgorithm.merge | def merge(self, graph, witness_sigil, witness_tokens, alignments={}):
"""
:type graph: VariantGraph
"""
# NOTE: token_to_vertex only contains newly generated vertices
token_to_vertex = {}
last = graph.start
for token in witness_tokens:
vertex = alignme... | python | def merge(self, graph, witness_sigil, witness_tokens, alignments={}):
"""
:type graph: VariantGraph
"""
# NOTE: token_to_vertex only contains newly generated vertices
token_to_vertex = {}
last = graph.start
for token in witness_tokens:
vertex = alignme... | [
"def",
"merge",
"(",
"self",
",",
"graph",
",",
"witness_sigil",
",",
"witness_tokens",
",",
"alignments",
"=",
"{",
"}",
")",
":",
"# NOTE: token_to_vertex only contains newly generated vertices",
"token_to_vertex",
"=",
"{",
"}",
"last",
"=",
"graph",
".",
"star... | :type graph: VariantGraph | [
":",
"type",
"graph",
":",
"VariantGraph"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/core_classes.py#L296-L314 |
interedition/collatex | collatex-pythonport/collatex/edit_graph_aligner.py | EditGraphAligner.collate | def collate(self, graph):
"""
:type graph: VariantGraph
"""
# prepare the token index
self.token_index.prepare()
self.vertex_array = [None] * len(self.token_index.token_array)
# Build the variant graph for the first witness
# this is easy: generate a vert... | python | def collate(self, graph):
"""
:type graph: VariantGraph
"""
# prepare the token index
self.token_index.prepare()
self.vertex_array = [None] * len(self.token_index.token_array)
# Build the variant graph for the first witness
# this is easy: generate a vert... | [
"def",
"collate",
"(",
"self",
",",
"graph",
")",
":",
"# prepare the token index",
"self",
".",
"token_index",
".",
"prepare",
"(",
")",
"self",
".",
"vertex_array",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"self",
".",
"token_index",
".",
"token_array",
... | :type graph: VariantGraph | [
":",
"type",
"graph",
":",
"VariantGraph"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/edit_graph_aligner.py#L195-L260 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet._parse | def _parse(self, pattern):
"""Parse string of comma-separated x-y/step -like ranges"""
# Comma separated ranges
if pattern.find(',') < 0:
subranges = [pattern]
else:
subranges = pattern.split(',')
for subrange in subranges:
if subrange.find('/... | python | def _parse(self, pattern):
"""Parse string of comma-separated x-y/step -like ranges"""
# Comma separated ranges
if pattern.find(',') < 0:
subranges = [pattern]
else:
subranges = pattern.split(',')
for subrange in subranges:
if subrange.find('/... | [
"def",
"_parse",
"(",
"self",
",",
"pattern",
")",
":",
"# Comma separated ranges",
"if",
"pattern",
".",
"find",
"(",
"','",
")",
"<",
"0",
":",
"subranges",
"=",
"[",
"pattern",
"]",
"else",
":",
"subranges",
"=",
"pattern",
".",
"split",
"(",
"','",... | Parse string of comma-separated x-y/step -like ranges | [
"Parse",
"string",
"of",
"comma",
"-",
"separated",
"x",
"-",
"y",
"/",
"step",
"-",
"like",
"ranges"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L123-L178 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.fromlist | def fromlist(cls, rnglist, autostep=None):
"""Class method that returns a new RangeSet with ranges from provided
list."""
inst = RangeSet(autostep=autostep)
inst.updaten(rnglist)
return inst | python | def fromlist(cls, rnglist, autostep=None):
"""Class method that returns a new RangeSet with ranges from provided
list."""
inst = RangeSet(autostep=autostep)
inst.updaten(rnglist)
return inst | [
"def",
"fromlist",
"(",
"cls",
",",
"rnglist",
",",
"autostep",
"=",
"None",
")",
":",
"inst",
"=",
"RangeSet",
"(",
"autostep",
"=",
"autostep",
")",
"inst",
".",
"updaten",
"(",
"rnglist",
")",
"return",
"inst"
] | Class method that returns a new RangeSet with ranges from provided
list. | [
"Class",
"method",
"that",
"returns",
"a",
"new",
"RangeSet",
"with",
"ranges",
"from",
"provided",
"list",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L181-L186 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.fromone | def fromone(cls, index, pad=0, autostep=None):
"""Class method that returns a new RangeSet of one single item or
a single range (from integer or slice object)."""
inst = RangeSet(autostep=autostep)
# support slice object with duck-typing
try:
inst.add(index, pad)
... | python | def fromone(cls, index, pad=0, autostep=None):
"""Class method that returns a new RangeSet of one single item or
a single range (from integer or slice object)."""
inst = RangeSet(autostep=autostep)
# support slice object with duck-typing
try:
inst.add(index, pad)
... | [
"def",
"fromone",
"(",
"cls",
",",
"index",
",",
"pad",
"=",
"0",
",",
"autostep",
"=",
"None",
")",
":",
"inst",
"=",
"RangeSet",
"(",
"autostep",
"=",
"autostep",
")",
"# support slice object with duck-typing",
"try",
":",
"inst",
".",
"add",
"(",
"ind... | Class method that returns a new RangeSet of one single item or
a single range (from integer or slice object). | [
"Class",
"method",
"that",
"returns",
"a",
"new",
"RangeSet",
"of",
"one",
"single",
"item",
"or",
"a",
"single",
"range",
"(",
"from",
"integer",
"or",
"slice",
"object",
")",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L189-L200 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.set_autostep | def set_autostep(self, val):
"""Set autostep value (property)"""
if val is None:
# disabled by default for pdsh compat (+inf is 1E400, but a bug in
# python 2.4 makes it impossible to be pickled, so we use less)
# NOTE: Later, we could consider sys.maxint here
... | python | def set_autostep(self, val):
"""Set autostep value (property)"""
if val is None:
# disabled by default for pdsh compat (+inf is 1E400, but a bug in
# python 2.4 makes it impossible to be pickled, so we use less)
# NOTE: Later, we could consider sys.maxint here
... | [
"def",
"set_autostep",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"# disabled by default for pdsh compat (+inf is 1E400, but a bug in",
"# python 2.4 makes it impossible to be pickled, so we use less)",
"# NOTE: Later, we could consider sys.maxint here",
"self... | Set autostep value (property) | [
"Set",
"autostep",
"value",
"(",
"property",
")"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L209-L218 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.striter | def striter(self):
"""Iterate over each (optionally padded) string element in RangeSet."""
pad = self.padding or 0
for i in self._sorted():
yield "%0*d" % (pad, i) | python | def striter(self):
"""Iterate over each (optionally padded) string element in RangeSet."""
pad = self.padding or 0
for i in self._sorted():
yield "%0*d" % (pad, i) | [
"def",
"striter",
"(",
"self",
")",
":",
"pad",
"=",
"self",
".",
"padding",
"or",
"0",
"for",
"i",
"in",
"self",
".",
"_sorted",
"(",
")",
":",
"yield",
"\"%0*d\"",
"%",
"(",
"pad",
",",
"i",
")"
] | Iterate over each (optionally padded) string element in RangeSet. | [
"Iterate",
"over",
"each",
"(",
"optionally",
"padded",
")",
"string",
"element",
"in",
"RangeSet",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L230-L234 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.contiguous | def contiguous(self):
"""Object-based iterator over contiguous range sets."""
pad = self.padding or 0
for sli in self._contiguous_slices():
yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), pad) | python | def contiguous(self):
"""Object-based iterator over contiguous range sets."""
pad = self.padding or 0
for sli in self._contiguous_slices():
yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), pad) | [
"def",
"contiguous",
"(",
"self",
")",
":",
"pad",
"=",
"self",
".",
"padding",
"or",
"0",
"for",
"sli",
"in",
"self",
".",
"_contiguous_slices",
"(",
")",
":",
"yield",
"RangeSet",
".",
"fromone",
"(",
"slice",
"(",
"sli",
".",
"start",
",",
"sli",
... | Object-based iterator over contiguous range sets. | [
"Object",
"-",
"based",
"iterator",
"over",
"contiguous",
"range",
"sets",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L236-L240 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet._strslices | def _strslices(self):
"""Stringify slices list (x-y/step format)"""
pad = self.padding or 0
for sli in self.slices():
if sli.start + 1 == sli.stop:
yield "%0*d" % (pad, sli.start)
else:
assert sli.step >= 0, "Internal error: sli.step < 0"
... | python | def _strslices(self):
"""Stringify slices list (x-y/step format)"""
pad = self.padding or 0
for sli in self.slices():
if sli.start + 1 == sli.stop:
yield "%0*d" % (pad, sli.start)
else:
assert sli.step >= 0, "Internal error: sli.step < 0"
... | [
"def",
"_strslices",
"(",
"self",
")",
":",
"pad",
"=",
"self",
".",
"padding",
"or",
"0",
"for",
"sli",
"in",
"self",
".",
"slices",
"(",
")",
":",
"if",
"sli",
".",
"start",
"+",
"1",
"==",
"sli",
".",
"stop",
":",
"yield",
"\"%0*d\"",
"%",
"... | Stringify slices list (x-y/step format) | [
"Stringify",
"slices",
"list",
"(",
"x",
"-",
"y",
"/",
"step",
"format",
")"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L271-L283 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet._contiguous_slices | def _contiguous_slices(self):
"""Internal iterator over contiguous slices in RangeSet."""
k = j = None
for i in self._sorted():
if k is None:
k = j = i
if i - j > 1:
yield slice(k, j + 1, 1)
k = i
j = i
i... | python | def _contiguous_slices(self):
"""Internal iterator over contiguous slices in RangeSet."""
k = j = None
for i in self._sorted():
if k is None:
k = j = i
if i - j > 1:
yield slice(k, j + 1, 1)
k = i
j = i
i... | [
"def",
"_contiguous_slices",
"(",
"self",
")",
":",
"k",
"=",
"j",
"=",
"None",
"for",
"i",
"in",
"self",
".",
"_sorted",
"(",
")",
":",
"if",
"k",
"is",
"None",
":",
"k",
"=",
"j",
"=",
"i",
"if",
"i",
"-",
"j",
">",
"1",
":",
"yield",
"sl... | Internal iterator over contiguous slices in RangeSet. | [
"Internal",
"iterator",
"over",
"contiguous",
"slices",
"in",
"RangeSet",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L293-L304 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet._folded_slices | def _folded_slices(self):
"""Internal generator that is able to retrieve ranges organized by step.
Complexity: O(n) with n = number of ranges in tree."""
if len(self) == 0:
return
prng = None # pending range
istart = None # processing starting indice
... | python | def _folded_slices(self):
"""Internal generator that is able to retrieve ranges organized by step.
Complexity: O(n) with n = number of ranges in tree."""
if len(self) == 0:
return
prng = None # pending range
istart = None # processing starting indice
... | [
"def",
"_folded_slices",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"prng",
"=",
"None",
"# pending range",
"istart",
"=",
"None",
"# processing starting indice",
"m",
"=",
"0",
"# processing step",
"for",
"sli",
"in",
... | Internal generator that is able to retrieve ranges organized by step.
Complexity: O(n) with n = number of ranges in tree. | [
"Internal",
"generator",
"that",
"is",
"able",
"to",
"retrieve",
"ranges",
"organized",
"by",
"step",
".",
"Complexity",
":",
"O",
"(",
"n",
")",
"with",
"n",
"=",
"number",
"of",
"ranges",
"in",
"tree",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L306-L406 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.split | def split(self, nbr):
"""
Split the rangeset into nbr sub-rangesets (at most). Each
sub-rangeset will have the same number of elements more or
less 1. Current rangeset remains unmodified. Returns an
iterator.
>>> RangeSet("1-5").split(3)
RangeSet("1-2")
... | python | def split(self, nbr):
"""
Split the rangeset into nbr sub-rangesets (at most). Each
sub-rangeset will have the same number of elements more or
less 1. Current rangeset remains unmodified. Returns an
iterator.
>>> RangeSet("1-5").split(3)
RangeSet("1-2")
... | [
"def",
"split",
"(",
"self",
",",
"nbr",
")",
":",
"assert",
"(",
"nbr",
">",
"0",
")",
"# We put the same number of element in each sub-nodeset.",
"slice_size",
"=",
"len",
"(",
"self",
")",
"/",
"nbr",
"left",
"=",
"len",
"(",
"self",
")",
"%",
"nbr",
... | Split the rangeset into nbr sub-rangesets (at most). Each
sub-rangeset will have the same number of elements more or
less 1. Current rangeset remains unmodified. Returns an
iterator.
>>> RangeSet("1-5").split(3)
RangeSet("1-2")
RangeSet("3-4")
RangeSet("foo5") | [
"Split",
"the",
"rangeset",
"into",
"nbr",
"sub",
"-",
"rangesets",
"(",
"at",
"most",
")",
".",
"Each",
"sub",
"-",
"rangeset",
"will",
"have",
"the",
"same",
"number",
"of",
"elements",
"more",
"or",
"less",
"1",
".",
"Current",
"rangeset",
"remains",
... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L433-L455 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.add_range | def add_range(self, start, stop, step=1, pad=0):
"""
Add a range (start, stop, step and padding length) to RangeSet.
Like the Python built-in function range(), the last element is
the largest start + i * step less than stop.
"""
assert start < stop, "please provide ordere... | python | def add_range(self, start, stop, step=1, pad=0):
"""
Add a range (start, stop, step and padding length) to RangeSet.
Like the Python built-in function range(), the last element is
the largest start + i * step less than stop.
"""
assert start < stop, "please provide ordere... | [
"def",
"add_range",
"(",
"self",
",",
"start",
",",
"stop",
",",
"step",
"=",
"1",
",",
"pad",
"=",
"0",
")",
":",
"assert",
"start",
"<",
"stop",
",",
"\"please provide ordered node index ranges\"",
"assert",
"step",
">",
"0",
"assert",
"pad",
">=",
"0"... | Add a range (start, stop, step and padding length) to RangeSet.
Like the Python built-in function range(), the last element is
the largest start + i * step less than stop. | [
"Add",
"a",
"range",
"(",
"start",
"stop",
"step",
"and",
"padding",
"length",
")",
"to",
"RangeSet",
".",
"Like",
"the",
"Python",
"built",
"-",
"in",
"function",
"range",
"()",
"the",
"last",
"element",
"is",
"the",
"largest",
"start",
"+",
"i",
"*",... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L457-L470 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.copy | def copy(self):
"""Return a shallow copy of a RangeSet."""
cpy = self.__class__()
cpy._autostep = self._autostep
cpy.padding = self.padding
cpy.update(self)
return cpy | python | def copy(self):
"""Return a shallow copy of a RangeSet."""
cpy = self.__class__()
cpy._autostep = self._autostep
cpy.padding = self.padding
cpy.update(self)
return cpy | [
"def",
"copy",
"(",
"self",
")",
":",
"cpy",
"=",
"self",
".",
"__class__",
"(",
")",
"cpy",
".",
"_autostep",
"=",
"self",
".",
"_autostep",
"cpy",
".",
"padding",
"=",
"self",
".",
"padding",
"cpy",
".",
"update",
"(",
"self",
")",
"return",
"cpy... | Return a shallow copy of a RangeSet. | [
"Return",
"a",
"shallow",
"copy",
"of",
"a",
"RangeSet",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L472-L478 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet._wrap_set_op | def _wrap_set_op(self, fun, arg):
"""Wrap built-in set operations for RangeSet to workaround built-in set
base class issues (RangeSet.__new/init__ not called)"""
result = fun(self, arg)
result._autostep = self._autostep
result.padding = self.padding
return result | python | def _wrap_set_op(self, fun, arg):
"""Wrap built-in set operations for RangeSet to workaround built-in set
base class issues (RangeSet.__new/init__ not called)"""
result = fun(self, arg)
result._autostep = self._autostep
result.padding = self.padding
return result | [
"def",
"_wrap_set_op",
"(",
"self",
",",
"fun",
",",
"arg",
")",
":",
"result",
"=",
"fun",
"(",
"self",
",",
"arg",
")",
"result",
".",
"_autostep",
"=",
"self",
".",
"_autostep",
"result",
".",
"padding",
"=",
"self",
".",
"padding",
"return",
"res... | Wrap built-in set operations for RangeSet to workaround built-in set
base class issues (RangeSet.__new/init__ not called) | [
"Wrap",
"built",
"-",
"in",
"set",
"operations",
"for",
"RangeSet",
"to",
"workaround",
"built",
"-",
"in",
"set",
"base",
"class",
"issues",
"(",
"RangeSet",
".",
"__new",
"/",
"init__",
"not",
"called",
")"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L504-L510 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.intersection | def intersection(self, other):
"""Return the intersection of two RangeSets as a new RangeSet.
(I.e. all elements that are in both sets.)
"""
#NOTE: This is a work around
# Python 3 return as the result of set.intersection a new set instance.
# Python 2 however returns a... | python | def intersection(self, other):
"""Return the intersection of two RangeSets as a new RangeSet.
(I.e. all elements that are in both sets.)
"""
#NOTE: This is a work around
# Python 3 return as the result of set.intersection a new set instance.
# Python 2 however returns a... | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"#NOTE: This is a work around ",
"# Python 3 return as the result of set.intersection a new set instance.",
"# Python 2 however returns as a the result a ClusterShell.RangeSet.RangeSet instance.",
"# ORIGINAL CODE: return self._wrap_s... | Return the intersection of two RangeSets as a new RangeSet.
(I.e. all elements that are in both sets.) | [
"Return",
"the",
"intersection",
"of",
"two",
"RangeSets",
"as",
"a",
"new",
"RangeSet",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L537-L548 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.difference | def difference(self, other):
"""Return the difference of two RangeSets as a new RangeSet.
(I.e. all elements that are in this set and not in the other.)
"""
#NOTE: This is a work around
# Python 3 return as the result of set.intersection a new set instance.
# Python 2 ho... | python | def difference(self, other):
"""Return the difference of two RangeSets as a new RangeSet.
(I.e. all elements that are in this set and not in the other.)
"""
#NOTE: This is a work around
# Python 3 return as the result of set.intersection a new set instance.
# Python 2 ho... | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"#NOTE: This is a work around",
"# Python 3 return as the result of set.intersection a new set instance.",
"# Python 2 however returns as a the result a ClusterShell.RangeSet.RangeSet instance.",
"# ORIGINAL CODE: return self._wrap_set_... | Return the difference of two RangeSets as a new RangeSet.
(I.e. all elements that are in this set and not in the other.) | [
"Return",
"the",
"difference",
"of",
"two",
"RangeSets",
"as",
"a",
"new",
"RangeSet",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L575-L586 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.issubset | def issubset(self, other):
"""Report whether another set contains this RangeSet."""
self._binary_sanity_check(other)
return set.issubset(self, other) | python | def issubset(self, other):
"""Report whether another set contains this RangeSet."""
self._binary_sanity_check(other)
return set.issubset(self, other) | [
"def",
"issubset",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_binary_sanity_check",
"(",
"other",
")",
"return",
"set",
".",
"issubset",
"(",
"self",
",",
"other",
")"
] | Report whether another set contains this RangeSet. | [
"Report",
"whether",
"another",
"set",
"contains",
"this",
"RangeSet",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L604-L607 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.issuperset | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | python | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | [
"def",
"issuperset",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_binary_sanity_check",
"(",
"other",
")",
"return",
"set",
".",
"issuperset",
"(",
"self",
",",
"other",
")"
] | Report whether this RangeSet contains another set. | [
"Report",
"whether",
"this",
"RangeSet",
"contains",
"another",
"set",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L609-L612 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.difference_update | def difference_update(self, other, strict=False):
"""Remove all elements of another set from this RangeSet.
If strict is True, raise KeyError if an element cannot be removed.
(strict is a RangeSet addition)"""
if strict and other not in self:
raise KeyError(other.dif... | python | def difference_update(self, other, strict=False):
"""Remove all elements of another set from this RangeSet.
If strict is True, raise KeyError if an element cannot be removed.
(strict is a RangeSet addition)"""
if strict and other not in self:
raise KeyError(other.dif... | [
"def",
"difference_update",
"(",
"self",
",",
"other",
",",
"strict",
"=",
"False",
")",
":",
"if",
"strict",
"and",
"other",
"not",
"in",
"self",
":",
"raise",
"KeyError",
"(",
"other",
".",
"difference",
"(",
"self",
")",
"[",
"0",
"]",
")",
"set",... | Remove all elements of another set from this RangeSet.
If strict is True, raise KeyError if an element cannot be removed.
(strict is a RangeSet addition) | [
"Remove",
"all",
"elements",
"of",
"another",
"set",
"from",
"this",
"RangeSet",
".",
"If",
"strict",
"is",
"True",
"raise",
"KeyError",
"if",
"an",
"element",
"cannot",
"be",
"removed",
".",
"(",
"strict",
"is",
"a",
"RangeSet",
"addition",
")"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L677-L684 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.update | def update(self, iterable):
"""Add all integers from an iterable (such as a list)."""
if isinstance(iterable, RangeSet):
# keep padding unless is has not been defined yet
if self.padding is None and iterable.padding is not None:
self.padding = iterable.padding
... | python | def update(self, iterable):
"""Add all integers from an iterable (such as a list)."""
if isinstance(iterable, RangeSet):
# keep padding unless is has not been defined yet
if self.padding is None and iterable.padding is not None:
self.padding = iterable.padding
... | [
"def",
"update",
"(",
"self",
",",
"iterable",
")",
":",
"if",
"isinstance",
"(",
"iterable",
",",
"RangeSet",
")",
":",
"# keep padding unless is has not been defined yet",
"if",
"self",
".",
"padding",
"is",
"None",
"and",
"iterable",
".",
"padding",
"is",
"... | Add all integers from an iterable (such as a list). | [
"Add",
"all",
"integers",
"from",
"an",
"iterable",
"(",
"such",
"as",
"a",
"list",
")",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L688-L695 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.updaten | def updaten(self, rangesets):
"""
Update a rangeset with the union of itself and several others.
"""
for rng in rangesets:
if isinstance(rng, set):
self.update(rng)
else:
self.update(RangeSet(rng)) | python | def updaten(self, rangesets):
"""
Update a rangeset with the union of itself and several others.
"""
for rng in rangesets:
if isinstance(rng, set):
self.update(rng)
else:
self.update(RangeSet(rng)) | [
"def",
"updaten",
"(",
"self",
",",
"rangesets",
")",
":",
"for",
"rng",
"in",
"rangesets",
":",
"if",
"isinstance",
"(",
"rng",
",",
"set",
")",
":",
"self",
".",
"update",
"(",
"rng",
")",
"else",
":",
"self",
".",
"update",
"(",
"RangeSet",
"(",... | Update a rangeset with the union of itself and several others. | [
"Update",
"a",
"rangeset",
"with",
"the",
"union",
"of",
"itself",
"and",
"several",
"others",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L697-L705 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.add | def add(self, element, pad=0):
"""Add an element to a RangeSet.
This has no effect if the element is already present.
"""
set.add(self, int(element))
if pad > 0 and self.padding is None:
self.padding = pad | python | def add(self, element, pad=0):
"""Add an element to a RangeSet.
This has no effect if the element is already present.
"""
set.add(self, int(element))
if pad > 0 and self.padding is None:
self.padding = pad | [
"def",
"add",
"(",
"self",
",",
"element",
",",
"pad",
"=",
"0",
")",
":",
"set",
".",
"add",
"(",
"self",
",",
"int",
"(",
"element",
")",
")",
"if",
"pad",
">",
"0",
"and",
"self",
".",
"padding",
"is",
"None",
":",
"self",
".",
"padding",
... | Add an element to a RangeSet.
This has no effect if the element is already present. | [
"Add",
"an",
"element",
"to",
"a",
"RangeSet",
".",
"This",
"has",
"no",
"effect",
"if",
"the",
"element",
"is",
"already",
"present",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L716-L722 |
interedition/collatex | collatex-pythonport/ClusterShell/RangeSet.py | RangeSet.discard | def discard(self, element):
"""Remove element from the RangeSet if it is a member.
If the element is not a member, do nothing.
"""
try:
i = int(element)
set.discard(self, i)
except ValueError:
pass | python | def discard(self, element):
"""Remove element from the RangeSet if it is a member.
If the element is not a member, do nothing.
"""
try:
i = int(element)
set.discard(self, i)
except ValueError:
pass | [
"def",
"discard",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"i",
"=",
"int",
"(",
"element",
")",
"set",
".",
"discard",
"(",
"self",
",",
"i",
")",
"except",
"ValueError",
":",
"pass"
] | Remove element from the RangeSet if it is a member.
If the element is not a member, do nothing. | [
"Remove",
"element",
"from",
"the",
"RangeSet",
"if",
"it",
"is",
"a",
"member",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L732-L741 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | _open | def _open(filename, mode="r"):
"""
Universal open file facility.
With normal files, this function behaves as the open builtin.
With gzip-ed files, it decompress or compress according to the specified mode.
In addition, when filename is '-', it opens the standard input or output according to
the ... | python | def _open(filename, mode="r"):
"""
Universal open file facility.
With normal files, this function behaves as the open builtin.
With gzip-ed files, it decompress or compress according to the specified mode.
In addition, when filename is '-', it opens the standard input or output according to
the ... | [
"def",
"_open",
"(",
"filename",
",",
"mode",
"=",
"\"r\"",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"\".gz\"",
")",
":",
"return",
"GzipFile",
"(",
"filename",
",",
"mode",
",",
"COMPRESSION_LEVEL",
")",
"elif",
"filename",
"==",
"\"-\"",
":",
... | Universal open file facility.
With normal files, this function behaves as the open builtin.
With gzip-ed files, it decompress or compress according to the specified mode.
In addition, when filename is '-', it opens the standard input or output according to
the specified mode.
Mode are expected to be... | [
"Universal",
"open",
"file",
"facility",
".",
"With",
"normal",
"files",
"this",
"function",
"behaves",
"as",
"the",
"open",
"builtin",
".",
"With",
"gzip",
"-",
"ed",
"files",
"it",
"decompress",
"or",
"compress",
"according",
"to",
"the",
"specified",
"mod... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L62-L80 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | _radixPass | def _radixPass(a, b, r, n, K):
"""
Stable sort of the sequence a according to the keys given in r.
>>> a=range(5)
>>> b=[0]*5
>>> r=[2,1,3,0,4]
>>> _radixPass(a, b, r, 5, 5)
>>> b
[3, 1, 0, 2, 4]
When n is less than the length of a, the end of b must be left unaltered.
>>> b=[... | python | def _radixPass(a, b, r, n, K):
"""
Stable sort of the sequence a according to the keys given in r.
>>> a=range(5)
>>> b=[0]*5
>>> r=[2,1,3,0,4]
>>> _radixPass(a, b, r, 5, 5)
>>> b
[3, 1, 0, 2, 4]
When n is less than the length of a, the end of b must be left unaltered.
>>> b=[... | [
"def",
"_radixPass",
"(",
"a",
",",
"b",
",",
"r",
",",
"n",
",",
"K",
")",
":",
"c",
"=",
"_array",
"(",
"\"i\"",
",",
"[",
"0",
"]",
"*",
"(",
"K",
"+",
"1",
")",
")",
"# counter array",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"#... | Stable sort of the sequence a according to the keys given in r.
>>> a=range(5)
>>> b=[0]*5
>>> r=[2,1,3,0,4]
>>> _radixPass(a, b, r, 5, 5)
>>> b
[3, 1, 0, 2, 4]
When n is less than the length of a, the end of b must be left unaltered.
>>> b=[5]*5
>>> _radixPass(a, b, r, 2, 2)
... | [
"Stable",
"sort",
"of",
"the",
"sequence",
"a",
"according",
"to",
"the",
"keys",
"given",
"in",
"r",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L83-L136 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | _nbOperations | def _nbOperations(n):
"""
Exact number of atomic operations in _radixPass.
"""
if n < 2:
return 0
else:
n0 = (n + 2) // 3
n02 = n0 + n // 3
return 3 * (n02) + n0 + _nbOperations(n02) | python | def _nbOperations(n):
"""
Exact number of atomic operations in _radixPass.
"""
if n < 2:
return 0
else:
n0 = (n + 2) // 3
n02 = n0 + n // 3
return 3 * (n02) + n0 + _nbOperations(n02) | [
"def",
"_nbOperations",
"(",
"n",
")",
":",
"if",
"n",
"<",
"2",
":",
"return",
"0",
"else",
":",
"n0",
"=",
"(",
"n",
"+",
"2",
")",
"//",
"3",
"n02",
"=",
"n0",
"+",
"n",
"//",
"3",
"return",
"3",
"*",
"(",
"n02",
")",
"+",
"n0",
"+",
... | Exact number of atomic operations in _radixPass. | [
"Exact",
"number",
"of",
"atomic",
"operations",
"in",
"_radixPass",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L139-L149 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | _suffixArrayWithTrace | def _suffixArrayWithTrace(s, SA, n, K, operations, totalOperations):
"""
This function is a rewrite in Python of the C implementation proposed in Kärkkäinen and Sanders paper.
Find the suffix array SA of s[0..n-1] in {1..K}^n
Require s[n]=s[n+1]=s[n+2]=0, n>=2
"""
if _trace:
_traceSuffi... | python | def _suffixArrayWithTrace(s, SA, n, K, operations, totalOperations):
"""
This function is a rewrite in Python of the C implementation proposed in Kärkkäinen and Sanders paper.
Find the suffix array SA of s[0..n-1] in {1..K}^n
Require s[n]=s[n+1]=s[n+2]=0, n>=2
"""
if _trace:
_traceSuffi... | [
"def",
"_suffixArrayWithTrace",
"(",
"s",
",",
"SA",
",",
"n",
",",
"K",
",",
"operations",
",",
"totalOperations",
")",
":",
"if",
"_trace",
":",
"_traceSuffixArray",
"(",
"operations",
",",
"totalOperations",
")",
"n0",
"=",
"(",
"n",
"+",
"2",
")",
... | This function is a rewrite in Python of the C implementation proposed in Kärkkäinen and Sanders paper.
Find the suffix array SA of s[0..n-1] in {1..K}^n
Require s[n]=s[n+1]=s[n+2]=0, n>=2 | [
"This",
"function",
"is",
"a",
"rewrite",
"in",
"Python",
"of",
"the",
"C",
"implementation",
"proposed",
"in",
"Kärkkäinen",
"and",
"Sanders",
"paper",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L161-L281 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | _longestCommonPrefix | def _longestCommonPrefix(seq1, seq2, start1=0, start2=0):
"""
Returns the length of the longest common prefix of seq1
starting at offset start1 and seq2 starting at offset start2.
>>> _longestCommonPrefix("abcdef", "abcghj")
3
>>> _longestCommonPrefix("abcghj", "abcdef")
3
>>> _longes... | python | def _longestCommonPrefix(seq1, seq2, start1=0, start2=0):
"""
Returns the length of the longest common prefix of seq1
starting at offset start1 and seq2 starting at offset start2.
>>> _longestCommonPrefix("abcdef", "abcghj")
3
>>> _longestCommonPrefix("abcghj", "abcdef")
3
>>> _longes... | [
"def",
"_longestCommonPrefix",
"(",
"seq1",
",",
"seq2",
",",
"start1",
"=",
"0",
",",
"start2",
"=",
"0",
")",
":",
"len1",
"=",
"len",
"(",
"seq1",
")",
"-",
"start1",
"len2",
"=",
"len",
"(",
"seq2",
")",
"-",
"start2",
"# We set seq2 as the shortes... | Returns the length of the longest common prefix of seq1
starting at offset start1 and seq2 starting at offset start2.
>>> _longestCommonPrefix("abcdef", "abcghj")
3
>>> _longestCommonPrefix("abcghj", "abcdef")
3
>>> _longestCommonPrefix("miss", "")
0
>>> _longestCommonPrefix("", "mr"... | [
"Returns",
"the",
"length",
"of",
"the",
"longest",
"common",
"prefix",
"of",
"seq1",
"starting",
"at",
"offset",
"start1",
"and",
"seq2",
"starting",
"at",
"offset",
"start2",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L297-L351 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | LCP | def LCP(SA):
"""
Compute the longest common prefix for every adjacent suffixes.
The result is a list of same size as SA.
Given two suffixes at positions i and i+1,
their LCP is stored at position i+1.
A zero is stored at position 0 of the output.
>>> SA=SuffixArray("abba", unit=UNIT_BYTE)
... | python | def LCP(SA):
"""
Compute the longest common prefix for every adjacent suffixes.
The result is a list of same size as SA.
Given two suffixes at positions i and i+1,
their LCP is stored at position i+1.
A zero is stored at position 0 of the output.
>>> SA=SuffixArray("abba", unit=UNIT_BYTE)
... | [
"def",
"LCP",
"(",
"SA",
")",
":",
"string",
"=",
"SA",
".",
"string",
"length",
"=",
"SA",
".",
"length",
"lcps",
"=",
"_array",
"(",
"\"i\"",
",",
"[",
"0",
"]",
"*",
"length",
")",
"SA",
"=",
"SA",
".",
"SA",
"if",
"_trace",
":",
"delta",
... | Compute the longest common prefix for every adjacent suffixes.
The result is a list of same size as SA.
Given two suffixes at positions i and i+1,
their LCP is stored at position i+1.
A zero is stored at position 0 of the output.
>>> SA=SuffixArray("abba", unit=UNIT_BYTE)
>>> SA._LCP_values
... | [
"Compute",
"the",
"longest",
"common",
"prefix",
"for",
"every",
"adjacent",
"suffixes",
".",
"The",
"result",
"is",
"a",
"list",
"of",
"same",
"size",
"as",
"SA",
".",
"Given",
"two",
"suffixes",
"at",
"positions",
"i",
"and",
"i",
"+",
"1",
"their",
... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L354-L403 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | parseArgv | def parseArgv():
"""
Command line option parser.
"""
parser = OptionParser()
parser.usage = r""" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>]
Create the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use.
UNIT may be set to 'byte', 'charac... | python | def parseArgv():
"""
Command line option parser.
"""
parser = OptionParser()
parser.usage = r""" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>]
Create the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use.
UNIT may be set to 'byte', 'charac... | [
"def",
"parseArgv",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"usage",
"=",
"r\"\"\" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>]\n\nCreate the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use.\nUN... | Command line option parser. | [
"Command",
"line",
"option",
"parser",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L909-L965 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | main | def main():
"""
Entry point for the standalone script.
"""
(options, strings) = parseArgv()
global _suffixArray, _trace
#############
# Verbosity #
#############
_trace = options.verbose
###################
# Processing unit #
###################
if options.unit ==... | python | def main():
"""
Entry point for the standalone script.
"""
(options, strings) = parseArgv()
global _suffixArray, _trace
#############
# Verbosity #
#############
_trace = options.verbose
###################
# Processing unit #
###################
if options.unit ==... | [
"def",
"main",
"(",
")",
":",
"(",
"options",
",",
"strings",
")",
"=",
"parseArgv",
"(",
")",
"global",
"_suffixArray",
",",
"_trace",
"#############",
"# Verbosity #",
"#############",
"_trace",
"=",
"options",
".",
"verbose",
"###################",
"# Process... | Entry point for the standalone script. | [
"Entry",
"point",
"for",
"the",
"standalone",
"script",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L968-L1046 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.addFeatureSA | def addFeatureSA(self, callback, default=None, name=None):
"""
Add a feature to the suffix array.
The callback must return a sequence such that
the feature at position i is attached to the suffix referenced by
self.SA[i].
It is called with one argument: the instance of S... | python | def addFeatureSA(self, callback, default=None, name=None):
"""
Add a feature to the suffix array.
The callback must return a sequence such that
the feature at position i is attached to the suffix referenced by
self.SA[i].
It is called with one argument: the instance of S... | [
"def",
"addFeatureSA",
"(",
"self",
",",
"callback",
",",
"default",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"featureName",
"=",
"callback",
".",
"__name__",
"else",
":",
"featureName",
"=",
"name",
"featureValue... | Add a feature to the suffix array.
The callback must return a sequence such that
the feature at position i is attached to the suffix referenced by
self.SA[i].
It is called with one argument: the instance of SuffixArray self.
The callback may traverse self.SA in any fashion.
... | [
"Add",
"a",
"feature",
"to",
"the",
"suffix",
"array",
".",
"The",
"callback",
"must",
"return",
"a",
"sequence",
"such",
"that",
"the",
"feature",
"at",
"position",
"i",
"is",
"attached",
"to",
"the",
"suffix",
"referenced",
"by",
"self",
".",
"SA",
"["... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L458-L547 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.addFeature | def addFeature(self, callback, default=None, name=None, arguments=None):
"""
Add a feature to the suffix array.
The callback must return the feature corresponding to the suffix at
position self.SA[i].
The callback must be callable (a function or lambda).
The argument nam... | python | def addFeature(self, callback, default=None, name=None, arguments=None):
"""
Add a feature to the suffix array.
The callback must return the feature corresponding to the suffix at
position self.SA[i].
The callback must be callable (a function or lambda).
The argument nam... | [
"def",
"addFeature",
"(",
"self",
",",
"callback",
",",
"default",
"=",
"None",
",",
"name",
"=",
"None",
",",
"arguments",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"featureName",
"=",
"callback",
".",
"__name__",
"else",
":",
"featureNa... | Add a feature to the suffix array.
The callback must return the feature corresponding to the suffix at
position self.SA[i].
The callback must be callable (a function or lambda).
The argument names of the callback are used to determine the data
needed. If an argument is the name ... | [
"Add",
"a",
"feature",
"to",
"the",
"suffix",
"array",
".",
"The",
"callback",
"must",
"return",
"the",
"feature",
"corresponding",
"to",
"the",
"suffix",
"at",
"position",
"self",
".",
"SA",
"[",
"i",
"]",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L549-L598 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.tokenize | def tokenize(self, string):
"""
Tokenizer utility.
When processing byte, outputs the string unaltered.
The character unit type is used for unicode data, the string is
decoded according to the encoding provided.
In the case of word unit, EOL characters are detached from th... | python | def tokenize(self, string):
"""
Tokenizer utility.
When processing byte, outputs the string unaltered.
The character unit type is used for unicode data, the string is
decoded according to the encoding provided.
In the case of word unit, EOL characters are detached from th... | [
"def",
"tokenize",
"(",
"self",
",",
"string",
")",
":",
"if",
"self",
".",
"unit",
"==",
"UNIT_WORD",
":",
"# the EOL character is treated as a word, hence a substitution",
"# before split",
"return",
"[",
"token",
"for",
"token",
"in",
"string",
".",
"replace",
... | Tokenizer utility.
When processing byte, outputs the string unaltered.
The character unit type is used for unicode data, the string is
decoded according to the encoding provided.
In the case of word unit, EOL characters are detached from the
preceding word, and outputs the list o... | [
"Tokenizer",
"utility",
".",
"When",
"processing",
"byte",
"outputs",
"the",
"string",
"unaltered",
".",
"The",
"character",
"unit",
"type",
"is",
"used",
"for",
"unicode",
"data",
"the",
"string",
"is",
"decoded",
"according",
"to",
"the",
"encoding",
"provid... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L600-L642 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.reprString | def reprString(self, string, length):
"""
Output a string of length tokens in the original form.
If string is an integer, it is considered as an offset in the text.
Otherwise string is considered as a sequence of ids (see voc and
tokId).
>>> SA=SuffixArray('mississippi',... | python | def reprString(self, string, length):
"""
Output a string of length tokens in the original form.
If string is an integer, it is considered as an offset in the text.
Otherwise string is considered as a sequence of ids (see voc and
tokId).
>>> SA=SuffixArray('mississippi',... | [
"def",
"reprString",
"(",
"self",
",",
"string",
",",
"length",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"int",
")",
":",
"length",
"=",
"min",
"(",
"length",
",",
"self",
".",
"length",
"-",
"string",
")",
"string",
"=",
"self",
".",
"str... | Output a string of length tokens in the original form.
If string is an integer, it is considered as an offset in the text.
Otherwise string is considered as a sequence of ids (see voc and
tokId).
>>> SA=SuffixArray('mississippi', UNIT_BYTE)
>>> SA.reprString(0, 3)
'mis'
... | [
"Output",
"a",
"string",
"of",
"length",
"tokens",
"in",
"the",
"original",
"form",
".",
"If",
"string",
"is",
"an",
"integer",
"it",
"is",
"considered",
"as",
"an",
"offset",
"in",
"the",
"text",
".",
"Otherwise",
"string",
"is",
"considered",
"as",
"a"... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L644-L680 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.toFile | def toFile(self, filename):
"""
Save the suffix array instance including all features attached in
filename. Accept any filename following the _open conventions,
for example if it ends with .gz the file created will be a compressed
GZip file.
"""
start = _time()
... | python | def toFile(self, filename):
"""
Save the suffix array instance including all features attached in
filename. Accept any filename following the _open conventions,
for example if it ends with .gz the file created will be a compressed
GZip file.
"""
start = _time()
... | [
"def",
"toFile",
"(",
"self",
",",
"filename",
")",
":",
"start",
"=",
"_time",
"(",
")",
"fd",
"=",
"_open",
"(",
"filename",
",",
"\"w\"",
")",
"savedData",
"=",
"[",
"self",
".",
"string",
",",
"self",
".",
"unit",
",",
"self",
".",
"voc",
","... | Save the suffix array instance including all features attached in
filename. Accept any filename following the _open conventions,
for example if it ends with .gz the file created will be a compressed
GZip file. | [
"Save",
"the",
"suffix",
"array",
"instance",
"including",
"all",
"features",
"attached",
"in",
"filename",
".",
"Accept",
"any",
"filename",
"following",
"the",
"_open",
"conventions",
"for",
"example",
"if",
"it",
"ends",
"with",
".",
"gz",
"the",
"file",
... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L708-L736 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.fromFile | def fromFile(cls, filename):
"""
Load a suffix array instance from filename, a file created by
toFile.
Accept any filename following the _open conventions.
"""
self = cls.__new__(cls) # new instance which does not call __init__
start = _time()
savedData... | python | def fromFile(cls, filename):
"""
Load a suffix array instance from filename, a file created by
toFile.
Accept any filename following the _open conventions.
"""
self = cls.__new__(cls) # new instance which does not call __init__
start = _time()
savedData... | [
"def",
"fromFile",
"(",
"cls",
",",
"filename",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"# new instance which does not call __init__",
"start",
"=",
"_time",
"(",
")",
"savedData",
"=",
"_loads",
"(",
"_open",
"(",
"filename",
",",
"... | Load a suffix array instance from filename, a file created by
toFile.
Accept any filename following the _open conventions. | [
"Load",
"a",
"suffix",
"array",
"instance",
"from",
"filename",
"a",
"file",
"created",
"by",
"toFile",
".",
"Accept",
"any",
"filename",
"following",
"the",
"_open",
"conventions",
"."
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L739-L774 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray._findOne | def _findOne(self, subString):
"""
>>> SA=SuffixArray("mississippi", unit=UNIT_BYTE)
>>> SA._findOne("ippi")
1
>>> SA._findOne("missi")
4
"""
SA = self.SA
LCPs = self._LCP_values
string = self.string
try:
subString = _... | python | def _findOne(self, subString):
"""
>>> SA=SuffixArray("mississippi", unit=UNIT_BYTE)
>>> SA._findOne("ippi")
1
>>> SA._findOne("missi")
4
"""
SA = self.SA
LCPs = self._LCP_values
string = self.string
try:
subString = _... | [
"def",
"_findOne",
"(",
"self",
",",
"subString",
")",
":",
"SA",
"=",
"self",
".",
"SA",
"LCPs",
"=",
"self",
".",
"_LCP_values",
"string",
"=",
"self",
".",
"string",
"try",
":",
"subString",
"=",
"_array",
"(",
"\"i\"",
",",
"[",
"self",
".",
"t... | >>> SA=SuffixArray("mississippi", unit=UNIT_BYTE)
>>> SA._findOne("ippi")
1
>>> SA._findOne("missi")
4 | [
">>>",
"SA",
"=",
"SuffixArray",
"(",
"mississippi",
"unit",
"=",
"UNIT_BYTE",
")",
">>>",
"SA",
".",
"_findOne",
"(",
"ippi",
")",
"1"
] | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L776-L822 |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | SuffixArray.find | def find(self, subString, features=[]):
"""
Dichotomy search of subString in the suffix array.
As soon as a suffix which starts with subString is found,
it uses the LCPs in order to find the other matching suffixes.
The outputs consists in a list of tuple (pos, feature0, feature... | python | def find(self, subString, features=[]):
"""
Dichotomy search of subString in the suffix array.
As soon as a suffix which starts with subString is found,
it uses the LCPs in order to find the other matching suffixes.
The outputs consists in a list of tuple (pos, feature0, feature... | [
"def",
"find",
"(",
"self",
",",
"subString",
",",
"features",
"=",
"[",
"]",
")",
":",
"SA",
"=",
"self",
".",
"SA",
"LCPs",
"=",
"self",
".",
"_LCP_values",
"string",
"=",
"self",
".",
"string",
"middle",
"=",
"self",
".",
"_findOne",
"(",
"subSt... | Dichotomy search of subString in the suffix array.
As soon as a suffix which starts with subString is found,
it uses the LCPs in order to find the other matching suffixes.
The outputs consists in a list of tuple (pos, feature0, feature1, ...)
where feature0, feature1, ... are the featur... | [
"Dichotomy",
"search",
"of",
"subString",
"in",
"the",
"suffix",
"array",
".",
"As",
"soon",
"as",
"a",
"suffix",
"which",
"starts",
"with",
"subString",
"is",
"found",
"it",
"uses",
"the",
"LCPs",
"in",
"order",
"to",
"find",
"the",
"other",
"matching",
... | train | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L824-L906 |
sramana/pyatom | pyatom.py | escape | def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character (") is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
... | python | def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character (") is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
... | [
"def",
"escape",
"(",
"s",
",",
"quote",
"=",
"False",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"''",
"elif",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"return",
"s",
".",
"__html__",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"... | Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character (") is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
:param quote: set to true to al... | [
"Replace",
"special",
"characters",
"&",
"<",
"and",
">",
"to",
"HTML",
"-",
"safe",
"sequences",
".",
"If",
"the",
"optional",
"flag",
"quote",
"is",
"True",
"the",
"quotation",
"mark",
"character",
"(",
")",
"is",
"also",
"translated",
"."
] | train | https://github.com/sramana/pyatom/blob/9b937ac86926a1aa0e14ae774d1cc303f46327d5/pyatom.py#L42-L61 |
sramana/pyatom | pyatom.py | AtomFeed.add | def add(self, *args, **kwargs):
"""Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor.
"""
if len(args) == 1 and not kwargs and isinstance(arg... | python | def add(self, *args, **kwargs):
"""Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor.
"""
if len(args) == 1 and not kwargs and isinstance(arg... | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"not",
"kwargs",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"FeedEntry",
")",
":",
"self",
".",
"entries... | Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor. | [
"Add",
"a",
"new",
"entry",
"to",
"the",
"feed",
".",
"This",
"function",
"can",
"either",
"be",
"called",
"with",
"a",
":",
"class",
":",
"FeedEntry",
"or",
"some",
"keyword",
"and",
"positional",
"arguments",
"that",
"are",
"forwarded",
"to",
"the",
":... | train | https://github.com/sramana/pyatom/blob/9b937ac86926a1aa0e14ae774d1cc303f46327d5/pyatom.py#L167-L177 |
sramana/pyatom | pyatom.py | AtomFeed.generate | def generate(self):
"""Return a generator that yields pieces of XML."""
# atom demands either an author element in every entry or a global one
if not self.author:
if False in map(lambda e: bool(e.author), self.entries):
self.author = ({'name': u'unbekannter Autor'},)
... | python | def generate(self):
"""Return a generator that yields pieces of XML."""
# atom demands either an author element in every entry or a global one
if not self.author:
if False in map(lambda e: bool(e.author), self.entries):
self.author = ({'name': u'unbekannter Autor'},)
... | [
"def",
"generate",
"(",
"self",
")",
":",
"# atom demands either an author element in every entry or a global one",
"if",
"not",
"self",
".",
"author",
":",
"if",
"False",
"in",
"map",
"(",
"lambda",
"e",
":",
"bool",
"(",
"e",
".",
"author",
")",
",",
"self",... | Return a generator that yields pieces of XML. | [
"Return",
"a",
"generator",
"that",
"yields",
"pieces",
"of",
"XML",
"."
] | train | https://github.com/sramana/pyatom/blob/9b937ac86926a1aa0e14ae774d1cc303f46327d5/pyatom.py#L186-L240 |
sramana/pyatom | pyatom.py | FeedEntry.generate | def generate(self):
"""Yields pieces of ATOM XML."""
base = ''
if self.xml_base:
base = ' xml:base="%s"' % escape(self.xml_base, True)
yield u'<entry%s>\n' % base
yield u' ' + _make_text_block('title', self.title, self.title_type)
yield u' <id>%s</id>\n' % e... | python | def generate(self):
"""Yields pieces of ATOM XML."""
base = ''
if self.xml_base:
base = ' xml:base="%s"' % escape(self.xml_base, True)
yield u'<entry%s>\n' % base
yield u' ' + _make_text_block('title', self.title, self.title_type)
yield u' <id>%s</id>\n' % e... | [
"def",
"generate",
"(",
"self",
")",
":",
"base",
"=",
"''",
"if",
"self",
".",
"xml_base",
":",
"base",
"=",
"' xml:base=\"%s\"'",
"%",
"escape",
"(",
"self",
".",
"xml_base",
",",
"True",
")",
"yield",
"u'<entry%s>\\n'",
"%",
"base",
"yield",
"u' '",
... | Yields pieces of ATOM XML. | [
"Yields",
"pieces",
"of",
"ATOM",
"XML",
"."
] | train | https://github.com/sramana/pyatom/blob/9b937ac86926a1aa0e14ae774d1cc303f46327d5/pyatom.py#L337-L376 |
nitely/django-djconfig | djconfig/utils.py | override_djconfig | def override_djconfig(**new_cache_values):
"""
Temporarily override config values.
This is similar to :py:func:`django.test.override_settings`,\
use it in testing.
:param new_cache_values: Keyword arguments,\
the key should match one in the config,\
a new one is created otherwise,\
the... | python | def override_djconfig(**new_cache_values):
"""
Temporarily override config values.
This is similar to :py:func:`django.test.override_settings`,\
use it in testing.
:param new_cache_values: Keyword arguments,\
the key should match one in the config,\
a new one is created otherwise,\
the... | [
"def",
"override_djconfig",
"(",
"*",
"*",
"new_cache_values",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"old_cache_values",
"=",
"{",
... | Temporarily override config values.
This is similar to :py:func:`django.test.override_settings`,\
use it in testing.
:param new_cache_values: Keyword arguments,\
the key should match one in the config,\
a new one is created otherwise,\
the value is overridden within\
the decorated function | [
"Temporarily",
"override",
"config",
"values",
"."
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/utils.py#L17-L56 |
nitely/django-djconfig | djconfig/utils.py | serialize | def serialize(value, field):
"""
Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value
"""
assert isinstance(field, forms.Field)
if isinstance(field, forms.ModelMultipleChoiceField):
... | python | def serialize(value, field):
"""
Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value
"""
assert isinstance(field, forms.Field)
if isinstance(field, forms.ModelMultipleChoiceField):
... | [
"def",
"serialize",
"(",
"value",
",",
"field",
")",
":",
"assert",
"isinstance",
"(",
"field",
",",
"forms",
".",
"Field",
")",
"if",
"isinstance",
"(",
"field",
",",
"forms",
".",
"ModelMultipleChoiceField",
")",
":",
"return",
"json",
".",
"dumps",
"(... | Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value | [
"Form",
"values",
"serialization"
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/utils.py#L59-L73 |
nitely/django-djconfig | setup.py | get_version | def get_version(package):
"""Get version without importing the lib"""
with io.open(os.path.join(BASE_DIR, package, '__init__.py'), encoding='utf-8') as fh:
return [
l.split('=', 1)[1].strip().strip("'").strip('"')
for l in fh.readlines()
if '__version__' in l][0] | python | def get_version(package):
"""Get version without importing the lib"""
with io.open(os.path.join(BASE_DIR, package, '__init__.py'), encoding='utf-8') as fh:
return [
l.split('=', 1)[1].strip().strip("'").strip('"')
for l in fh.readlines()
if '__version__' in l][0] | [
"def",
"get_version",
"(",
"package",
")",
":",
"with",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"BASE_DIR",
",",
"package",
",",
"'__init__.py'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"return",
"[",
"l",
"... | Get version without importing the lib | [
"Get",
"version",
"without",
"importing",
"the",
"lib"
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/setup.py#L14-L20 |
nitely/django-djconfig | djconfig/conf.py | _check_backend | def _check_backend():
"""
Check :py:class:`djconfig.middleware.DjConfigMiddleware`\
is registered into ``settings.MIDDLEWARE_CLASSES``
"""
# Django 1.10 does not allow
# both settings to be set
middleware = set(
getattr(settings, 'MIDDLEWARE', None) or
getattr(settings, 'MIDD... | python | def _check_backend():
"""
Check :py:class:`djconfig.middleware.DjConfigMiddleware`\
is registered into ``settings.MIDDLEWARE_CLASSES``
"""
# Django 1.10 does not allow
# both settings to be set
middleware = set(
getattr(settings, 'MIDDLEWARE', None) or
getattr(settings, 'MIDD... | [
"def",
"_check_backend",
"(",
")",
":",
"# Django 1.10 does not allow",
"# both settings to be set",
"middleware",
"=",
"set",
"(",
"getattr",
"(",
"settings",
",",
"'MIDDLEWARE'",
",",
"None",
")",
"or",
"getattr",
"(",
"settings",
",",
"'MIDDLEWARE_CLASSES'",
",",... | Check :py:class:`djconfig.middleware.DjConfigMiddleware`\
is registered into ``settings.MIDDLEWARE_CLASSES`` | [
"Check",
":",
"py",
":",
"class",
":",
"djconfig",
".",
"middleware",
".",
"DjConfigMiddleware",
"\\",
"is",
"registered",
"into",
"settings",
".",
"MIDDLEWARE_CLASSES"
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/conf.py#L23-L45 |
nitely/django-djconfig | djconfig/conf.py | Config._register | def _register(self, form_class, check_middleware=True):
"""
Register a config form into the registry
:param object form_class: The form class to register.\
Must be an instance of :py:class:`djconfig.forms.ConfigForm`
:param bool check_middleware: Check\
:py:class:`djconf... | python | def _register(self, form_class, check_middleware=True):
"""
Register a config form into the registry
:param object form_class: The form class to register.\
Must be an instance of :py:class:`djconfig.forms.ConfigForm`
:param bool check_middleware: Check\
:py:class:`djconf... | [
"def",
"_register",
"(",
"self",
",",
"form_class",
",",
"check_middleware",
"=",
"True",
")",
":",
"if",
"not",
"issubclass",
"(",
"form_class",
",",
"_ConfigFormBase",
")",
":",
"raise",
"ValueError",
"(",
"\"The form does not inherit from `forms.ConfigForm`\"",
"... | Register a config form into the registry
:param object form_class: The form class to register.\
Must be an instance of :py:class:`djconfig.forms.ConfigForm`
:param bool check_middleware: Check\
:py:class:`djconfig.middleware.DjConfigMiddleware`\
is registered into ``settings.MID... | [
"Register",
"a",
"config",
"form",
"into",
"the",
"registry"
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/conf.py#L83-L100 |
nitely/django-djconfig | djconfig/conf.py | Config._reload | def _reload(self):
"""
Gets every registered form's field value.\
If a field name is found in the db, it will load it from there.\
Otherwise, the initial value from the field form is used
"""
ConfigModel = apps.get_model('djconfig.Config')
cache = {}
data ... | python | def _reload(self):
"""
Gets every registered form's field value.\
If a field name is found in the db, it will load it from there.\
Otherwise, the initial value from the field form is used
"""
ConfigModel = apps.get_model('djconfig.Config')
cache = {}
data ... | [
"def",
"_reload",
"(",
"self",
")",
":",
"ConfigModel",
"=",
"apps",
".",
"get_model",
"(",
"'djconfig.Config'",
")",
"cache",
"=",
"{",
"}",
"data",
"=",
"dict",
"(",
"ConfigModel",
".",
"objects",
".",
"all",
"(",
")",
".",
"values_list",
"(",
"'key'... | Gets every registered form's field value.\
If a field name is found in the db, it will load it from there.\
Otherwise, the initial value from the field form is used | [
"Gets",
"every",
"registered",
"form",
"s",
"field",
"value",
".",
"\\",
"If",
"a",
"field",
"name",
"is",
"found",
"in",
"the",
"db",
"it",
"will",
"load",
"it",
"from",
"there",
".",
"\\",
"Otherwise",
"the",
"initial",
"value",
"from",
"the",
"field... | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/conf.py#L102-L142 |
nitely/django-djconfig | djconfig/conf.py | Config._reload_maybe | def _reload_maybe(self):
"""
Reload the config if the config\
model has been updated. This is called\
once on every request by the middleware.\
Should not be called directly.
"""
ConfigModel = apps.get_model('djconfig.Config')
data = dict(
Con... | python | def _reload_maybe(self):
"""
Reload the config if the config\
model has been updated. This is called\
once on every request by the middleware.\
Should not be called directly.
"""
ConfigModel = apps.get_model('djconfig.Config')
data = dict(
Con... | [
"def",
"_reload_maybe",
"(",
"self",
")",
":",
"ConfigModel",
"=",
"apps",
".",
"get_model",
"(",
"'djconfig.Config'",
")",
"data",
"=",
"dict",
"(",
"ConfigModel",
".",
"objects",
".",
"filter",
"(",
"key",
"=",
"'_updated_at'",
")",
".",
"values_list",
"... | Reload the config if the config\
model has been updated. This is called\
once on every request by the middleware.\
Should not be called directly. | [
"Reload",
"the",
"config",
"if",
"the",
"config",
"\\",
"model",
"has",
"been",
"updated",
".",
"This",
"is",
"called",
"\\",
"once",
"on",
"every",
"request",
"by",
"the",
"middleware",
".",
"\\",
"Should",
"not",
"be",
"called",
"directly",
"."
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/conf.py#L144-L160 |
nitely/django-djconfig | djconfig/forms.py | ConfigForm.save | def save(self):
"""
Save the config with the cleaned data,\
update the last modified date so\
the config is reloaded on other process/nodes.\
Reload the config so it can be called right away.
"""
assert self.__class__ in conf.config._registry,\
'%(clas... | python | def save(self):
"""
Save the config with the cleaned data,\
update the last modified date so\
the config is reloaded on other process/nodes.\
Reload the config so it can be called right away.
"""
assert self.__class__ in conf.config._registry,\
'%(clas... | [
"def",
"save",
"(",
"self",
")",
":",
"assert",
"self",
".",
"__class__",
"in",
"conf",
".",
"config",
".",
"_registry",
",",
"'%(class_name)s is not registered'",
"%",
"{",
"'class_name'",
":",
"self",
".",
"__class__",
".",
"__name__",
"}",
"ConfigModel",
... | Save the config with the cleaned data,\
update the last modified date so\
the config is reloaded on other process/nodes.\
Reload the config so it can be called right away. | [
"Save",
"the",
"config",
"with",
"the",
"cleaned",
"data",
"\\",
"update",
"the",
"last",
"modified",
"date",
"so",
"\\",
"the",
"config",
"is",
"reloaded",
"on",
"other",
"process",
"/",
"nodes",
".",
"\\",
"Reload",
"the",
"config",
"so",
"it",
"can",
... | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/forms.py#L36-L71 |
nitely/django-djconfig | djconfig/admin.py | register | def register(conf, conf_admin, **options):
"""
Register a new admin section.
:param conf: A subclass of ``djconfig.admin.Config``
:param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin``
:param options: Extra options passed to ``django.contrib.admin.site.register``
"""
assert issubcl... | python | def register(conf, conf_admin, **options):
"""
Register a new admin section.
:param conf: A subclass of ``djconfig.admin.Config``
:param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin``
:param options: Extra options passed to ``django.contrib.admin.site.register``
"""
assert issubcl... | [
"def",
"register",
"(",
"conf",
",",
"conf_admin",
",",
"*",
"*",
"options",
")",
":",
"assert",
"issubclass",
"(",
"conf_admin",
",",
"ConfigAdmin",
")",
",",
"(",
"'conf_admin is not a ConfigAdmin subclass'",
")",
"assert",
"issubclass",
"(",
"getattr",
"(",
... | Register a new admin section.
:param conf: A subclass of ``djconfig.admin.Config``
:param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin``
:param options: Extra options passed to ``django.contrib.admin.site.register`` | [
"Register",
"a",
"new",
"admin",
"section",
"."
] | train | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/admin.py#L130-L156 |
gamechanger/schemer | schemer/extension_types.py | Mixed | def Mixed(*types):
"""Mixed type, used to indicate a field in a schema can be
one of many types. Use as a last resort only.
The Mixed type can be used directly as a class to indicate
any type is permitted for a given field:
`"my_field": {"type": Mixed}`
It can also be instantiated with list of s... | python | def Mixed(*types):
"""Mixed type, used to indicate a field in a schema can be
one of many types. Use as a last resort only.
The Mixed type can be used directly as a class to indicate
any type is permitted for a given field:
`"my_field": {"type": Mixed}`
It can also be instantiated with list of s... | [
"def",
"Mixed",
"(",
"*",
"types",
")",
":",
"if",
"len",
"(",
"types",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Mixed type requires at least 2 specific types\"",
")",
"types",
"=",
"set",
"(",
"types",
")",
"# dedupe",
"class",
"MixedType",
"(",
... | Mixed type, used to indicate a field in a schema can be
one of many types. Use as a last resort only.
The Mixed type can be used directly as a class to indicate
any type is permitted for a given field:
`"my_field": {"type": Mixed}`
It can also be instantiated with list of specific types the
fiel... | [
"Mixed",
"type",
"used",
"to",
"indicate",
"a",
"field",
"in",
"a",
"schema",
"can",
"be",
"one",
"of",
"many",
"types",
".",
"Use",
"as",
"a",
"last",
"resort",
"only",
".",
"The",
"Mixed",
"type",
"can",
"be",
"used",
"directly",
"as",
"a",
"class"... | train | https://github.com/gamechanger/schemer/blob/1d1dd7da433d3b84ce5a80ded5a84ab4a65825ee/schemer/extension_types.py#L1-L28 |
gamechanger/schemer | schemer/validators.py | one_of | def one_of(*args):
"""
Validates that a field value matches one of the values
given to this validator.
"""
if len(args) == 1 and isinstance(args[0], list):
items = args[0]
else:
items = list(args)
def validate(value):
if not value in items:
return e("{} i... | python | def one_of(*args):
"""
Validates that a field value matches one of the values
given to this validator.
"""
if len(args) == 1 and isinstance(args[0], list):
items = args[0]
else:
items = list(args)
def validate(value):
if not value in items:
return e("{} i... | [
"def",
"one_of",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"list",
")",
":",
"items",
"=",
"args",
"[",
"0",
"]",
"else",
":",
"items",
"=",
"list",
"(",
"args"... | Validates that a field value matches one of the values
given to this validator. | [
"Validates",
"that",
"a",
"field",
"value",
"matches",
"one",
"of",
"the",
"values",
"given",
"to",
"this",
"validator",
"."
] | train | https://github.com/gamechanger/schemer/blob/1d1dd7da433d3b84ce5a80ded5a84ab4a65825ee/schemer/validators.py#L8-L21 |
gamechanger/schemer | schemer/validators.py | gte | def gte(min_value):
"""
Validates that a field value is greater than or equal to the
value given to this validator.
"""
def validate(value):
if value < min_value:
return e("{} is not greater than or equal to {}", value, min_value)
return validate | python | def gte(min_value):
"""
Validates that a field value is greater than or equal to the
value given to this validator.
"""
def validate(value):
if value < min_value:
return e("{} is not greater than or equal to {}", value, min_value)
return validate | [
"def",
"gte",
"(",
"min_value",
")",
":",
"def",
"validate",
"(",
"value",
")",
":",
"if",
"value",
"<",
"min_value",
":",
"return",
"e",
"(",
"\"{} is not greater than or equal to {}\"",
",",
"value",
",",
"min_value",
")",
"return",
"validate"
] | Validates that a field value is greater than or equal to the
value given to this validator. | [
"Validates",
"that",
"a",
"field",
"value",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"value",
"given",
"to",
"this",
"validator",
"."
] | train | https://github.com/gamechanger/schemer/blob/1d1dd7da433d3b84ce5a80ded5a84ab4a65825ee/schemer/validators.py#L24-L32 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.