repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
night-crawler/django-docker-helpers
django_docker_helpers/management.py
create_admin
def create_admin(user_config_path: str = 'CONFIG.superuser') -> bool: """ Creates a superuser from a specified dict/object bundle located at ``user_config_path``. Skips if the specified object contains no email or no username. If a user with the specified username already exists and has no usable passwo...
python
def create_admin(user_config_path: str = 'CONFIG.superuser') -> bool: """ Creates a superuser from a specified dict/object bundle located at ``user_config_path``. Skips if the specified object contains no email or no username. If a user with the specified username already exists and has no usable passwo...
[ "def", "create_admin", "(", "user_config_path", ":", "str", "=", "'CONFIG.superuser'", ")", "->", "bool", ":", "from", "django", ".", "conf", "import", "settings", "wf", "(", "'Creating superuser... '", ",", "False", ")", "username", ",", "email", ",", "passwo...
Creates a superuser from a specified dict/object bundle located at ``user_config_path``. Skips if the specified object contains no email or no username. If a user with the specified username already exists and has no usable password it updates user's password with a specified one. ``user_config_path`` ...
[ "Creates", "a", "superuser", "from", "a", "specified", "dict", "/", "object", "bundle", "located", "at", "user_config_path", ".", "Skips", "if", "the", "specified", "object", "contains", "no", "email", "or", "no", "username", ".", "If", "a", "user", "with", ...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/management.py#L8-L69
train
night-crawler/django-docker-helpers
django_docker_helpers/management.py
run_gunicorn
def run_gunicorn(application: WSGIHandler, gunicorn_module_name: str = 'gunicorn_prod'): """ Runs gunicorn with a specified config. :param application: Django uwsgi application :param gunicorn_module_name: gunicorn settings module name :return: ``Application().run()`` """ from gunicorn.app....
python
def run_gunicorn(application: WSGIHandler, gunicorn_module_name: str = 'gunicorn_prod'): """ Runs gunicorn with a specified config. :param application: Django uwsgi application :param gunicorn_module_name: gunicorn settings module name :return: ``Application().run()`` """ from gunicorn.app....
[ "def", "run_gunicorn", "(", "application", ":", "WSGIHandler", ",", "gunicorn_module_name", ":", "str", "=", "'gunicorn_prod'", ")", ":", "from", "gunicorn", ".", "app", ".", "base", "import", "Application", "class", "DjangoApplication", "(", "Application", ")", ...
Runs gunicorn with a specified config. :param application: Django uwsgi application :param gunicorn_module_name: gunicorn settings module name :return: ``Application().run()``
[ "Runs", "gunicorn", "with", "a", "specified", "config", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/management.py#L72-L96
train
alefnula/tea
tea/console/color.py
set_color
def set_color( fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, ): """Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal """ _set_color(fg, bg, fg_dar...
python
def set_color( fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, ): """Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal """ _set_color(fg, bg, fg_dar...
[ "def", "set_color", "(", "fg", "=", "Color", ".", "normal", ",", "bg", "=", "Color", ".", "normal", ",", "fg_dark", "=", "False", ",", "bg_dark", "=", "False", ",", "underlined", "=", "False", ",", ")", ":", "_set_color", "(", "fg", ",", "bg", ",",...
Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal
[ "Set", "the", "console", "color", ".", ">>>", "set_color", "(", "Color", ".", "red", "Color", ".", "blue", ")", ">>>", "set_color", "(", "red", "blue", ")", ">>>", "set_color", "()", "#", "returns", "back", "to", "normal" ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/color.py#L171-L184
train
alefnula/tea
tea/console/color.py
cprint
def cprint( text, fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, parse=False, ): """Print string in to stdout using colored font. See L{set_color} for more details about colors. Args: text (str): Text that needs to be pri...
python
def cprint( text, fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, parse=False, ): """Print string in to stdout using colored font. See L{set_color} for more details about colors. Args: text (str): Text that needs to be pri...
[ "def", "cprint", "(", "text", ",", "fg", "=", "Color", ".", "normal", ",", "bg", "=", "Color", ".", "normal", ",", "fg_dark", "=", "False", ",", "bg_dark", "=", "False", ",", "underlined", "=", "False", ",", "parse", "=", "False", ",", ")", ":", ...
Print string in to stdout using colored font. See L{set_color} for more details about colors. Args: text (str): Text that needs to be printed.
[ "Print", "string", "in", "to", "stdout", "using", "colored", "font", ".", "See", "L", "{", "set_color", "}", "for", "more", "details", "about", "colors", ".", "Args", ":", "text", "(", "str", ")", ":", "Text", "that", "needs", "to", "be", "printed", ...
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/color.py#L202-L239
train
alefnula/tea
tea/console/color.py
colorize_output
def colorize_output(output, colors, indent=0): r"""Print output to console using provided color mappings. Color mapping is dict with regular expressions as key and tuple of two as values. Key is used to match if line should be colorized and tuple contains color to be used and boolean value that in...
python
def colorize_output(output, colors, indent=0): r"""Print output to console using provided color mappings. Color mapping is dict with regular expressions as key and tuple of two as values. Key is used to match if line should be colorized and tuple contains color to be used and boolean value that in...
[ "def", "colorize_output", "(", "output", ",", "colors", ",", "indent", "=", "0", ")", ":", "for", "line", "in", "output", ".", "split", "(", "\"\\n\"", ")", ":", "cprint", "(", "\" \"", "*", "indent", ")", "if", "line", "==", "\"\"", ":", "cprint", ...
r"""Print output to console using provided color mappings. Color mapping is dict with regular expressions as key and tuple of two as values. Key is used to match if line should be colorized and tuple contains color to be used and boolean value that indicates if dark foreground is used. For ex...
[ "r", "Print", "output", "to", "console", "using", "provided", "color", "mappings", ".", "Color", "mapping", "is", "dict", "with", "regular", "expressions", "as", "key", "and", "tuple", "of", "two", "as", "values", ".", "Key", "is", "used", "to", "match", ...
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/color.py#L242-L283
train
alefnula/tea
tea/console/color.py
_colorize_single_line
def _colorize_single_line(line, regexp, color_def): """Print single line to console with ability to colorize parts of it.""" match = regexp.match(line) groupdict = match.groupdict() groups = match.groups() if not groupdict: # no named groups, just colorize whole line color = c...
python
def _colorize_single_line(line, regexp, color_def): """Print single line to console with ability to colorize parts of it.""" match = regexp.match(line) groupdict = match.groupdict() groups = match.groups() if not groupdict: # no named groups, just colorize whole line color = c...
[ "def", "_colorize_single_line", "(", "line", ",", "regexp", ",", "color_def", ")", ":", "match", "=", "regexp", ".", "match", "(", "line", ")", "groupdict", "=", "match", ".", "groupdict", "(", ")", "groups", "=", "match", ".", "groups", "(", ")", "if"...
Print single line to console with ability to colorize parts of it.
[ "Print", "single", "line", "to", "console", "with", "ability", "to", "colorize", "parts", "of", "it", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/color.py#L286-L308
train
pyout/pyout
pyout/tabular.py
TerminalStream.height
def height(self): """Terminal height. """ if self.interactive: if self._height is None: self._height = self.term.height return self._height
python
def height(self): """Terminal height. """ if self.interactive: if self._height is None: self._height = self.term.height return self._height
[ "def", "height", "(", "self", ")", ":", "if", "self", ".", "interactive", ":", "if", "self", ".", "_height", "is", "None", ":", "self", ".", "_height", "=", "self", ".", "term", ".", "height", "return", "self", ".", "_height" ]
Terminal height.
[ "Terminal", "height", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/tabular.py#L39-L45
train
pyout/pyout
pyout/tabular.py
TerminalStream.clear_last_lines
def clear_last_lines(self, n): """Clear last N lines of terminal output. """ self.term.stream.write( self.term.move_up * n + self.term.clear_eos) self.term.stream.flush()
python
def clear_last_lines(self, n): """Clear last N lines of terminal output. """ self.term.stream.write( self.term.move_up * n + self.term.clear_eos) self.term.stream.flush()
[ "def", "clear_last_lines", "(", "self", ",", "n", ")", ":", "self", ".", "term", ".", "stream", ".", "write", "(", "self", ".", "term", ".", "move_up", "*", "n", "+", "self", ".", "term", ".", "clear_eos", ")", "self", ".", "term", ".", "stream", ...
Clear last N lines of terminal output.
[ "Clear", "last", "N", "lines", "of", "terminal", "output", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/tabular.py#L52-L57
train
pyout/pyout
pyout/tabular.py
TerminalStream.overwrite_line
def overwrite_line(self, n, text): """Move back N lines and overwrite line with `text`. """ with self._moveback(n): self.term.stream.write(text)
python
def overwrite_line(self, n, text): """Move back N lines and overwrite line with `text`. """ with self._moveback(n): self.term.stream.write(text)
[ "def", "overwrite_line", "(", "self", ",", "n", ",", "text", ")", ":", "with", "self", ".", "_moveback", "(", "n", ")", ":", "self", ".", "term", ".", "stream", ".", "write", "(", "text", ")" ]
Move back N lines and overwrite line with `text`.
[ "Move", "back", "N", "lines", "and", "overwrite", "line", "with", "text", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/tabular.py#L68-L72
train
pyout/pyout
pyout/tabular.py
TerminalStream.move_to
def move_to(self, n): """Move back N lines in terminal. """ self.term.stream.write(self.term.move_up * n)
python
def move_to(self, n): """Move back N lines in terminal. """ self.term.stream.write(self.term.move_up * n)
[ "def", "move_to", "(", "self", ",", "n", ")", ":", "self", ".", "term", ".", "stream", ".", "write", "(", "self", ".", "term", ".", "move_up", "*", "n", ")" ]
Move back N lines in terminal.
[ "Move", "back", "N", "lines", "in", "terminal", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/tabular.py#L74-L77
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
ConfigLoader.get
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, required: bool = False, **kwargs): """ Tries to read a ``variable_path`` from each ...
python
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, required: bool = False, **kwargs): """ Tries to read a ``variable_path`` from each ...
[ "def", "get", "(", "self", ",", "variable_path", ":", "str", ",", "default", ":", "t", ".", "Optional", "[", "t", ".", "Any", "]", "=", "None", ",", "coerce_type", ":", "t", ".", "Optional", "[", "t", ".", "Type", "]", "=", "None", ",", "coercer"...
Tries to read a ``variable_path`` from each of the passed parsers. It stops if read was successful and returns a retrieved value. If none of the parsers contain a value for the specified path it returns ``default``. :param variable_path: a path to variable in config :param default: a de...
[ "Tries", "to", "read", "a", "variable_path", "from", "each", "of", "the", "passed", "parsers", ".", "It", "stops", "if", "read", "was", "successful", "and", "returns", "a", "retrieved", "value", ".", "If", "none", "of", "the", "parsers", "contain", "a", ...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L118-L169
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
ConfigLoader.import_parsers
def import_parsers(parser_modules: t.Iterable[str]) -> t.Generator[t.Type[BaseParser], None, None]: """ Resolves and imports all modules specified in ``parser_modules``. Short names from the local scope are supported (the scope is ``django_docker_helpers.config.backends``). :param parse...
python
def import_parsers(parser_modules: t.Iterable[str]) -> t.Generator[t.Type[BaseParser], None, None]: """ Resolves and imports all modules specified in ``parser_modules``. Short names from the local scope are supported (the scope is ``django_docker_helpers.config.backends``). :param parse...
[ "def", "import_parsers", "(", "parser_modules", ":", "t", ".", "Iterable", "[", "str", "]", ")", "->", "t", ".", "Generator", "[", "t", ".", "Type", "[", "BaseParser", "]", ",", "None", ",", "None", "]", ":", "for", "import_path", "in", "parser_modules...
Resolves and imports all modules specified in ``parser_modules``. Short names from the local scope are supported (the scope is ``django_docker_helpers.config.backends``). :param parser_modules: a list of dot-separated module paths :return: a generator of [probably] :class:`~django_docker_helper...
[ "Resolves", "and", "imports", "all", "modules", "specified", "in", "parser_modules", ".", "Short", "names", "from", "the", "local", "scope", "are", "supported", "(", "the", "scope", "is", "django_docker_helpers", ".", "config", ".", "backends", ")", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L172-L197
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
ConfigLoader.load_parser_options_from_env
def load_parser_options_from_env( parser_class: t.Type[BaseParser], env: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, t.Any]: """ Extracts arguments from ``parser_class.__init__`` and populates them from environment variables. Uses ``__init__`` argument type annot...
python
def load_parser_options_from_env( parser_class: t.Type[BaseParser], env: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, t.Any]: """ Extracts arguments from ``parser_class.__init__`` and populates them from environment variables. Uses ``__init__`` argument type annot...
[ "def", "load_parser_options_from_env", "(", "parser_class", ":", "t", ".", "Type", "[", "BaseParser", "]", ",", "env", ":", "t", ".", "Optional", "[", "t", ".", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "t", ".", "Dict", "["...
Extracts arguments from ``parser_class.__init__`` and populates them from environment variables. Uses ``__init__`` argument type annotations for correct type casting. .. note:: Environment variables should be prefixed with ``<UPPERCASEPARSERCLASSNAME>__``. :param parser_class: a ...
[ "Extracts", "arguments", "from", "parser_class", ".", "__init__", "and", "populates", "them", "from", "environment", "variables", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L200-L266
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
ConfigLoader.from_env
def from_env(parser_modules: t.Optional[t.Union[t.List[str], t.Tuple[str]]] = DEFAULT_PARSER_MODULES, env: t.Optional[t.Dict[str, str]] = None, silent: bool = False, suppress_logs: bool = False, extra: t.Optional[dict] = None) -> 'ConfigLoader': ...
python
def from_env(parser_modules: t.Optional[t.Union[t.List[str], t.Tuple[str]]] = DEFAULT_PARSER_MODULES, env: t.Optional[t.Dict[str, str]] = None, silent: bool = False, suppress_logs: bool = False, extra: t.Optional[dict] = None) -> 'ConfigLoader': ...
[ "def", "from_env", "(", "parser_modules", ":", "t", ".", "Optional", "[", "t", ".", "Union", "[", "t", ".", "List", "[", "str", "]", ",", "t", ".", "Tuple", "[", "str", "]", "]", "]", "=", "DEFAULT_PARSER_MODULES", ",", "env", ":", "t", ".", "Opt...
Creates an instance of :class:`~django_docker_helpers.config.ConfigLoader` with parsers initialized from environment variables. By default it tries to initialize all bundled parsers. Parsers may be customized with ``parser_modules`` argument or ``CONFIG__PARSERS`` environment variable. ...
[ "Creates", "an", "instance", "of", ":", "class", ":", "~django_docker_helpers", ".", "config", ".", "ConfigLoader", "with", "parsers", "initialized", "from", "environment", "variables", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L269-L339
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
ConfigLoader.print_config_read_queue
def print_config_read_queue( self, use_color: bool = False, max_col_width: int = 50): """ Prints all read (in call order) options. :param max_col_width: limit column width, ``50`` by default :param use_color: use terminal colors :return: nothi...
python
def print_config_read_queue( self, use_color: bool = False, max_col_width: int = 50): """ Prints all read (in call order) options. :param max_col_width: limit column width, ``50`` by default :param use_color: use terminal colors :return: nothi...
[ "def", "print_config_read_queue", "(", "self", ",", "use_color", ":", "bool", "=", "False", ",", "max_col_width", ":", "int", "=", "50", ")", ":", "wf", "(", "self", ".", "format_config_read_queue", "(", "use_color", "=", "use_color", ",", "max_col_width", "...
Prints all read (in call order) options. :param max_col_width: limit column width, ``50`` by default :param use_color: use terminal colors :return: nothing
[ "Prints", "all", "read", "(", "in", "call", "order", ")", "options", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L361-L373
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
ConfigLoader.format_config_read_queue
def format_config_read_queue(self, use_color: bool = False, max_col_width: int = 50) -> str: """ Prepares a string with pretty printed config read queue. :param use_color: use terminal colors :param max_col_width: limit c...
python
def format_config_read_queue(self, use_color: bool = False, max_col_width: int = 50) -> str: """ Prepares a string with pretty printed config read queue. :param use_color: use terminal colors :param max_col_width: limit c...
[ "def", "format_config_read_queue", "(", "self", ",", "use_color", ":", "bool", "=", "False", ",", "max_col_width", ":", "int", "=", "50", ")", "->", "str", ":", "try", ":", "from", "terminaltables", "import", "SingleTable", "except", "ImportError", ":", "imp...
Prepares a string with pretty printed config read queue. :param use_color: use terminal colors :param max_col_width: limit column width, ``50`` by default :return:
[ "Prepares", "a", "string", "with", "pretty", "printed", "config", "read", "queue", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L375-L417
train
hufman/flask_rdf
flask_rdf/flask.py
Decorator.get_graph
def get_graph(cls, response): """ Given a Flask response, find the rdflib Graph """ if cls.is_graph(response): # single graph object return response if hasattr(response, '__getitem__'): # indexable tuple if len(response) > 0 and \ cls.is_graph(response[0]): # graph object return response[0]
python
def get_graph(cls, response): """ Given a Flask response, find the rdflib Graph """ if cls.is_graph(response): # single graph object return response if hasattr(response, '__getitem__'): # indexable tuple if len(response) > 0 and \ cls.is_graph(response[0]): # graph object return response[0]
[ "def", "get_graph", "(", "cls", ",", "response", ")", ":", "if", "cls", ".", "is_graph", "(", "response", ")", ":", "# single graph object", "return", "response", "if", "hasattr", "(", "response", ",", "'__getitem__'", ")", ":", "# indexable tuple", "if", "l...
Given a Flask response, find the rdflib Graph
[ "Given", "a", "Flask", "response", "find", "the", "rdflib", "Graph" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/flask.py#L8-L16
train
hufman/flask_rdf
flask_rdf/flask.py
Decorator.replace_graph
def replace_graph(cls, response, serialized): """ Replace the rdflib Graph in a Flask response """ if cls.is_graph(response): # single graph object return serialized if hasattr(response, '__getitem__'): # indexable tuple if len(response) > 0 and \ cls.is_graph(response[0]): # graph object return ...
python
def replace_graph(cls, response, serialized): """ Replace the rdflib Graph in a Flask response """ if cls.is_graph(response): # single graph object return serialized if hasattr(response, '__getitem__'): # indexable tuple if len(response) > 0 and \ cls.is_graph(response[0]): # graph object return ...
[ "def", "replace_graph", "(", "cls", ",", "response", ",", "serialized", ")", ":", "if", "cls", ".", "is_graph", "(", "response", ")", ":", "# single graph object", "return", "serialized", "if", "hasattr", "(", "response", ",", "'__getitem__'", ")", ":", "# i...
Replace the rdflib Graph in a Flask response
[ "Replace", "the", "rdflib", "Graph", "in", "a", "Flask", "response" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/flask.py#L19-L28
train
alefnula/tea
tea/utils/crypto.py
_from_hex_digest
def _from_hex_digest(digest): """Convert hex digest to sequence of bytes.""" return "".join( [chr(int(digest[x : x + 2], 16)) for x in range(0, len(digest), 2)] )
python
def _from_hex_digest(digest): """Convert hex digest to sequence of bytes.""" return "".join( [chr(int(digest[x : x + 2], 16)) for x in range(0, len(digest), 2)] )
[ "def", "_from_hex_digest", "(", "digest", ")", ":", "return", "\"\"", ".", "join", "(", "[", "chr", "(", "int", "(", "digest", "[", "x", ":", "x", "+", "2", "]", ",", "16", ")", ")", "for", "x", "in", "range", "(", "0", ",", "len", "(", "dige...
Convert hex digest to sequence of bytes.
[ "Convert", "hex", "digest", "to", "sequence", "of", "bytes", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/crypto.py#L112-L116
train
alefnula/tea
tea/utils/crypto.py
encrypt
def encrypt(data, digest=True): """Perform encryption of provided data.""" alg = get_best_algorithm() enc = implementations["encryption"][alg]( data, implementations["get_key"]() ) return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc))
python
def encrypt(data, digest=True): """Perform encryption of provided data.""" alg = get_best_algorithm() enc = implementations["encryption"][alg]( data, implementations["get_key"]() ) return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc))
[ "def", "encrypt", "(", "data", ",", "digest", "=", "True", ")", ":", "alg", "=", "get_best_algorithm", "(", ")", "enc", "=", "implementations", "[", "\"encryption\"", "]", "[", "alg", "]", "(", "data", ",", "implementations", "[", "\"get_key\"", "]", "("...
Perform encryption of provided data.
[ "Perform", "encryption", "of", "provided", "data", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/crypto.py#L428-L434
train
alefnula/tea
tea/utils/crypto.py
decrypt
def decrypt(data, digest=True): """Decrypt provided data.""" alg, _, data = data.rpartition("$") if not alg: return data data = _from_hex_digest(data) if digest else data try: return implementations["decryption"][alg]( data, implementations["get_key"]() ) exce...
python
def decrypt(data, digest=True): """Decrypt provided data.""" alg, _, data = data.rpartition("$") if not alg: return data data = _from_hex_digest(data) if digest else data try: return implementations["decryption"][alg]( data, implementations["get_key"]() ) exce...
[ "def", "decrypt", "(", "data", ",", "digest", "=", "True", ")", ":", "alg", ",", "_", ",", "data", "=", "data", ".", "rpartition", "(", "\"$\"", ")", "if", "not", "alg", ":", "return", "data", "data", "=", "_from_hex_digest", "(", "data", ")", "if"...
Decrypt provided data.
[ "Decrypt", "provided", "data", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/crypto.py#L437-L448
train
lingfeiwang/findr-python
findr/netr.py
one_greedy
def one_greedy(self,dp,namax=None,nimax=None,nomax=None): """Reconstructs a directed acyclic graph according to prior information of edge significance. This function first ranks all edges and introduce the most significant one by one, avoiding those that would create a loop. Optional constraints on the maximum total...
python
def one_greedy(self,dp,namax=None,nimax=None,nomax=None): """Reconstructs a directed acyclic graph according to prior information of edge significance. This function first ranks all edges and introduce the most significant one by one, avoiding those that would create a loop. Optional constraints on the maximum total...
[ "def", "one_greedy", "(", "self", ",", "dp", ",", "namax", "=", "None", ",", "nimax", "=", "None", ",", "nomax", "=", "None", ")", ":", "try", ":", "from", "exceptions", "import", "ValueError", "except", "ImportError", ":", "pass", "if", "self", ".", ...
Reconstructs a directed acyclic graph according to prior information of edge significance. This function first ranks all edges and introduce the most significant one by one, avoiding those that would create a loop. Optional constraints on the maximum total number of edges, the number of incoming or outgoing edges fo...
[ "Reconstructs", "a", "directed", "acyclic", "graph", "according", "to", "prior", "information", "of", "edge", "significance", ".", "This", "function", "first", "ranks", "all", "edges", "and", "introduce", "the", "most", "significant", "one", "by", "one", "avoidi...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/netr.py#L20-L91
train
letuananh/chirptext
chirp.py
gen_vocab
def gen_vocab(cli, args): ''' Generate vocabulary list from a tokenized file ''' if args.topk and args.topk <= 0: topk = None cli.logger.warning("Invalid k will be ignored (k should be greater than or equal to 1)") else: topk = args.topk if args.stopwords: with open(args....
python
def gen_vocab(cli, args): ''' Generate vocabulary list from a tokenized file ''' if args.topk and args.topk <= 0: topk = None cli.logger.warning("Invalid k will be ignored (k should be greater than or equal to 1)") else: topk = args.topk if args.stopwords: with open(args....
[ "def", "gen_vocab", "(", "cli", ",", "args", ")", ":", "if", "args", ".", "topk", "and", "args", ".", "topk", "<=", "0", ":", "topk", "=", "None", "cli", ".", "logger", ".", "warning", "(", "\"Invalid k will be ignored (k should be greater than or equal to 1)\...
Generate vocabulary list from a tokenized file
[ "Generate", "vocabulary", "list", "from", "a", "tokenized", "file" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirp.py#L70-L101
train
letuananh/chirptext
chirp.py
main
def main(): ''' ChirpText Tools main function ''' app = CLIApp(desc='ChirpText Tools', logger=__name__, show_version=show_version) # add tasks vocab_task = app.add_task('vocab', func=gen_vocab) vocab_task.add_argument('input', help='Input file') vocab_task.add_argument('--output', help='Output f...
python
def main(): ''' ChirpText Tools main function ''' app = CLIApp(desc='ChirpText Tools', logger=__name__, show_version=show_version) # add tasks vocab_task = app.add_task('vocab', func=gen_vocab) vocab_task.add_argument('input', help='Input file') vocab_task.add_argument('--output', help='Output f...
[ "def", "main", "(", ")", ":", "app", "=", "CLIApp", "(", "desc", "=", "'ChirpText Tools'", ",", "logger", "=", "__name__", ",", "show_version", "=", "show_version", ")", "# add tasks", "vocab_task", "=", "app", ".", "add_task", "(", "'vocab'", ",", "func",...
ChirpText Tools main function
[ "ChirpText", "Tools", "main", "function" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirp.py#L112-L122
train
nathan-hoad/outbox
outbox.py
add_attachment
def add_attachment(message, attachment, rfc2231=True): '''Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance. ''' data = attachment.read() part = MIMEBase('application', 'octet-stream') part.set_payloa...
python
def add_attachment(message, attachment, rfc2231=True): '''Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance. ''' data = attachment.read() part = MIMEBase('application', 'octet-stream') part.set_payloa...
[ "def", "add_attachment", "(", "message", ",", "attachment", ",", "rfc2231", "=", "True", ")", ":", "data", "=", "attachment", ".", "read", "(", ")", "part", "=", "MIMEBase", "(", "'application'", ",", "'octet-stream'", ")", "part", ".", "set_payload", "(",...
Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance.
[ "Attach", "an", "attachment", "to", "a", "message", "as", "a", "side", "effect", "." ]
afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb
https://github.com/nathan-hoad/outbox/blob/afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb/outbox.py#L219-L235
train
nathan-hoad/outbox
outbox.py
Outbox._login
def _login(self): '''Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ''' server, port, mode, debug = self.connection_details if mode == 'SSL': smtp_class = smtplib.SMTP_SSL else: smtp_class = smtplib.SM...
python
def _login(self): '''Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ''' server, port, mode, debug = self.connection_details if mode == 'SSL': smtp_class = smtplib.SMTP_SSL else: smtp_class = smtplib.SM...
[ "def", "_login", "(", "self", ")", ":", "server", ",", "port", ",", "mode", ",", "debug", "=", "self", ".", "connection_details", "if", "mode", "==", "'SSL'", ":", "smtp_class", "=", "smtplib", ".", "SMTP_SSL", "else", ":", "smtp_class", "=", "smtplib", ...
Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance.
[ "Login", "to", "the", "SMTP", "server", "specified", "at", "instantiation" ]
afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb
https://github.com/nathan-hoad/outbox/blob/afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb/outbox.py#L142-L162
train
nathan-hoad/outbox
outbox.py
Outbox.send
def send(self, email, attachments=()): '''Send an email. Connect/Disconnect if not already connected Arguments: email: Email instance to send. attachments: iterable containing Attachment instances ''' msg = email.as_mime(attachments) if 'From' not in ms...
python
def send(self, email, attachments=()): '''Send an email. Connect/Disconnect if not already connected Arguments: email: Email instance to send. attachments: iterable containing Attachment instances ''' msg = email.as_mime(attachments) if 'From' not in ms...
[ "def", "send", "(", "self", ",", "email", ",", "attachments", "=", "(", ")", ")", ":", "msg", "=", "email", ".", "as_mime", "(", "attachments", ")", "if", "'From'", "not", "in", "msg", ":", "msg", "[", "'From'", "]", "=", "self", ".", "sender_addre...
Send an email. Connect/Disconnect if not already connected Arguments: email: Email instance to send. attachments: iterable containing Attachment instances
[ "Send", "an", "email", ".", "Connect", "/", "Disconnect", "if", "not", "already", "connected" ]
afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb
https://github.com/nathan-hoad/outbox/blob/afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb/outbox.py#L174-L193
train
smnorris/pgdata
pgdata/table.py
Table.column_types
def column_types(self): """Return a dict mapping column name to type for all columns in table """ column_types = {} for c in self.sqla_columns: column_types[c.name] = c.type return column_types
python
def column_types(self): """Return a dict mapping column name to type for all columns in table """ column_types = {} for c in self.sqla_columns: column_types[c.name] = c.type return column_types
[ "def", "column_types", "(", "self", ")", ":", "column_types", "=", "{", "}", "for", "c", "in", "self", ".", "sqla_columns", ":", "column_types", "[", "c", ".", "name", "]", "=", "c", ".", "type", "return", "column_types" ]
Return a dict mapping column name to type for all columns in table
[ "Return", "a", "dict", "mapping", "column", "name", "to", "type", "for", "all", "columns", "in", "table" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L74-L80
train
smnorris/pgdata
pgdata/table.py
Table._valid_table_name
def _valid_table_name(self, table_name): """Check if the table name is obviously invalid. """ if table_name is None or not len(table_name.strip()): raise ValueError("Invalid table name: %r" % table_name) return table_name.strip()
python
def _valid_table_name(self, table_name): """Check if the table name is obviously invalid. """ if table_name is None or not len(table_name.strip()): raise ValueError("Invalid table name: %r" % table_name) return table_name.strip()
[ "def", "_valid_table_name", "(", "self", ",", "table_name", ")", ":", "if", "table_name", "is", "None", "or", "not", "len", "(", "table_name", ".", "strip", "(", ")", ")", ":", "raise", "ValueError", "(", "\"Invalid table name: %r\"", "%", "table_name", ")",...
Check if the table name is obviously invalid.
[ "Check", "if", "the", "table", "name", "is", "obviously", "invalid", "." ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L93-L98
train
smnorris/pgdata
pgdata/table.py
Table.add_primary_key
def add_primary_key(self, column="id"): """Add primary key constraint to specified column """ if not self.primary_key: sql = """ALTER TABLE {s}.{t} ADD PRIMARY KEY ({c}) """.format( s=self.schema, t=self.name, c=column ...
python
def add_primary_key(self, column="id"): """Add primary key constraint to specified column """ if not self.primary_key: sql = """ALTER TABLE {s}.{t} ADD PRIMARY KEY ({c}) """.format( s=self.schema, t=self.name, c=column ...
[ "def", "add_primary_key", "(", "self", ",", "column", "=", "\"id\"", ")", ":", "if", "not", "self", ".", "primary_key", ":", "sql", "=", "\"\"\"ALTER TABLE {s}.{t}\n ADD PRIMARY KEY ({c})\n \"\"\"", ".", "format", "(", "s", "=", "s...
Add primary key constraint to specified column
[ "Add", "primary", "key", "constraint", "to", "specified", "column" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L105-L114
train
smnorris/pgdata
pgdata/table.py
Table.drop
def drop(self): """Drop the table from the database """ if self._is_dropped is False: self.table.drop(self.engine) self._is_dropped = True
python
def drop(self): """Drop the table from the database """ if self._is_dropped is False: self.table.drop(self.engine) self._is_dropped = True
[ "def", "drop", "(", "self", ")", ":", "if", "self", ".", "_is_dropped", "is", "False", ":", "self", ".", "table", ".", "drop", "(", "self", ".", "engine", ")", "self", ".", "_is_dropped", "=", "True" ]
Drop the table from the database
[ "Drop", "the", "table", "from", "the", "database" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L116-L121
train
smnorris/pgdata
pgdata/table.py
Table.create_column
def create_column(self, name, type): """ Explicitely create a new column ``name`` of a specified type. ``type`` must be a `SQLAlchemy column type <http://docs.sqlalchemy.org/en/rel_0_8/core/types.html>`_. :: table.create_column('created_at', sqlalchemy.DateTime) """ ...
python
def create_column(self, name, type): """ Explicitely create a new column ``name`` of a specified type. ``type`` must be a `SQLAlchemy column type <http://docs.sqlalchemy.org/en/rel_0_8/core/types.html>`_. :: table.create_column('created_at', sqlalchemy.DateTime) """ ...
[ "def", "create_column", "(", "self", ",", "name", ",", "type", ")", ":", "self", ".", "_check_dropped", "(", ")", "if", "normalize_column_name", "(", "name", ")", "not", "in", "self", ".", "_normalized_columns", ":", "self", ".", "op", ".", "add_column", ...
Explicitely create a new column ``name`` of a specified type. ``type`` must be a `SQLAlchemy column type <http://docs.sqlalchemy.org/en/rel_0_8/core/types.html>`_. :: table.create_column('created_at', sqlalchemy.DateTime)
[ "Explicitely", "create", "a", "new", "column", "name", "of", "a", "specified", "type", ".", "type", "must", "be", "a", "SQLAlchemy", "column", "type", "<http", ":", "//", "docs", ".", "sqlalchemy", ".", "org", "/", "en", "/", "rel_0_8", "/", "core", "/...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L138-L149
train
smnorris/pgdata
pgdata/table.py
Table.drop_column
def drop_column(self, name): """ Drop the column ``name`` :: table.drop_column('created_at') """ self._check_dropped() if name in list(self.table.columns.keys()): self.op.drop_column(self.table.name, name, schema=self.schema) self.tabl...
python
def drop_column(self, name): """ Drop the column ``name`` :: table.drop_column('created_at') """ self._check_dropped() if name in list(self.table.columns.keys()): self.op.drop_column(self.table.name, name, schema=self.schema) self.tabl...
[ "def", "drop_column", "(", "self", ",", "name", ")", ":", "self", ".", "_check_dropped", "(", ")", "if", "name", "in", "list", "(", "self", ".", "table", ".", "columns", ".", "keys", "(", ")", ")", ":", "self", ".", "op", ".", "drop_column", "(", ...
Drop the column ``name`` :: table.drop_column('created_at')
[ "Drop", "the", "column", "name", "::" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L151-L161
train
smnorris/pgdata
pgdata/table.py
Table.create_index
def create_index(self, columns, name=None, index_type="btree"): """ Create an index to speed up queries on a table. If no ``name`` is given a random name is created. :: table.create_index(['name', 'country']) """ self._check_dropped() if not name: ...
python
def create_index(self, columns, name=None, index_type="btree"): """ Create an index to speed up queries on a table. If no ``name`` is given a random name is created. :: table.create_index(['name', 'country']) """ self._check_dropped() if not name: ...
[ "def", "create_index", "(", "self", ",", "columns", ",", "name", "=", "None", ",", "index_type", "=", "\"btree\"", ")", ":", "self", ".", "_check_dropped", "(", ")", "if", "not", "name", ":", "sig", "=", "\"||\"", ".", "join", "(", "columns", "+", "[...
Create an index to speed up queries on a table. If no ``name`` is given a random name is created. :: table.create_index(['name', 'country'])
[ "Create", "an", "index", "to", "speed", "up", "queries", "on", "a", "table", ".", "If", "no", "name", "is", "given", "a", "random", "name", "is", "created", ".", "::", "table", ".", "create_index", "(", "[", "name", "country", "]", ")" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L163-L190
train
smnorris/pgdata
pgdata/table.py
Table.distinct
def distinct(self, *columns, **_filter): """ Returns all rows of a table, but removes rows in with duplicate values in ``columns``. Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_. :: # returns only one row per year, ignoring th...
python
def distinct(self, *columns, **_filter): """ Returns all rows of a table, but removes rows in with duplicate values in ``columns``. Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_. :: # returns only one row per year, ignoring th...
[ "def", "distinct", "(", "self", ",", "*", "columns", ",", "*", "*", "_filter", ")", ":", "self", ".", "_check_dropped", "(", ")", "qargs", "=", "[", "]", "try", ":", "columns", "=", "[", "self", ".", "table", ".", "c", "[", "c", "]", "for", "c"...
Returns all rows of a table, but removes rows in with duplicate values in ``columns``. Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_. :: # returns only one row per year, ignoring the rest table.distinct('year') # works...
[ "Returns", "all", "rows", "of", "a", "table", "but", "removes", "rows", "in", "with", "duplicate", "values", "in", "columns", ".", "Interally", "this", "creates", "a", "DISTINCT", "statement", "<http", ":", "//", "www", ".", "w3schools", ".", "com", "/", ...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L197-L230
train
smnorris/pgdata
pgdata/table.py
Table.insert
def insert(self, row): """ Add a row (type: dict) by inserting it into the table. Columns must exist. :: data = dict(title='I am a banana!') table.insert(data) Returns the inserted row's primary key. """ self._check_dropped() res = ...
python
def insert(self, row): """ Add a row (type: dict) by inserting it into the table. Columns must exist. :: data = dict(title='I am a banana!') table.insert(data) Returns the inserted row's primary key. """ self._check_dropped() res = ...
[ "def", "insert", "(", "self", ",", "row", ")", ":", "self", ".", "_check_dropped", "(", ")", "res", "=", "self", ".", "engine", ".", "execute", "(", "self", ".", "table", ".", "insert", "(", "row", ")", ")", "if", "len", "(", "res", ".", "inserte...
Add a row (type: dict) by inserting it into the table. Columns must exist. :: data = dict(title='I am a banana!') table.insert(data) Returns the inserted row's primary key.
[ "Add", "a", "row", "(", "type", ":", "dict", ")", "by", "inserting", "it", "into", "the", "table", ".", "Columns", "must", "exist", ".", "::", "data", "=", "dict", "(", "title", "=", "I", "am", "a", "banana!", ")", "table", ".", "insert", "(", "d...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L232-L244
train
smnorris/pgdata
pgdata/table.py
Table.insert_many
def insert_many(self, rows, chunk_size=1000): """ Add many rows at a time, which is significantly faster than adding them one by one. Per default the rows are processed in chunks of 1000 per commit, unless you specify a different ``chunk_size``. See :py:meth:`insert() <dataset.Ta...
python
def insert_many(self, rows, chunk_size=1000): """ Add many rows at a time, which is significantly faster than adding them one by one. Per default the rows are processed in chunks of 1000 per commit, unless you specify a different ``chunk_size``. See :py:meth:`insert() <dataset.Ta...
[ "def", "insert_many", "(", "self", ",", "rows", ",", "chunk_size", "=", "1000", ")", ":", "def", "_process_chunk", "(", "chunk", ")", ":", "self", ".", "table", ".", "insert", "(", ")", ".", "execute", "(", "chunk", ")", "self", ".", "_check_dropped", ...
Add many rows at a time, which is significantly faster than adding them one by one. Per default the rows are processed in chunks of 1000 per commit, unless you specify a different ``chunk_size``. See :py:meth:`insert() <dataset.Table.insert>` for details on the other parameters. ...
[ "Add", "many", "rows", "at", "a", "time", "which", "is", "significantly", "faster", "than", "adding", "them", "one", "by", "one", ".", "Per", "default", "the", "rows", "are", "processed", "in", "chunks", "of", "1000", "per", "commit", "unless", "you", "s...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L246-L270
train
smnorris/pgdata
pgdata/table.py
Table.rename
def rename(self, name): """Rename the table """ sql = """ALTER TABLE {s}.{t} RENAME TO {name} """.format( s=self.schema, t=self.name, name=name ) self.engine.execute(sql) self.table = SQLATable(name, self.metadata, schema=self.schema, autoload=Tr...
python
def rename(self, name): """Rename the table """ sql = """ALTER TABLE {s}.{t} RENAME TO {name} """.format( s=self.schema, t=self.name, name=name ) self.engine.execute(sql) self.table = SQLATable(name, self.metadata, schema=self.schema, autoload=Tr...
[ "def", "rename", "(", "self", ",", "name", ")", ":", "sql", "=", "\"\"\"ALTER TABLE {s}.{t} RENAME TO {name}\n \"\"\"", ".", "format", "(", "s", "=", "self", ".", "schema", ",", "t", "=", "self", ".", "name", ",", "name", "=", "name", ")", "se...
Rename the table
[ "Rename", "the", "table" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L272-L280
train
smnorris/pgdata
pgdata/table.py
Table.find_one
def find_one(self, **kwargs): """ Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None. :: row = table.find_one(country='United States') """ kwargs["_limit"] = 1 iterator = self.find(**kwargs) try: return n...
python
def find_one(self, **kwargs): """ Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None. :: row = table.find_one(country='United States') """ kwargs["_limit"] = 1 iterator = self.find(**kwargs) try: return n...
[ "def", "find_one", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"_limit\"", "]", "=", "1", "iterator", "=", "self", ".", "find", "(", "*", "*", "kwargs", ")", "try", ":", "return", "next", "(", "iterator", ")", "except", "StopIt...
Works just like :py:meth:`find() <dataset.Table.find>` but returns one result, or None. :: row = table.find_one(country='United States')
[ "Works", "just", "like", ":", "py", ":", "meth", ":", "find", "()", "<dataset", ".", "Table", ".", "find", ">", "but", "returns", "one", "result", "or", "None", ".", "::", "row", "=", "table", ".", "find_one", "(", "country", "=", "United", "States",...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L282-L293
train
smnorris/pgdata
pgdata/table.py
Table.find
def find( self, _limit=None, _offset=0, _step=5000, order_by="id", return_count=False, **_filter ): """ Performs a simple search on the table. Simply pass keyword arguments as ``filter``. :: results = table.find(country='Fra...
python
def find( self, _limit=None, _offset=0, _step=5000, order_by="id", return_count=False, **_filter ): """ Performs a simple search on the table. Simply pass keyword arguments as ``filter``. :: results = table.find(country='Fra...
[ "def", "find", "(", "self", ",", "_limit", "=", "None", ",", "_offset", "=", "0", ",", "_step", "=", "5000", ",", "order_by", "=", "\"id\"", ",", "return_count", "=", "False", ",", "*", "*", "_filter", ")", ":", "self", ".", "_check_dropped", "(", ...
Performs a simple search on the table. Simply pass keyword arguments as ``filter``. :: results = table.find(country='France') results = table.find(country='France', year=1980) Using ``_limit``:: # just return the first 10 rows results = table.find(country=...
[ "Performs", "a", "simple", "search", "on", "the", "table", ".", "Simply", "pass", "keyword", "arguments", "as", "filter", ".", "::", "results", "=", "table", ".", "find", "(", "country", "=", "France", ")", "results", "=", "table", ".", "find", "(", "c...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L301-L377
train
smnorris/pgdata
pgdata/__init__.py
connect
def connect(url=None, schema=None, sql_path=None, multiprocessing=False): """Open a new connection to postgres via psycopg2/sqlalchemy """ if url is None: url = os.environ.get("DATABASE_URL") return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing)
python
def connect(url=None, schema=None, sql_path=None, multiprocessing=False): """Open a new connection to postgres via psycopg2/sqlalchemy """ if url is None: url = os.environ.get("DATABASE_URL") return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing)
[ "def", "connect", "(", "url", "=", "None", ",", "schema", "=", "None", ",", "sql_path", "=", "None", ",", "multiprocessing", "=", "False", ")", ":", "if", "url", "is", "None", ":", "url", "=", "os", ".", "environ", ".", "get", "(", "\"DATABASE_URL\""...
Open a new connection to postgres via psycopg2/sqlalchemy
[ "Open", "a", "new", "connection", "to", "postgres", "via", "psycopg2", "/", "sqlalchemy" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/__init__.py#L15-L20
train
smnorris/pgdata
pgdata/__init__.py
create_db
def create_db(url=None): """Create a new database """ if url is None: url = os.environ.get("DATABASE_URL") parsed_url = urlparse(url) db_name = parsed_url.path db_name = db_name.strip("/") db = connect("postgresql://" + parsed_url.netloc) # check that db does not exist q = ""...
python
def create_db(url=None): """Create a new database """ if url is None: url = os.environ.get("DATABASE_URL") parsed_url = urlparse(url) db_name = parsed_url.path db_name = db_name.strip("/") db = connect("postgresql://" + parsed_url.netloc) # check that db does not exist q = ""...
[ "def", "create_db", "(", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "os", ".", "environ", ".", "get", "(", "\"DATABASE_URL\"", ")", "parsed_url", "=", "urlparse", "(", "url", ")", "db_name", "=", "parsed_url", ".", "pat...
Create a new database
[ "Create", "a", "new", "database" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/__init__.py#L23-L44
train
smnorris/pgdata
pgdata/__init__.py
drop_db
def drop_db(url): """Drop specified database """ parsed_url = urlparse(url) db_name = parsed_url.path db_name = db_name.strip("/") db = connect("postgresql://" + parsed_url.netloc) # check that db exists q = """SELECT 1 as exists FROM pg_database WHERE datname = '{d...
python
def drop_db(url): """Drop specified database """ parsed_url = urlparse(url) db_name = parsed_url.path db_name = db_name.strip("/") db = connect("postgresql://" + parsed_url.netloc) # check that db exists q = """SELECT 1 as exists FROM pg_database WHERE datname = '{d...
[ "def", "drop_db", "(", "url", ")", ":", "parsed_url", "=", "urlparse", "(", "url", ")", "db_name", "=", "parsed_url", ".", "path", "db_name", "=", "db_name", ".", "strip", "(", "\"/\"", ")", "db", "=", "connect", "(", "\"postgresql://\"", "+", "parsed_ur...
Drop specified database
[ "Drop", "specified", "database" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/__init__.py#L47-L65
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
shred
def shred(key_name: str, value: t.Any, field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]: """ Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret. :param field_names: a list of key names that can possibl...
python
def shred(key_name: str, value: t.Any, field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]: """ Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret. :param field_names: a list of key names that can possibl...
[ "def", "shred", "(", "key_name", ":", "str", ",", "value", ":", "t", ".", "Any", ",", "field_names", ":", "t", ".", "Iterable", "[", "str", "]", "=", "SHRED_DATA_FIELD_NAMES", ")", "->", "t", ".", "Union", "[", "t", ".", "Any", ",", "str", "]", "...
Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret. :param field_names: a list of key names that can possibly contain sensitive data :param key_name: a key name to check :param value: a value to mask :return: an unchanged value if nothing to hide...
[ "Replaces", "sensitive", "data", "in", "value", "with", "*", "if", "key_name", "contains", "something", "that", "looks", "like", "a", "secret", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L46-L67
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
dot_path
def dot_path(obj: t.Union[t.Dict, object], path: str, default: t.Any = None, separator: str = '.'): """ Provides an access to elements of a mixed dict/object type by a delimiter-separated path. :: class O1: my_dict = {'a': {'b': 1}} class ...
python
def dot_path(obj: t.Union[t.Dict, object], path: str, default: t.Any = None, separator: str = '.'): """ Provides an access to elements of a mixed dict/object type by a delimiter-separated path. :: class O1: my_dict = {'a': {'b': 1}} class ...
[ "def", "dot_path", "(", "obj", ":", "t", ".", "Union", "[", "t", ".", "Dict", ",", "object", "]", ",", "path", ":", "str", ",", "default", ":", "t", ".", "Any", "=", "None", ",", "separator", ":", "str", "=", "'.'", ")", ":", "path_items", "=",...
Provides an access to elements of a mixed dict/object type by a delimiter-separated path. :: class O1: my_dict = {'a': {'b': 1}} class O2: def __init__(self): self.nested = O1() class O3: final = O2() o = O3() assert uti...
[ "Provides", "an", "access", "to", "elements", "of", "a", "mixed", "dict", "/", "object", "type", "by", "a", "delimiter", "-", "separated", "path", ".", "::" ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L97-L140
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
dotkey
def dotkey(obj: dict, path: str, default=None, separator='.'): """ Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpath.util.get``. :param obj: dict like ``{'some': {'value': 3}}`` :param path: ``'some.value'`` :param separator: ``'.'`` or ``'/'`` or what...
python
def dotkey(obj: dict, path: str, default=None, separator='.'): """ Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpath.util.get``. :param obj: dict like ``{'some': {'value': 3}}`` :param path: ``'some.value'`` :param separator: ``'.'`` or ``'/'`` or what...
[ "def", "dotkey", "(", "obj", ":", "dict", ",", "path", ":", "str", ",", "default", "=", "None", ",", "separator", "=", "'.'", ")", ":", "try", ":", "return", "get", "(", "obj", ",", "path", ",", "separator", "=", "separator", ")", "except", "KeyErr...
Provides an interface to traverse nested dict values by dot-separated paths. Wrapper for ``dpath.util.get``. :param obj: dict like ``{'some': {'value': 3}}`` :param path: ``'some.value'`` :param separator: ``'.'`` or ``'/'`` or whatever :param default: default for KeyError :return: dict value or de...
[ "Provides", "an", "interface", "to", "traverse", "nested", "dict", "values", "by", "dot", "-", "separated", "paths", ".", "Wrapper", "for", "dpath", ".", "util", ".", "get", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L143-L156
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
_materialize_dict
def _materialize_dict(bundle: dict, separator: str = '.') -> t.Generator[t.Tuple[str, t.Any], None, None]: """ Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``. :param bundle: a dict to traverse :param separator: build paths with a given separator :return: a gen...
python
def _materialize_dict(bundle: dict, separator: str = '.') -> t.Generator[t.Tuple[str, t.Any], None, None]: """ Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``. :param bundle: a dict to traverse :param separator: build paths with a given separator :return: a gen...
[ "def", "_materialize_dict", "(", "bundle", ":", "dict", ",", "separator", ":", "str", "=", "'.'", ")", "->", "t", ".", "Generator", "[", "t", ".", "Tuple", "[", "str", ",", "t", ".", "Any", "]", ",", "None", ",", "None", "]", ":", "for", "path_pr...
Traverses and transforms a given dict ``bundle`` into tuples of ``(key_path, value)``. :param bundle: a dict to traverse :param separator: build paths with a given separator :return: a generator of tuples ``(materialized_path, value)`` Example: >>> list(_materialize_dict({'test': {'path': 1}, 'key...
[ "Traverses", "and", "transforms", "a", "given", "dict", "bundle", "into", "tuples", "of", "(", "key_path", "value", ")", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L159-L177
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
materialize_dict
def materialize_dict(bundle: dict, separator: str = '.') -> t.List[t.Tuple[str, t.Any]]: """ Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ``('path.to.value', <value>)``. Output is ordered by depth: the deepest element first. :param bundle: a dic...
python
def materialize_dict(bundle: dict, separator: str = '.') -> t.List[t.Tuple[str, t.Any]]: """ Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ``('path.to.value', <value>)``. Output is ordered by depth: the deepest element first. :param bundle: a dic...
[ "def", "materialize_dict", "(", "bundle", ":", "dict", ",", "separator", ":", "str", "=", "'.'", ")", "->", "t", ".", "List", "[", "t", ".", "Tuple", "[", "str", ",", "t", ".", "Any", "]", "]", ":", "def", "_matkeysort", "(", "tup", ":", "t", "...
Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ``('path.to.value', <value>)``. Output is ordered by depth: the deepest element first. :param bundle: a dict to materialize :param separator: build paths with a given separator :return: a depth descen...
[ "Transforms", "a", "given", "bundle", "into", "a", "*", "sorted", "*", "list", "of", "tuples", "with", "materialized", "value", "paths", "and", "values", ":", "(", "path", ".", "to", ".", "value", "<value", ">", ")", ".", "Output", "is", "ordered", "by...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L180-L220
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
mp_serialize_dict
def mp_serialize_dict( bundle: dict, separator: str = '.', serialize: t.Optional[t.Callable] = dump_yaml, value_prefix: str = '::YAML::\n') -> t.List[t.Tuple[str, bytes]]: """ Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ...
python
def mp_serialize_dict( bundle: dict, separator: str = '.', serialize: t.Optional[t.Callable] = dump_yaml, value_prefix: str = '::YAML::\n') -> t.List[t.Tuple[str, bytes]]: """ Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ...
[ "def", "mp_serialize_dict", "(", "bundle", ":", "dict", ",", "separator", ":", "str", "=", "'.'", ",", "serialize", ":", "t", ".", "Optional", "[", "t", ".", "Callable", "]", "=", "dump_yaml", ",", "value_prefix", ":", "str", "=", "'::YAML::\\n'", ")", ...
Transforms a given ``bundle`` into a *sorted* list of tuples with materialized value paths and values: ``('path.to.value', b'<some>')``. If the ``<some>`` value is not an instance of a basic type, it's serialized with ``serialize`` callback. If this value is an empty string, it's serialized anyway to enforce co...
[ "Transforms", "a", "given", "bundle", "into", "a", "*", "sorted", "*", "list", "of", "tuples", "with", "materialized", "value", "paths", "and", "values", ":", "(", "path", ".", "to", ".", "value", "b", "<some", ">", ")", ".", "If", "the", "<some", ">...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L223-L294
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
wf
def wf(raw_str: str, flush: bool = True, prevent_completion_polluting: bool = True, stream: t.TextIO = sys.stdout): """ Writes a given ``raw_str`` into a ``stream``. Ignores output if ``prevent_completion_polluting`` is set and there's no extra ``sys.argv`` arguments present (a bash com...
python
def wf(raw_str: str, flush: bool = True, prevent_completion_polluting: bool = True, stream: t.TextIO = sys.stdout): """ Writes a given ``raw_str`` into a ``stream``. Ignores output if ``prevent_completion_polluting`` is set and there's no extra ``sys.argv`` arguments present (a bash com...
[ "def", "wf", "(", "raw_str", ":", "str", ",", "flush", ":", "bool", "=", "True", ",", "prevent_completion_polluting", ":", "bool", "=", "True", ",", "stream", ":", "t", ".", "TextIO", "=", "sys", ".", "stdout", ")", ":", "if", "prevent_completion_polluti...
Writes a given ``raw_str`` into a ``stream``. Ignores output if ``prevent_completion_polluting`` is set and there's no extra ``sys.argv`` arguments present (a bash completion issue). :param raw_str: a raw string to print :param flush: execute ``flush()`` :param prevent_completion_polluting: don't write...
[ "Writes", "a", "given", "raw_str", "into", "a", "stream", ".", "Ignores", "output", "if", "prevent_completion_polluting", "is", "set", "and", "there", "s", "no", "extra", "sys", ".", "argv", "arguments", "present", "(", "a", "bash", "completion", "issue", ")...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L297-L315
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
coerce_str_to_bool
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool: """ Converts a given string ``val`` into a boolean. :param val: any string representation of boolean :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object :return: ``True`` if...
python
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool: """ Converts a given string ``val`` into a boolean. :param val: any string representation of boolean :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object :return: ``True`` if...
[ "def", "coerce_str_to_bool", "(", "val", ":", "t", ".", "Union", "[", "str", ",", "int", ",", "bool", ",", "None", "]", ",", "strict", ":", "bool", "=", "False", ")", "->", "bool", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val",...
Converts a given string ``val`` into a boolean. :param val: any string representation of boolean :param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object :return: ``True`` if ``val`` is thruthy, ``False`` otherwise. :raises ValueError: if ``strict`` specified and ``val``...
[ "Converts", "a", "given", "string", "val", "into", "a", "boolean", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L318-L340
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
env_bool_flag
def env_bool_flag(flag_name: str, strict: bool = False, env: t.Optional[t.Dict[str, str]] = None) -> bool: """ Converts an environment variable into a boolean. Empty string (presence in env) is treated as ``True``. :param flag_name: an environment variable name :param strict: raise ``ValueError`` if a ...
python
def env_bool_flag(flag_name: str, strict: bool = False, env: t.Optional[t.Dict[str, str]] = None) -> bool: """ Converts an environment variable into a boolean. Empty string (presence in env) is treated as ``True``. :param flag_name: an environment variable name :param strict: raise ``ValueError`` if a ...
[ "def", "env_bool_flag", "(", "flag_name", ":", "str", ",", "strict", ":", "bool", "=", "False", ",", "env", ":", "t", ".", "Optional", "[", "t", ".", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "bool", ":", "env", "=", "en...
Converts an environment variable into a boolean. Empty string (presence in env) is treated as ``True``. :param flag_name: an environment variable name :param strict: raise ``ValueError`` if a ``flag_name`` value connot be coerced into a boolean in obvious way :param env: a dict with environment variables, ...
[ "Converts", "an", "environment", "variable", "into", "a", "boolean", ".", "Empty", "string", "(", "presence", "in", "env", ")", "is", "treated", "as", "True", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L343-L361
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
run_env_once
def run_env_once(f: t.Callable) -> t.Callable: """ A decorator to prevent ``manage.py`` from running code twice for everything. (https://stackoverflow.com/questions/16546652/why-does-django-run-everything-twice) :param f: function or method to decorate :return: callable """ @wraps(f) d...
python
def run_env_once(f: t.Callable) -> t.Callable: """ A decorator to prevent ``manage.py`` from running code twice for everything. (https://stackoverflow.com/questions/16546652/why-does-django-run-everything-twice) :param f: function or method to decorate :return: callable """ @wraps(f) d...
[ "def", "run_env_once", "(", "f", ":", "t", ".", "Callable", ")", "->", "t", ".", "Callable", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "has_run", "=", "os", ".", "environ", ".", "ge...
A decorator to prevent ``manage.py`` from running code twice for everything. (https://stackoverflow.com/questions/16546652/why-does-django-run-everything-twice) :param f: function or method to decorate :return: callable
[ "A", "decorator", "to", "prevent", "manage", ".", "py", "from", "running", "code", "twice", "for", "everything", ".", "(", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "16546652", "/", "why", "-", "does", "-", "django", "-", ...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L364-L382
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
is_dockerized
def is_dockerized(flag_name: str = 'DOCKERIZED', strict: bool = False): """ Reads env ``DOCKERIZED`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``DOCKERIZED`...
python
def is_dockerized(flag_name: str = 'DOCKERIZED', strict: bool = False): """ Reads env ``DOCKERIZED`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``DOCKERIZED`...
[ "def", "is_dockerized", "(", "flag_name", ":", "str", "=", "'DOCKERIZED'", ",", "strict", ":", "bool", "=", "False", ")", ":", "return", "env_bool_flag", "(", "flag_name", ",", "strict", "=", "strict", ")" ]
Reads env ``DOCKERIZED`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``DOCKERIZED`` env, ``False`` otherwise
[ "Reads", "env", "DOCKERIZED", "variable", "as", "a", "boolean", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L385-L393
train
night-crawler/django-docker-helpers
django_docker_helpers/utils.py
is_production
def is_production(flag_name: str = 'PRODUCTION', strict: bool = False): """ Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`...
python
def is_production(flag_name: str = 'PRODUCTION', strict: bool = False): """ Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`...
[ "def", "is_production", "(", "flag_name", ":", "str", "=", "'PRODUCTION'", ",", "strict", ":", "bool", "=", "False", ")", ":", "return", "env_bool_flag", "(", "flag_name", ",", "strict", "=", "strict", ")" ]
Reads env ``PRODUCTION`` variable as a boolean. :param flag_name: environment variable name :param strict: raise a ``ValueError`` if variable does not look like a normal boolean :return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise
[ "Reads", "env", "PRODUCTION", "variable", "as", "a", "boolean", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/utils.py#L396-L404
train
lingfeiwang/findr-python
findr/examples.py
load_geuvadis_data
def load_geuvadis_data(): """This function loads downsampled data files from the Geuvadis study (Lappalainen, T. et al. Transcriptome and genome sequencing uncovers functional variation in humans. Nature 501, 506-511 (2013)), including expression levels of 10 miRNAs and 3000 genes for 360 European individuals. Among t...
python
def load_geuvadis_data(): """This function loads downsampled data files from the Geuvadis study (Lappalainen, T. et al. Transcriptome and genome sequencing uncovers functional variation in humans. Nature 501, 506-511 (2013)), including expression levels of 10 miRNAs and 3000 genes for 360 European individuals. Among t...
[ "def", "load_geuvadis_data", "(", ")", ":", "from", "os", ".", "path", "import", "dirname", ",", "join", "from", ".", "auto", "import", "gtype_np", ",", "ftype_np", "import", "numpy", "as", "np", "def", "getdata", "(", "name", ",", "dtype", ",", "shape",...
This function loads downsampled data files from the Geuvadis study (Lappalainen, T. et al. Transcriptome and genome sequencing uncovers functional variation in humans. Nature 501, 506-511 (2013)), including expression levels of 10 miRNAs and 3000 genes for 360 European individuals. Among them, all miRNAs and 1000 genes...
[ "This", "function", "loads", "downsampled", "data", "files", "from", "the", "Geuvadis", "study", "(", "Lappalainen", "T", ".", "et", "al", ".", "Transcriptome", "and", "genome", "sequencing", "uncovers", "functional", "variation", "in", "humans", ".", "Nature", ...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/examples.py#L20-L49
train
lingfeiwang/findr-python
findr/examples.py
runcode
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
python
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
[ "def", "runcode", "(", "code", ")", ":", "for", "line", "in", "code", ":", "print", "(", "'# '", "+", "line", ")", "exec", "(", "line", ",", "globals", "(", ")", ")", "print", "(", "'# return ans'", ")", "return", "ans" ]
Run the given code line by line with printing, as list of lines, and return variable 'ans'.
[ "Run", "the", "given", "code", "line", "by", "line", "with", "printing", "as", "list", "of", "lines", "and", "return", "variable", "ans", "." ]
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/examples.py#L51-L57
train
metapensiero/metapensiero.signal
src/metapensiero/signal/utils.py
signal
def signal(*args, **kwargs): from .core import Signal """A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signa...
python
def signal(*args, **kwargs): from .core import Signal """A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signa...
[ "def", "signal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "core", "import", "Signal", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "callable", "(", "args", "[", "0", "]",...
A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signal(SignalOptions.EXEC_CONCURRENT) def validation_function(ar...
[ "A", "signal", "decorator", "designed", "to", "work", "both", "in", "the", "simpler", "way", "like", ":" ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/utils.py#L248-L274
train
metapensiero/metapensiero.signal
src/metapensiero/signal/utils.py
Executor.exec_all_endpoints
def exec_all_endpoints(self, *args, **kwargs): """Execute each passed endpoint and collect the results. If a result is anoter `MultipleResults` it will extend the results with those contained therein. If the result is `NoResult`, skip the addition.""" results = [] for handler in ...
python
def exec_all_endpoints(self, *args, **kwargs): """Execute each passed endpoint and collect the results. If a result is anoter `MultipleResults` it will extend the results with those contained therein. If the result is `NoResult`, skip the addition.""" results = [] for handler in ...
[ "def", "exec_all_endpoints", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "results", "=", "[", "]", "for", "handler", "in", "self", ".", "endpoints", ":", "if", "isinstance", "(", "handler", ",", "weakref", ".", "ref", ")", ":", ...
Execute each passed endpoint and collect the results. If a result is anoter `MultipleResults` it will extend the results with those contained therein. If the result is `NoResult`, skip the addition.
[ "Execute", "each", "passed", "endpoint", "and", "collect", "the", "results", ".", "If", "a", "result", "is", "anoter", "MultipleResults", "it", "will", "extend", "the", "results", "with", "those", "contained", "therein", ".", "If", "the", "result", "is", "No...
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/utils.py#L70-L90
train
metapensiero/metapensiero.signal
src/metapensiero/signal/utils.py
Executor.run
def run(self, *args, **kwargs): """Call all the registered handlers with the arguments passed. If this signal is a class member, call also the handlers registered at class-definition time. If an external publish function is supplied, call it with the provided arguments. :returns...
python
def run(self, *args, **kwargs): """Call all the registered handlers with the arguments passed. If this signal is a class member, call also the handlers registered at class-definition time. If an external publish function is supplied, call it with the provided arguments. :returns...
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "fvalidation", "is", "not", "None", ":", "try", ":", "if", "self", ".", "fvalidation", "(", "*", "args", ",", "*", "*", "kwargs", ")", "is", "Fal...
Call all the registered handlers with the arguments passed. If this signal is a class member, call also the handlers registered at class-definition time. If an external publish function is supplied, call it with the provided arguments. :returns: an instance of `~.utils.MultipleResults`
[ "Call", "all", "the", "registered", "handlers", "with", "the", "arguments", "passed", ".", "If", "this", "signal", "is", "a", "class", "member", "call", "also", "the", "handlers", "registered", "at", "class", "-", "definition", "time", ".", "If", "an", "ex...
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/utils.py#L92-L129
train
jonhadfield/creds
lib/creds/constants.py
login_defs
def login_defs(): """Discover the minimum and maximum UID number.""" uid_min = None uid_max = None login_defs_path = '/etc/login.defs' if os.path.exists(login_defs_path): with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as log_defs_file: login_data = log_defs...
python
def login_defs(): """Discover the minimum and maximum UID number.""" uid_min = None uid_max = None login_defs_path = '/etc/login.defs' if os.path.exists(login_defs_path): with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as log_defs_file: login_data = log_defs...
[ "def", "login_defs", "(", ")", ":", "uid_min", "=", "None", "uid_max", "=", "None", "login_defs_path", "=", "'/etc/login.defs'", "if", "os", ".", "path", ".", "exists", "(", "login_defs_path", ")", ":", "with", "io", ".", "open", "(", "text_type", "(", "...
Discover the minimum and maximum UID number.
[ "Discover", "the", "minimum", "and", "maximum", "UID", "number", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/constants.py#L33-L54
train
night-crawler/django-docker-helpers
django_docker_helpers/files.py
collect_static
def collect_static() -> bool: """ Runs Django ``collectstatic`` command in silent mode. :return: always ``True`` """ from django.core.management import execute_from_command_line # from django.conf import settings # if not os.listdir(settings.STATIC_ROOT): wf('Collecting static files... ...
python
def collect_static() -> bool: """ Runs Django ``collectstatic`` command in silent mode. :return: always ``True`` """ from django.core.management import execute_from_command_line # from django.conf import settings # if not os.listdir(settings.STATIC_ROOT): wf('Collecting static files... ...
[ "def", "collect_static", "(", ")", "->", "bool", ":", "from", "django", ".", "core", ".", "management", "import", "execute_from_command_line", "# from django.conf import settings", "# if not os.listdir(settings.STATIC_ROOT):", "wf", "(", "'Collecting static files... '", ",", ...
Runs Django ``collectstatic`` command in silent mode. :return: always ``True``
[ "Runs", "Django", "collectstatic", "command", "in", "silent", "mode", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/files.py#L5-L17
train
night-crawler/django-docker-helpers
django_docker_helpers/config/backends/redis_parser.py
RedisParser.inner_parser
def inner_parser(self) -> BaseParser: """ Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain ...
python
def inner_parser(self) -> BaseParser: """ Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain ...
[ "def", "inner_parser", "(", "self", ")", "->", "BaseParser", ":", "if", "self", ".", "_inner_parser", "is", "not", "None", ":", "return", "self", ".", "_inner_parser", "config", "=", "self", ".", "client", ".", "get", "(", "self", ".", "endpoint", ")", ...
Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config
[ "Prepares", "inner", "config", "parser", "for", "config", "stored", "at", "endpoint", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/redis_parser.py#L72-L94
train
jonhadfield/creds
lib/creds/users.py
generate_add_user_command
def generate_add_user_command(proposed_user=None, manage_home=None): """Generate command to add a user. args: proposed_user (User): User manage_home: bool returns: list: The command string split into shell-like syntax """ command = None if get_platform() in ('Linux', 'O...
python
def generate_add_user_command(proposed_user=None, manage_home=None): """Generate command to add a user. args: proposed_user (User): User manage_home: bool returns: list: The command string split into shell-like syntax """ command = None if get_platform() in ('Linux', 'O...
[ "def", "generate_add_user_command", "(", "proposed_user", "=", "None", ",", "manage_home", "=", "None", ")", ":", "command", "=", "None", "if", "get_platform", "(", ")", "in", "(", "'Linux'", ",", "'OpenBSD'", ")", ":", "command", "=", "'{0} {1}'", ".", "f...
Generate command to add a user. args: proposed_user (User): User manage_home: bool returns: list: The command string split into shell-like syntax
[ "Generate", "command", "to", "add", "a", "user", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L245-L291
train
jonhadfield/creds
lib/creds/users.py
generate_modify_user_command
def generate_modify_user_command(task=None, manage_home=None): """Generate command to modify existing user to become the proposed user. args: task (dict): A proposed user and the differences between it and the existing user returns: list: The command string split into shell-like syntax ...
python
def generate_modify_user_command(task=None, manage_home=None): """Generate command to modify existing user to become the proposed user. args: task (dict): A proposed user and the differences between it and the existing user returns: list: The command string split into shell-like syntax ...
[ "def", "generate_modify_user_command", "(", "task", "=", "None", ",", "manage_home", "=", "None", ")", ":", "name", "=", "task", "[", "'proposed_user'", "]", ".", "name", "comparison_result", "=", "task", "[", "'user_comparison'", "]", "[", "'result'", "]", ...
Generate command to modify existing user to become the proposed user. args: task (dict): A proposed user and the differences between it and the existing user returns: list: The command string split into shell-like syntax
[ "Generate", "command", "to", "modify", "existing", "user", "to", "become", "the", "proposed", "user", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L294-L333
train
jonhadfield/creds
lib/creds/users.py
generate_delete_user_command
def generate_delete_user_command(username=None, manage_home=None): """Generate command to delete a user. args: username (str): user name manage_home (bool): manage home directory returns: list: The user delete command string split into shell-like syntax """ command = None ...
python
def generate_delete_user_command(username=None, manage_home=None): """Generate command to delete a user. args: username (str): user name manage_home (bool): manage home directory returns: list: The user delete command string split into shell-like syntax """ command = None ...
[ "def", "generate_delete_user_command", "(", "username", "=", "None", ",", "manage_home", "=", "None", ")", ":", "command", "=", "None", "remove_home", "=", "'-r'", "if", "manage_home", "else", "''", "if", "get_platform", "(", ")", "in", "(", "'Linux'", ",", ...
Generate command to delete a user. args: username (str): user name manage_home (bool): manage home directory returns: list: The user delete command string split into shell-like syntax
[ "Generate", "command", "to", "delete", "a", "user", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L336-L354
train
jonhadfield/creds
lib/creds/users.py
compare_user
def compare_user(passed_user=None, user_list=None): """Check if supplied User instance exists in supplied Users list and, if so, return the differences. args: passed_user (User): the user instance to check for differences user_list (Users): the Users instance containing a list of Users instance...
python
def compare_user(passed_user=None, user_list=None): """Check if supplied User instance exists in supplied Users list and, if so, return the differences. args: passed_user (User): the user instance to check for differences user_list (Users): the Users instance containing a list of Users instance...
[ "def", "compare_user", "(", "passed_user", "=", "None", ",", "user_list", "=", "None", ")", ":", "# Check if user exists", "returned", "=", "user_list", ".", "describe_users", "(", "users_filter", "=", "dict", "(", "name", "=", "passed_user", ".", "name", ")",...
Check if supplied User instance exists in supplied Users list and, if so, return the differences. args: passed_user (User): the user instance to check for differences user_list (Users): the Users instance containing a list of Users instances returns: dict: Details of the matching user ...
[ "Check", "if", "supplied", "User", "instance", "exists", "in", "supplied", "Users", "list", "and", "if", "so", "return", "the", "differences", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L370-L428
train
jonhadfield/creds
lib/creds/users.py
User.gecos
def gecos(self): """Force double quoted gecos. returns: str: The double quoted gecos. """ if not self._gecos: return None if self._gecos.startswith(text_type('\'')) and self._gecos.endswith(text_type('\'')): self._gecos = '\"{0}\"'.format(self...
python
def gecos(self): """Force double quoted gecos. returns: str: The double quoted gecos. """ if not self._gecos: return None if self._gecos.startswith(text_type('\'')) and self._gecos.endswith(text_type('\'')): self._gecos = '\"{0}\"'.format(self...
[ "def", "gecos", "(", "self", ")", ":", "if", "not", "self", ".", "_gecos", ":", "return", "None", "if", "self", ".", "_gecos", ".", "startswith", "(", "text_type", "(", "'\\''", ")", ")", "and", "self", ".", "_gecos", ".", "endswith", "(", "text_type...
Force double quoted gecos. returns: str: The double quoted gecos.
[ "Force", "double", "quoted", "gecos", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L49-L63
train
jonhadfield/creds
lib/creds/users.py
User.to_dict
def to_dict(self): """ Return the user as a dict. """ public_keys = [public_key.b64encoded for public_key in self.public_keys] return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos, home_dir=self.home_dir, shell=self.shell, public_keys=p...
python
def to_dict(self): """ Return the user as a dict. """ public_keys = [public_key.b64encoded for public_key in self.public_keys] return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos, home_dir=self.home_dir, shell=self.shell, public_keys=p...
[ "def", "to_dict", "(", "self", ")", ":", "public_keys", "=", "[", "public_key", ".", "b64encoded", "for", "public_key", "in", "self", ".", "public_keys", "]", "return", "dict", "(", "name", "=", "self", ".", "name", ",", "passwd", "=", "self", ".", "pa...
Return the user as a dict.
[ "Return", "the", "user", "as", "a", "dict", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L71-L75
train
jonhadfield/creds
lib/creds/users.py
Users.insert
def insert(self, index, value): """Insert an instance of User into the collection.""" self.check(value) self._user_list.insert(index, value)
python
def insert(self, index, value): """Insert an instance of User into the collection.""" self.check(value) self._user_list.insert(index, value)
[ "def", "insert", "(", "self", ",", "index", ",", "value", ")", ":", "self", ".", "check", "(", "value", ")", "self", ".", "_user_list", ".", "insert", "(", "index", ",", "value", ")" ]
Insert an instance of User into the collection.
[ "Insert", "an", "instance", "of", "User", "into", "the", "collection", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L117-L120
train
jonhadfield/creds
lib/creds/users.py
Users.remove
def remove(self, username=None): """Remove User instance based on supplied user name.""" self._user_list = [user for user in self._user_list if user.name != username]
python
def remove(self, username=None): """Remove User instance based on supplied user name.""" self._user_list = [user for user in self._user_list if user.name != username]
[ "def", "remove", "(", "self", ",", "username", "=", "None", ")", ":", "self", ".", "_user_list", "=", "[", "user", "for", "user", "in", "self", ".", "_user_list", "if", "user", ".", "name", "!=", "username", "]" ]
Remove User instance based on supplied user name.
[ "Remove", "User", "instance", "based", "on", "supplied", "user", "name", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L134-L136
train
jonhadfield/creds
lib/creds/users.py
Users.describe_users
def describe_users(self, users_filter=None): """Return a list of users matching a filter (if provided).""" user_list = Users(oktypes=User) for user in self._user_list: if users_filter and (users_filter.get('name') == user.name or users_filter.get('uid') == user.uid): ...
python
def describe_users(self, users_filter=None): """Return a list of users matching a filter (if provided).""" user_list = Users(oktypes=User) for user in self._user_list: if users_filter and (users_filter.get('name') == user.name or users_filter.get('uid') == user.uid): ...
[ "def", "describe_users", "(", "self", ",", "users_filter", "=", "None", ")", ":", "user_list", "=", "Users", "(", "oktypes", "=", "User", ")", "for", "user", "in", "self", ".", "_user_list", ":", "if", "users_filter", "and", "(", "users_filter", ".", "ge...
Return a list of users matching a filter (if provided).
[ "Return", "a", "list", "of", "users", "matching", "a", "filter", "(", "if", "provided", ")", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L138-L144
train
jonhadfield/creds
lib/creds/users.py
Users.from_yaml
def from_yaml(cls, file_path=None): """Create collection from a YAML file.""" try: import yaml except ImportError: # pragma: no cover yaml = None if not yaml: import sys sys.exit('PyYAML is not installed, but is required in order to parse ...
python
def from_yaml(cls, file_path=None): """Create collection from a YAML file.""" try: import yaml except ImportError: # pragma: no cover yaml = None if not yaml: import sys sys.exit('PyYAML is not installed, but is required in order to parse ...
[ "def", "from_yaml", "(", "cls", ",", "file_path", "=", "None", ")", ":", "try", ":", "import", "yaml", "except", "ImportError", ":", "# pragma: no cover", "yaml", "=", "None", "if", "not", "yaml", ":", "import", "sys", "sys", ".", "exit", "(", "'PyYAML i...
Create collection from a YAML file.
[ "Create", "collection", "from", "a", "YAML", "file", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L152-L169
train
jonhadfield/creds
lib/creds/users.py
Users.from_json
def from_json(cls, file_path=None): """Create collection from a JSON file.""" with io.open(file_path, encoding=text_type('utf-8')) as stream: try: users_json = json.load(stream) except ValueError: raise ValueError('No JSON object could be decoded')...
python
def from_json(cls, file_path=None): """Create collection from a JSON file.""" with io.open(file_path, encoding=text_type('utf-8')) as stream: try: users_json = json.load(stream) except ValueError: raise ValueError('No JSON object could be decoded')...
[ "def", "from_json", "(", "cls", ",", "file_path", "=", "None", ")", ":", "with", "io", ".", "open", "(", "file_path", ",", "encoding", "=", "text_type", "(", "'utf-8'", ")", ")", "as", "stream", ":", "try", ":", "users_json", "=", "json", ".", "load"...
Create collection from a JSON file.
[ "Create", "collection", "from", "a", "JSON", "file", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L172-L179
train
jonhadfield/creds
lib/creds/users.py
Users.from_passwd
def from_passwd(uid_min=None, uid_max=None): """Create collection from locally discovered data, e.g. /etc/passwd.""" import pwd users = Users(oktypes=User) passwd_list = pwd.getpwall() if not uid_min: uid_min = UID_MIN if not uid_max: uid_max = UID...
python
def from_passwd(uid_min=None, uid_max=None): """Create collection from locally discovered data, e.g. /etc/passwd.""" import pwd users = Users(oktypes=User) passwd_list = pwd.getpwall() if not uid_min: uid_min = UID_MIN if not uid_max: uid_max = UID...
[ "def", "from_passwd", "(", "uid_min", "=", "None", ",", "uid_max", "=", "None", ")", ":", "import", "pwd", "users", "=", "Users", "(", "oktypes", "=", "User", ")", "passwd_list", "=", "pwd", ".", "getpwall", "(", ")", "if", "not", "uid_min", ":", "ui...
Create collection from locally discovered data, e.g. /etc/passwd.
[ "Create", "collection", "from", "locally", "discovered", "data", "e", ".", "g", ".", "/", "etc", "/", "passwd", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L182-L205
train
jonhadfield/creds
lib/creds/users.py
Users.construct_user_list
def construct_user_list(raw_users=None): """Construct a list of User objects from a list of dicts.""" users = Users(oktypes=User) for user_dict in raw_users: public_keys = None if user_dict.get('public_keys'): public_keys = [PublicKey(b64encoded=x, raw=Non...
python
def construct_user_list(raw_users=None): """Construct a list of User objects from a list of dicts.""" users = Users(oktypes=User) for user_dict in raw_users: public_keys = None if user_dict.get('public_keys'): public_keys = [PublicKey(b64encoded=x, raw=Non...
[ "def", "construct_user_list", "(", "raw_users", "=", "None", ")", ":", "users", "=", "Users", "(", "oktypes", "=", "User", ")", "for", "user_dict", "in", "raw_users", ":", "public_keys", "=", "None", "if", "user_dict", ".", "get", "(", "'public_keys'", ")"...
Construct a list of User objects from a list of dicts.
[ "Construct", "a", "list", "of", "User", "objects", "from", "a", "list", "of", "dicts", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L208-L225
train
jonhadfield/creds
lib/creds/users.py
Users.to_dict
def to_dict(self): """ Return a dict of the users. """ users = dict(users=list()) for user in self: users['users'].append(user.to_dict()) return users
python
def to_dict(self): """ Return a dict of the users. """ users = dict(users=list()) for user in self: users['users'].append(user.to_dict()) return users
[ "def", "to_dict", "(", "self", ")", ":", "users", "=", "dict", "(", "users", "=", "list", "(", ")", ")", "for", "user", "in", "self", ":", "users", "[", "'users'", "]", ".", "append", "(", "user", ".", "to_dict", "(", ")", ")", "return", "users" ...
Return a dict of the users.
[ "Return", "a", "dict", "of", "the", "users", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L227-L232
train
jonhadfield/creds
lib/creds/users.py
Users.export
def export(self, file_path=None, export_format=None): """ Write the users to a file. """ with io.open(file_path, mode='w', encoding="utf-8") as export_file: if export_format == 'yaml': import yaml yaml.safe_dump(self.to_dict(), export_file, default_flow_style=...
python
def export(self, file_path=None, export_format=None): """ Write the users to a file. """ with io.open(file_path, mode='w', encoding="utf-8") as export_file: if export_format == 'yaml': import yaml yaml.safe_dump(self.to_dict(), export_file, default_flow_style=...
[ "def", "export", "(", "self", ",", "file_path", "=", "None", ",", "export_format", "=", "None", ")", ":", "with", "io", ".", "open", "(", "file_path", ",", "mode", "=", "'w'", ",", "encoding", "=", "\"utf-8\"", ")", "as", "export_file", ":", "if", "e...
Write the users to a file.
[ "Write", "the", "users", "to", "a", "file", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/users.py#L234-L242
train
letuananh/chirptext
chirptext/texttaglib.py
read
def read(path, mode='tsv'): ''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read() ''' if mode == 'tsv': return TxtReader.from_path(path).read() elif mode == 'json': return read_jso...
python
def read(path, mode='tsv'): ''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read() ''' if mode == 'tsv': return TxtReader.from_path(path).read() elif mode == 'json': return read_jso...
[ "def", "read", "(", "path", ",", "mode", "=", "'tsv'", ")", ":", "if", "mode", "==", "'tsv'", ":", "return", "TxtReader", ".", "from_path", "(", "path", ")", ".", "read", "(", ")", "elif", "mode", "==", "'json'", ":", "return", "read_json", "(", "p...
Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt) E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read()
[ "Helper", "function", "to", "read", "Document", "in", "TTL", "-", "TXT", "format", "(", "i", ".", "e", ".", "$", "{", "docname", "}", "_", "*", ".", "txt", ")", "E", ".", "g", ".", "read", "(", "~", "/", "data", "/", "myfile", ")", "is", "the...
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L936-L945
train
letuananh/chirptext
chirptext/texttaglib.py
write
def write(path, doc, mode=MODE_TSV, **kwargs): ''' Helper function to write doc to TTL-TXT format ''' if mode == MODE_TSV: with TxtWriter.from_path(path) as writer: writer.write_doc(doc) elif mode == MODE_JSON: write_json(path, doc, **kwargs)
python
def write(path, doc, mode=MODE_TSV, **kwargs): ''' Helper function to write doc to TTL-TXT format ''' if mode == MODE_TSV: with TxtWriter.from_path(path) as writer: writer.write_doc(doc) elif mode == MODE_JSON: write_json(path, doc, **kwargs)
[ "def", "write", "(", "path", ",", "doc", ",", "mode", "=", "MODE_TSV", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "==", "MODE_TSV", ":", "with", "TxtWriter", ".", "from_path", "(", "path", ")", "as", "writer", ":", "writer", ".", "write_doc", ...
Helper function to write doc to TTL-TXT format
[ "Helper", "function", "to", "write", "doc", "to", "TTL", "-", "TXT", "format" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L948-L954
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.tcmap
def tcmap(self): ''' Create a tokens-concepts map ''' tcmap = dd(list) for concept in self.__concept_map.values(): for w in concept.tokens: tcmap[w].append(concept) return tcmap
python
def tcmap(self): ''' Create a tokens-concepts map ''' tcmap = dd(list) for concept in self.__concept_map.values(): for w in concept.tokens: tcmap[w].append(concept) return tcmap
[ "def", "tcmap", "(", "self", ")", ":", "tcmap", "=", "dd", "(", "list", ")", "for", "concept", "in", "self", ".", "__concept_map", ".", "values", "(", ")", ":", "for", "w", "in", "concept", ".", "tokens", ":", "tcmap", "[", "w", "]", ".", "append...
Create a tokens-concepts map
[ "Create", "a", "tokens", "-", "concepts", "map" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L195-L201
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.msw
def msw(self): ''' Return a generator of tokens with more than one sense. ''' return (t for t, c in self.tcmap().items() if len(c) > 1)
python
def msw(self): ''' Return a generator of tokens with more than one sense. ''' return (t for t, c in self.tcmap().items() if len(c) > 1)
[ "def", "msw", "(", "self", ")", ":", "return", "(", "t", "for", "t", ",", "c", "in", "self", ".", "tcmap", "(", ")", ".", "items", "(", ")", "if", "len", "(", "c", ")", ">", "1", ")" ]
Return a generator of tokens with more than one sense.
[ "Return", "a", "generator", "of", "tokens", "with", "more", "than", "one", "sense", "." ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L207-L209
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.surface
def surface(self, tag): ''' Get surface string that is associated with a tag object ''' if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0: return self.text[tag.cfrom:tag.cto] else: return ''
python
def surface(self, tag): ''' Get surface string that is associated with a tag object ''' if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0: return self.text[tag.cfrom:tag.cto] else: return ''
[ "def", "surface", "(", "self", ",", "tag", ")", ":", "if", "tag", ".", "cfrom", "is", "not", "None", "and", "tag", ".", "cto", "is", "not", "None", "and", "tag", ".", "cfrom", ">=", "0", "and", "tag", ".", "cto", ">=", "0", ":", "return", "self...
Get surface string that is associated with a tag object
[ "Get", "surface", "string", "that", "is", "associated", "with", "a", "tag", "object" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L211-L216
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.new_tag
def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs): ''' Create a sentence-level tag ''' tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs) return self.add_tag(tag_obj)
python
def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs): ''' Create a sentence-level tag ''' tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs) return self.add_tag(tag_obj)
[ "def", "new_tag", "(", "self", ",", "label", ",", "cfrom", "=", "-", "1", ",", "cto", "=", "-", "1", ",", "tagtype", "=", "''", ",", "*", "*", "kwargs", ")", ":", "tag_obj", "=", "Tag", "(", "label", ",", "cfrom", ",", "cto", ",", "tagtype", ...
Create a sentence-level tag
[ "Create", "a", "sentence", "-", "level", "tag" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L222-L225
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.get_tag
def get_tag(self, tagtype): ''' Get the first tag of a particular type''' for tag in self.__tags: if tag.tagtype == tagtype: return tag return None
python
def get_tag(self, tagtype): ''' Get the first tag of a particular type''' for tag in self.__tags: if tag.tagtype == tagtype: return tag return None
[ "def", "get_tag", "(", "self", ",", "tagtype", ")", ":", "for", "tag", "in", "self", ".", "__tags", ":", "if", "tag", ".", "tagtype", "==", "tagtype", ":", "return", "tag", "return", "None" ]
Get the first tag of a particular type
[ "Get", "the", "first", "tag", "of", "a", "particular", "type" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L227-L232
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.get_tags
def get_tags(self, tagtype): ''' Get all tags of a type ''' return [t for t in self.__tags if t.tagtype == tagtype]
python
def get_tags(self, tagtype): ''' Get all tags of a type ''' return [t for t in self.__tags if t.tagtype == tagtype]
[ "def", "get_tags", "(", "self", ",", "tagtype", ")", ":", "return", "[", "t", "for", "t", "in", "self", ".", "__tags", "if", "t", ".", "tagtype", "==", "tagtype", "]" ]
Get all tags of a type
[ "Get", "all", "tags", "of", "a", "type" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L234-L236
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.add_token_object
def add_token_object(self, token): ''' Add a token object into this sentence ''' token.sent = self # take ownership of given token self.__tokens.append(token) return token
python
def add_token_object(self, token): ''' Add a token object into this sentence ''' token.sent = self # take ownership of given token self.__tokens.append(token) return token
[ "def", "add_token_object", "(", "self", ",", "token", ")", ":", "token", ".", "sent", "=", "self", "# take ownership of given token", "self", ".", "__tokens", ".", "append", "(", "token", ")", "return", "token" ]
Add a token object into this sentence
[ "Add", "a", "token", "object", "into", "this", "sentence" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L242-L246
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.new_concept
def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs): ''' Create a new concept object and add it to concept list tokens can be a list of Token objects or token indices ''' if cidx is None: cidx = self.new_concept_id() if tokens: tokens =...
python
def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs): ''' Create a new concept object and add it to concept list tokens can be a list of Token objects or token indices ''' if cidx is None: cidx = self.new_concept_id() if tokens: tokens =...
[ "def", "new_concept", "(", "self", ",", "tag", ",", "clemma", "=", "\"\"", ",", "tokens", "=", "None", ",", "cidx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "cidx", "is", "None", ":", "cidx", "=", "self", ".", "new_concept_id", "(", ...
Create a new concept object and add it to concept list tokens can be a list of Token objects or token indices
[ "Create", "a", "new", "concept", "object", "and", "add", "it", "to", "concept", "list", "tokens", "can", "be", "a", "list", "of", "Token", "objects", "or", "token", "indices" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L254-L263
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.add_concept
def add_concept(self, concept_obj): ''' Add a concept to current concept list ''' if concept_obj is None: raise Exception("Concept object cannot be None") elif concept_obj in self.__concepts: raise Exception("Concept object is already inside") elif concept_obj.cid...
python
def add_concept(self, concept_obj): ''' Add a concept to current concept list ''' if concept_obj is None: raise Exception("Concept object cannot be None") elif concept_obj in self.__concepts: raise Exception("Concept object is already inside") elif concept_obj.cid...
[ "def", "add_concept", "(", "self", ",", "concept_obj", ")", ":", "if", "concept_obj", "is", "None", ":", "raise", "Exception", "(", "\"Concept object cannot be None\"", ")", "elif", "concept_obj", "in", "self", ".", "__concepts", ":", "raise", "Exception", "(", ...
Add a concept to current concept list
[ "Add", "a", "concept", "to", "current", "concept", "list" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L265-L276
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.concept
def concept(self, cid, **kwargs): ''' Get concept by concept ID ''' if cid not in self.__concept_map: if 'default' in kwargs: return kwargs['default'] else: raise KeyError("Invalid cid") else: return self.__concept_map[cid]
python
def concept(self, cid, **kwargs): ''' Get concept by concept ID ''' if cid not in self.__concept_map: if 'default' in kwargs: return kwargs['default'] else: raise KeyError("Invalid cid") else: return self.__concept_map[cid]
[ "def", "concept", "(", "self", ",", "cid", ",", "*", "*", "kwargs", ")", ":", "if", "cid", "not", "in", "self", ".", "__concept_map", ":", "if", "'default'", "in", "kwargs", ":", "return", "kwargs", "[", "'default'", "]", "else", ":", "raise", "KeyEr...
Get concept by concept ID
[ "Get", "concept", "by", "concept", "ID" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L289-L297
train
letuananh/chirptext
chirptext/texttaglib.py
Sentence.import_tokens
def import_tokens(self, tokens, import_hook=None, ignorecase=True): ''' Import a list of string as tokens ''' text = self.text.lower() if ignorecase else self.text has_hooker = import_hook and callable(import_hook) cfrom = 0 if self.__tokens: for tk in self.__tokens: ...
python
def import_tokens(self, tokens, import_hook=None, ignorecase=True): ''' Import a list of string as tokens ''' text = self.text.lower() if ignorecase else self.text has_hooker = import_hook and callable(import_hook) cfrom = 0 if self.__tokens: for tk in self.__tokens: ...
[ "def", "import_tokens", "(", "self", ",", "tokens", ",", "import_hook", "=", "None", ",", "ignorecase", "=", "True", ")", ":", "text", "=", "self", ".", "text", ".", "lower", "(", ")", "if", "ignorecase", "else", "self", ".", "text", "has_hooker", "=",...
Import a list of string as tokens
[ "Import", "a", "list", "of", "string", "as", "tokens" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L315-L345
train
letuananh/chirptext
chirptext/texttaglib.py
Token.tag_map
def tag_map(self): ''' Build a map from tagtype to list of tags ''' tm = dd(list) for tag in self.__tags: tm[tag.tagtype].append(tag) return tm
python
def tag_map(self): ''' Build a map from tagtype to list of tags ''' tm = dd(list) for tag in self.__tags: tm[tag.tagtype].append(tag) return tm
[ "def", "tag_map", "(", "self", ")", ":", "tm", "=", "dd", "(", "list", ")", "for", "tag", "in", "self", ".", "__tags", ":", "tm", "[", "tag", ".", "tagtype", "]", ".", "append", "(", "tag", ")", "return", "tm" ]
Build a map from tagtype to list of tags
[ "Build", "a", "map", "from", "tagtype", "to", "list", "of", "tags" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L420-L425
train
letuananh/chirptext
chirptext/texttaglib.py
Token.find
def find(self, tagtype, **kwargs): '''Get the first tag with a type in this token ''' for t in self.__tags: if t.tagtype == tagtype: return t if 'default' in kwargs: return kwargs['default'] else: raise LookupError("Token {} is not tagg...
python
def find(self, tagtype, **kwargs): '''Get the first tag with a type in this token ''' for t in self.__tags: if t.tagtype == tagtype: return t if 'default' in kwargs: return kwargs['default'] else: raise LookupError("Token {} is not tagg...
[ "def", "find", "(", "self", ",", "tagtype", ",", "*", "*", "kwargs", ")", ":", "for", "t", "in", "self", ".", "__tags", ":", "if", "t", ".", "tagtype", "==", "tagtype", ":", "return", "t", "if", "'default'", "in", "kwargs", ":", "return", "kwargs",...
Get the first tag with a type in this token
[ "Get", "the", "first", "tag", "with", "a", "type", "in", "this", "token" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L430-L438
train
letuananh/chirptext
chirptext/texttaglib.py
Token.find_all
def find_all(self, tagtype): ''' Find all token-level tags with the specified tagtype ''' return [t for t in self.__tags if t.tagtype == tagtype]
python
def find_all(self, tagtype): ''' Find all token-level tags with the specified tagtype ''' return [t for t in self.__tags if t.tagtype == tagtype]
[ "def", "find_all", "(", "self", ",", "tagtype", ")", ":", "return", "[", "t", "for", "t", "in", "self", ".", "__tags", "if", "t", ".", "tagtype", "==", "tagtype", "]" ]
Find all token-level tags with the specified tagtype
[ "Find", "all", "token", "-", "level", "tags", "with", "the", "specified", "tagtype" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L440-L442
train
letuananh/chirptext
chirptext/texttaglib.py
Token.new_tag
def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs): ''' Create a new tag on this token ''' if cfrom is None: cfrom = self.cfrom if cto is None: cto = self.cto tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs) retur...
python
def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs): ''' Create a new tag on this token ''' if cfrom is None: cfrom = self.cfrom if cto is None: cto = self.cto tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs) retur...
[ "def", "new_tag", "(", "self", ",", "label", ",", "cfrom", "=", "None", ",", "cto", "=", "None", ",", "tagtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "cfrom", "is", "None", ":", "cfrom", "=", "self", ".", "cfrom", "if", "cto", ...
Create a new tag on this token
[ "Create", "a", "new", "tag", "on", "this", "token" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L448-L455
train
letuananh/chirptext
chirptext/texttaglib.py
Document.get
def get(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if sent_id is ...
python
def get(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if sent_id is ...
[ "def", "get", "(", "self", ",", "sent_id", ",", "*", "*", "kwargs", ")", ":", "if", "sent_id", "is", "not", "None", "and", "not", "isinstance", "(", "sent_id", ",", "int", ")", ":", "sent_id", "=", "int", "(", "sent_id", ")", "if", "sent_id", "is",...
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.
[ "If", "sent_id", "exists", "remove", "and", "return", "the", "associated", "sentence", "object", "else", "return", "default", ".", "If", "no", "default", "is", "provided", "KeyError", "will", "be", "raised", "." ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L588-L598
train
letuananh/chirptext
chirptext/texttaglib.py
Document.add_sent
def add_sent(self, sent_obj): ''' Add a ttl.Sentence object to this document ''' if sent_obj is None: raise Exception("Sentence object cannot be None") elif sent_obj.ID is None: # if sentID is None, create a new ID sent_obj.ID = next(self.__idgen) elif...
python
def add_sent(self, sent_obj): ''' Add a ttl.Sentence object to this document ''' if sent_obj is None: raise Exception("Sentence object cannot be None") elif sent_obj.ID is None: # if sentID is None, create a new ID sent_obj.ID = next(self.__idgen) elif...
[ "def", "add_sent", "(", "self", ",", "sent_obj", ")", ":", "if", "sent_obj", "is", "None", ":", "raise", "Exception", "(", "\"Sentence object cannot be None\"", ")", "elif", "sent_obj", ".", "ID", "is", "None", ":", "# if sentID is None, create a new ID", "sent_ob...
Add a ttl.Sentence object to this document
[ "Add", "a", "ttl", ".", "Sentence", "object", "to", "this", "document" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L603-L614
train
letuananh/chirptext
chirptext/texttaglib.py
Document.new_sent
def new_sent(self, text, ID=None, **kwargs): ''' Create a new sentence and add it to this Document ''' if ID is None: ID = next(self.__idgen) return self.add_sent(Sentence(text, ID=ID, **kwargs))
python
def new_sent(self, text, ID=None, **kwargs): ''' Create a new sentence and add it to this Document ''' if ID is None: ID = next(self.__idgen) return self.add_sent(Sentence(text, ID=ID, **kwargs))
[ "def", "new_sent", "(", "self", ",", "text", ",", "ID", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ID", "is", "None", ":", "ID", "=", "next", "(", "self", ".", "__idgen", ")", "return", "self", ".", "add_sent", "(", "Sentence", "(", ...
Create a new sentence and add it to this Document
[ "Create", "a", "new", "sentence", "and", "add", "it", "to", "this", "Document" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L616-L620
train
letuananh/chirptext
chirptext/texttaglib.py
Document.pop
def pop(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if not self.ha...
python
def pop(self, sent_id, **kwargs): ''' If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.''' if sent_id is not None and not isinstance(sent_id, int): sent_id = int(sent_id) if not self.ha...
[ "def", "pop", "(", "self", ",", "sent_id", ",", "*", "*", "kwargs", ")", ":", "if", "sent_id", "is", "not", "None", "and", "not", "isinstance", "(", "sent_id", ",", "int", ")", ":", "sent_id", "=", "int", "(", "sent_id", ")", "if", "not", "self", ...
If sent_id exists, remove and return the associated sentence object else return default. If no default is provided, KeyError will be raised.
[ "If", "sent_id", "exists", "remove", "and", "return", "the", "associated", "sentence", "object", "else", "return", "default", ".", "If", "no", "default", "is", "provided", "KeyError", "will", "be", "raised", "." ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L622-L637
train
letuananh/chirptext
chirptext/texttaglib.py
Document.read
def read(self): ''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) ''' warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning) with TxtReader.from_doc(self) as reader: reader.read(self) return self
python
def read(self): ''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) ''' warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning) with TxtReader.from_doc(self) as reader: reader.read(self) return self
[ "def", "read", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"Document.read() is deprecated and will be removed in near future.\"", ",", "DeprecationWarning", ")", "with", "TxtReader", ".", "from_doc", "(", "self", ")", "as", "reader", ":", "reader", ".", ...
Read tagged doc from mutliple files (sents, tokens, concepts, links, tags)
[ "Read", "tagged", "doc", "from", "mutliple", "files", "(", "sents", "tokens", "concepts", "links", "tags", ")" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L639-L644
train