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
alefnula/tea
tea/utils/compress.py
seven_zip
def seven_zip(archive, items, self_extracting=False): """Create a 7z archive.""" if not isinstance(items, (list, tuple)): items = [items] if self_extracting: return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items) else: return er(_get_sz(), "a", "-ssw", archive, *items)
python
def seven_zip(archive, items, self_extracting=False): """Create a 7z archive.""" if not isinstance(items, (list, tuple)): items = [items] if self_extracting: return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items) else: return er(_get_sz(), "a", "-ssw", archive, *items)
[ "def", "seven_zip", "(", "archive", ",", "items", ",", "self_extracting", "=", "False", ")", ":", "if", "not", "isinstance", "(", "items", ",", "(", "list", ",", "tuple", ")", ")", ":", "items", "=", "[", "items", "]", "if", "self_extracting", ":", "...
Create a 7z archive.
[ "Create", "a", "7z", "archive", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/compress.py#L158-L165
train
night-crawler/django-docker-helpers
django_docker_helpers/db.py
ensure_caches_alive
def ensure_caches_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries`` attempts to reach any backend are faile...
python
def ensure_caches_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries`` attempts to reach any backend are faile...
[ "def", "ensure_caches_alive", "(", "max_retries", ":", "int", "=", "100", ",", "retry_timeout", ":", "int", "=", "5", ",", "exit_on_failure", ":", "bool", "=", "True", ")", "->", "bool", ":", "for", "cache_alias", "in", "settings", ".", "CACHES", ".", "k...
Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries`` attempts to reach any backend are failed it returns ``False``. If ``exit_on_failure`` is set it shuts down with ``exit(1)``. It sets the ``django-docker-helpers:available-check`` key for every cache ba...
[ "Checks", "every", "cache", "backend", "alias", "in", "settings", ".", "CACHES", "until", "it", "becomes", "available", ".", "After", "max_retries", "attempts", "to", "reach", "any", "backend", "are", "failed", "it", "returns", "False", ".", "If", "exit_on_fai...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/db.py#L12-L45
train
night-crawler/django-docker-helpers
django_docker_helpers/db.py
ensure_databases_alive
def ensure_databases_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend ar...
python
def ensure_databases_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend ar...
[ "def", "ensure_databases_alive", "(", "max_retries", ":", "int", "=", "100", ",", "retry_timeout", ":", "int", "=", "5", ",", "exit_on_failure", ":", "bool", "=", "True", ")", "->", "bool", ":", "template", "=", "\"\"\"\n =============================\n Chec...
Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend are failed it returns ``False``. If ``exit_on_failure`` is set it shuts down with ``exit(1)``. For every database alias it tries to ``SELECT 1``. If no errors raised it chec...
[ "Checks", "every", "database", "alias", "in", "settings", ".", "DATABASES", "until", "it", "becomes", "available", ".", "After", "max_retries", "attempts", "to", "reach", "any", "backend", "are", "failed", "it", "returns", "False", ".", "If", "exit_on_failure", ...
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/db.py#L49-L98
train
night-crawler/django-docker-helpers
django_docker_helpers/db.py
migrate
def migrate(*argv) -> bool: """ Runs Django migrate command. :return: always ``True`` """ wf('Applying migrations... ', False) execute_from_command_line(['./manage.py', 'migrate'] + list(argv)) wf('[+]\n') return True
python
def migrate(*argv) -> bool: """ Runs Django migrate command. :return: always ``True`` """ wf('Applying migrations... ', False) execute_from_command_line(['./manage.py', 'migrate'] + list(argv)) wf('[+]\n') return True
[ "def", "migrate", "(", "*", "argv", ")", "->", "bool", ":", "wf", "(", "'Applying migrations... '", ",", "False", ")", "execute_from_command_line", "(", "[", "'./manage.py'", ",", "'migrate'", "]", "+", "list", "(", "argv", ")", ")", "wf", "(", "'[+]\\n'",...
Runs Django migrate command. :return: always ``True``
[ "Runs", "Django", "migrate", "command", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/db.py#L102-L111
train
hufman/flask_rdf
flask_rdf/wsgi.py
Decorator.output
def output(self, output, accepts, set_http_code, set_content_type): """ Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = Decorator...
python
def output(self, output, accepts, set_http_code, set_content_type): """ Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = Decorator...
[ "def", "output", "(", "self", ",", "output", ",", "accepts", ",", "set_http_code", ",", "set_content_type", ")", ":", "graph", "=", "Decorator", ".", "_get_graph", "(", "output", ")", "if", "graph", "is", "not", "None", ":", "# decide the format", "output_mi...
Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling
[ "Formats", "a", "response", "from", "a", "WSGI", "app", "to", "handle", "any", "RDF", "graphs", "If", "a", "view", "function", "returns", "a", "single", "RDF", "graph", "serialize", "it", "based", "on", "Accept", "header", "If", "it", "s", "not", "an", ...
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/wsgi.py#L24-L47
train
hufman/flask_rdf
flask_rdf/wsgi.py
Decorator.decorate
def decorate(self, app): """ Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ from functools import wraps @wraps(app) def decorated(environ, start_response): # capt...
python
def decorate(self, app): """ Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ from functools import wraps @wraps(app) def decorated(environ, start_response): # capt...
[ "def", "decorate", "(", "self", ",", "app", ")", ":", "from", "functools", "import", "wraps", "@", "wraps", "(", "app", ")", "def", "decorated", "(", "environ", ",", "start_response", ")", ":", "# capture any start_response from the app", "app_response", "=", ...
Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified
[ "Wraps", "a", "WSGI", "application", "to", "return", "formatted", "RDF", "graphs", "Uses", "content", "negotiation", "to", "serialize", "the", "graph", "to", "the", "client", "-", "preferred", "format", "Passes", "other", "content", "through", "unmodified" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/wsgi.py#L49-L101
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalNameHandlerDecorator.is_handler
def is_handler(cls, name, value): """Detect an handler and return its wanted signal name.""" signal_name = False config = None if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME): spec = getattr(value, SPEC_CONTAINER_MEMBER_NAME) if spec['kin...
python
def is_handler(cls, name, value): """Detect an handler and return its wanted signal name.""" signal_name = False config = None if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME): spec = getattr(value, SPEC_CONTAINER_MEMBER_NAME) if spec['kin...
[ "def", "is_handler", "(", "cls", ",", "name", ",", "value", ")", ":", "signal_name", "=", "False", "config", "=", "None", "if", "callable", "(", "value", ")", "and", "hasattr", "(", "value", ",", "SPEC_CONTAINER_MEMBER_NAME", ")", ":", "spec", "=", "geta...
Detect an handler and return its wanted signal name.
[ "Detect", "an", "handler", "and", "return", "its", "wanted", "signal", "name", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L36-L45
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
InheritanceToolsMeta._build_inheritance_chain
def _build_inheritance_chain(cls, bases, *names, merge=False): """For all of the names build a ChainMap containing a map for every base class.""" result = [] for name in names: maps = [] for base in bases: bmap = getattr(base, name, None) ...
python
def _build_inheritance_chain(cls, bases, *names, merge=False): """For all of the names build a ChainMap containing a map for every base class.""" result = [] for name in names: maps = [] for base in bases: bmap = getattr(base, name, None) ...
[ "def", "_build_inheritance_chain", "(", "cls", ",", "bases", ",", "*", "names", ",", "merge", "=", "False", ")", ":", "result", "=", "[", "]", "for", "name", "in", "names", ":", "maps", "=", "[", "]", "for", "base", "in", "bases", ":", "bmap", "=",...
For all of the names build a ChainMap containing a map for every base class.
[ "For", "all", "of", "the", "names", "build", "a", "ChainMap", "containing", "a", "map", "for", "every", "base", "class", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L55-L75
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta._build_instance_handler_mapping
def _build_instance_handler_mapping(cls, instance, handle_d): """For every unbound handler, get the bound version.""" res = {} for member_name, sig_name in handle_d.items(): if sig_name in res: sig_handlers = res[sig_name] else: sig_handler...
python
def _build_instance_handler_mapping(cls, instance, handle_d): """For every unbound handler, get the bound version.""" res = {} for member_name, sig_name in handle_d.items(): if sig_name in res: sig_handlers = res[sig_name] else: sig_handler...
[ "def", "_build_instance_handler_mapping", "(", "cls", ",", "instance", ",", "handle_d", ")", ":", "res", "=", "{", "}", "for", "member_name", ",", "sig_name", "in", "handle_d", ".", "items", "(", ")", ":", "if", "sig_name", "in", "res", ":", "sig_handlers"...
For every unbound handler, get the bound version.
[ "For", "every", "unbound", "handler", "get", "the", "bound", "version", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L134-L143
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta._check_local_handlers
def _check_local_handlers(cls, signals, handlers, namespace, configs): """For every marked handler, see if there is a suitable signal. If not, raise an error.""" for aname, sig_name in handlers.items(): # WARN: this code doesn't take in account the case where a new # meth...
python
def _check_local_handlers(cls, signals, handlers, namespace, configs): """For every marked handler, see if there is a suitable signal. If not, raise an error.""" for aname, sig_name in handlers.items(): # WARN: this code doesn't take in account the case where a new # meth...
[ "def", "_check_local_handlers", "(", "cls", ",", "signals", ",", "handlers", ",", "namespace", ",", "configs", ")", ":", "for", "aname", ",", "sig_name", "in", "handlers", ".", "items", "(", ")", ":", "# WARN: this code doesn't take in account the case where a new",...
For every marked handler, see if there is a suitable signal. If not, raise an error.
[ "For", "every", "marked", "handler", "see", "if", "there", "is", "a", "suitable", "signal", ".", "If", "not", "raise", "an", "error", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L145-L157
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta._find_local_signals
def _find_local_signals(cls, signals, namespace): """Add name info to every "local" (present in the body of this class) signal and add it to the mapping. Also complete signal initialization as member of the class by injecting its name. """ from . import Signal signaller...
python
def _find_local_signals(cls, signals, namespace): """Add name info to every "local" (present in the body of this class) signal and add it to the mapping. Also complete signal initialization as member of the class by injecting its name. """ from . import Signal signaller...
[ "def", "_find_local_signals", "(", "cls", ",", "signals", ",", "namespace", ")", ":", "from", ".", "import", "Signal", "signaller", "=", "cls", ".", "_external_signaller_and_handler", "for", "aname", ",", "avalue", "in", "namespace", ".", "items", "(", ")", ...
Add name info to every "local" (present in the body of this class) signal and add it to the mapping. Also complete signal initialization as member of the class by injecting its name.
[ "Add", "name", "info", "to", "every", "local", "(", "present", "in", "the", "body", "of", "this", "class", ")", "signal", "and", "add", "it", "to", "the", "mapping", ".", "Also", "complete", "signal", "initialization", "as", "member", "of", "the", "class...
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L159-L178
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta._find_local_handlers
def _find_local_handlers(cls, handlers, namespace, configs): """Add name info to every "local" (present in the body of this class) handler and add it to the mapping. """ for aname, avalue in namespace.items(): sig_name, config = cls._is_handler(aname, avalue) if ...
python
def _find_local_handlers(cls, handlers, namespace, configs): """Add name info to every "local" (present in the body of this class) handler and add it to the mapping. """ for aname, avalue in namespace.items(): sig_name, config = cls._is_handler(aname, avalue) if ...
[ "def", "_find_local_handlers", "(", "cls", ",", "handlers", ",", "namespace", ",", "configs", ")", ":", "for", "aname", ",", "avalue", "in", "namespace", ".", "items", "(", ")", ":", "sig_name", ",", "config", "=", "cls", ".", "_is_handler", "(", "aname"...
Add name info to every "local" (present in the body of this class) handler and add it to the mapping.
[ "Add", "name", "info", "to", "every", "local", "(", "present", "in", "the", "body", "of", "this", "class", ")", "handler", "and", "add", "it", "to", "the", "mapping", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L180-L188
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta._get_class_handlers
def _get_class_handlers(cls, signal_name, instance): """Returns the handlers registered at class level. """ handlers = cls._signal_handlers_sorted[signal_name] return [getattr(instance, hname) for hname in handlers]
python
def _get_class_handlers(cls, signal_name, instance): """Returns the handlers registered at class level. """ handlers = cls._signal_handlers_sorted[signal_name] return [getattr(instance, hname) for hname in handlers]
[ "def", "_get_class_handlers", "(", "cls", ",", "signal_name", ",", "instance", ")", ":", "handlers", "=", "cls", ".", "_signal_handlers_sorted", "[", "signal_name", "]", "return", "[", "getattr", "(", "instance", ",", "hname", ")", "for", "hname", "in", "han...
Returns the handlers registered at class level.
[ "Returns", "the", "handlers", "registered", "at", "class", "level", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L190-L194
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta._sort_handlers
def _sort_handlers(cls, signals, handlers, configs): """Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes. """ def macro_precedence_sor...
python
def _sort_handlers(cls, signals, handlers, configs): """Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes. """ def macro_precedence_sor...
[ "def", "_sort_handlers", "(", "cls", ",", "signals", ",", "handlers", ",", "configs", ")", ":", "def", "macro_precedence_sorter", "(", "flags", ",", "hname", ")", ":", "\"\"\"The default is to sort 'bottom_up', with lower level getting\n executed first, but sometim...
Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes.
[ "Sort", "class", "defined", "handlers", "to", "give", "precedence", "to", "those", "declared", "at", "lower", "level", ".", "config", "can", "contain", "two", "keys", "begin", "or", "end", "that", "will", "further", "reposition", "the", "handler", "at", "the...
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L196-L230
train
metapensiero/metapensiero.signal
src/metapensiero/signal/user.py
SignalAndHandlerInitMeta.instance_signals_and_handlers
def instance_signals_and_handlers(cls, instance): """Calculate per-instance signals and handlers.""" isignals = cls._signals.copy() ihandlers = cls._build_instance_handler_mapping( instance, cls._signal_handlers ) return isignals, ihandlers
python
def instance_signals_and_handlers(cls, instance): """Calculate per-instance signals and handlers.""" isignals = cls._signals.copy() ihandlers = cls._build_instance_handler_mapping( instance, cls._signal_handlers ) return isignals, ihandlers
[ "def", "instance_signals_and_handlers", "(", "cls", ",", "instance", ")", ":", "isignals", "=", "cls", ".", "_signals", ".", "copy", "(", ")", "ihandlers", "=", "cls", ".", "_build_instance_handler_mapping", "(", "instance", ",", "cls", ".", "_signal_handlers", ...
Calculate per-instance signals and handlers.
[ "Calculate", "per", "-", "instance", "signals", "and", "handlers", "." ]
1cbbb2e4bff00bf4887163b08b70d278e472bfe3
https://github.com/metapensiero/metapensiero.signal/blob/1cbbb2e4bff00bf4887163b08b70d278e472bfe3/src/metapensiero/signal/user.py#L232-L240
train
meng89/ipodshuffle
ipodshuffle/storage/log.py
Storage.add
def add(self, src): """ :param src: file path :return: checksum value """ checksum = get_checksum(src) filename = self.get_filename(checksum) if not filename: new_name = self._get_new_name() new_realpath = self._storage_dir + '/' + new_...
python
def add(self, src): """ :param src: file path :return: checksum value """ checksum = get_checksum(src) filename = self.get_filename(checksum) if not filename: new_name = self._get_new_name() new_realpath = self._storage_dir + '/' + new_...
[ "def", "add", "(", "self", ",", "src", ")", ":", "checksum", "=", "get_checksum", "(", "src", ")", "filename", "=", "self", ".", "get_filename", "(", "checksum", ")", "if", "not", "filename", ":", "new_name", "=", "self", ".", "_get_new_name", "(", ")"...
:param src: file path :return: checksum value
[ ":", "param", "src", ":", "file", "path", ":", "return", ":", "checksum", "value" ]
c9093dbb5cdac609376ebd3b4ef1b0fc58107d96
https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/storage/log.py#L129-L155
train
meng89/ipodshuffle
ipodshuffle/storage/log.py
Storage.get_filename
def get_filename(self, checksum): """ :param checksum: checksum :return: filename no storage base part """ filename = None for _filename, metadata in self._log.items(): if metadata['checksum'] == checksum: filename = _filename b...
python
def get_filename(self, checksum): """ :param checksum: checksum :return: filename no storage base part """ filename = None for _filename, metadata in self._log.items(): if metadata['checksum'] == checksum: filename = _filename b...
[ "def", "get_filename", "(", "self", ",", "checksum", ")", ":", "filename", "=", "None", "for", "_filename", ",", "metadata", "in", "self", ".", "_log", ".", "items", "(", ")", ":", "if", "metadata", "[", "'checksum'", "]", "==", "checksum", ":", "filen...
:param checksum: checksum :return: filename no storage base part
[ ":", "param", "checksum", ":", "checksum", ":", "return", ":", "filename", "no", "storage", "base", "part" ]
c9093dbb5cdac609376ebd3b4ef1b0fc58107d96
https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/storage/log.py#L157-L167
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.__retrieve
def __retrieve(self, key): ''' Retrieve file location from cache DB ''' with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT value FROM cache_entries WHERE key IS NULL") else: ...
python
def __retrieve(self, key): ''' Retrieve file location from cache DB ''' with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT value FROM cache_entries WHERE key IS NULL") else: ...
[ "def", "__retrieve", "(", "self", ",", "key", ")", ":", "with", "self", ".", "get_conn", "(", ")", "as", "conn", ":", "try", ":", "c", "=", "conn", ".", "cursor", "(", ")", "if", "key", "is", "None", ":", "c", ".", "execute", "(", "\"SELECT value...
Retrieve file location from cache DB
[ "Retrieve", "file", "location", "from", "cache", "DB" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L85-L103
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.__insert
def __insert(self, key, value): ''' Insert a new key to database ''' if key in self: getLogger().warning("Cache entry exists, cannot insert a new entry with key='{key}'".format(key=key)) return False with self.get_conn() as conn: try: ...
python
def __insert(self, key, value): ''' Insert a new key to database ''' if key in self: getLogger().warning("Cache entry exists, cannot insert a new entry with key='{key}'".format(key=key)) return False with self.get_conn() as conn: try: ...
[ "def", "__insert", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ":", "getLogger", "(", ")", ".", "warning", "(", "\"Cache entry exists, cannot insert a new entry with key='{key}'\"", ".", "format", "(", "key", "=", "key", ")", ...
Insert a new key to database
[ "Insert", "a", "new", "key", "to", "database" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L111-L127
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.__delete
def __delete(self, key): ''' Delete file key from database ''' with self.get_conn() as conn: try: c = conn.cursor() c.execute("DELETE FROM cache_entries WHERE key = ?", (key,)) conn.commit() except: getLogger...
python
def __delete(self, key): ''' Delete file key from database ''' with self.get_conn() as conn: try: c = conn.cursor() c.execute("DELETE FROM cache_entries WHERE key = ?", (key,)) conn.commit() except: getLogger...
[ "def", "__delete", "(", "self", ",", "key", ")", ":", "with", "self", ".", "get_conn", "(", ")", "as", "conn", ":", "try", ":", "c", "=", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "\"DELETE FROM cache_entries WHERE key = ?\"", ",", "("...
Delete file key from database
[ "Delete", "file", "key", "from", "database" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L129-L139
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.__insert_internal_blob
def __insert_internal_blob(self, key, blob, compressed=True): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None c = conn.cursor() try: compressed_flag = 1 if compressed else 0 ...
python
def __insert_internal_blob(self, key, blob, compressed=True): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None c = conn.cursor() try: compressed_flag = 1 if compressed else 0 ...
[ "def", "__insert_internal_blob", "(", "self", ",", "key", ",", "blob", ",", "compressed", "=", "True", ")", ":", "with", "self", ".", "get_conn", "(", ")", "as", "conn", ":", "conn", ".", "isolation_level", "=", "None", "c", "=", "conn", ".", "cursor",...
This method will insert blob data to blob table
[ "This", "method", "will", "insert", "blob", "data", "to", "blob", "table" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L143-L160
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.__delete_internal_blob
def __delete_internal_blob(self, key): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None try: c = conn.cursor() c.execute("BEGIN") if key is None: ...
python
def __delete_internal_blob(self, key): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None try: c = conn.cursor() c.execute("BEGIN") if key is None: ...
[ "def", "__delete_internal_blob", "(", "self", ",", "key", ")", ":", "with", "self", ".", "get_conn", "(", ")", "as", "conn", ":", "conn", ".", "isolation_level", "=", "None", "try", ":", "c", "=", "conn", ".", "cursor", "(", ")", "c", ".", "execute",...
This method will insert blob data to blob table
[ "This", "method", "will", "insert", "blob", "data", "to", "blob", "table" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L162-L180
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.__retrieve_internal_blob
def __retrieve_internal_blob(self, key): ''' Retrieve file location from cache DB ''' logger = getLogger() with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT compressed, blob_data FROM blo...
python
def __retrieve_internal_blob(self, key): ''' Retrieve file location from cache DB ''' logger = getLogger() with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT compressed, blob_data FROM blo...
[ "def", "__retrieve_internal_blob", "(", "self", ",", "key", ")", ":", "logger", "=", "getLogger", "(", ")", "with", "self", ".", "get_conn", "(", ")", "as", "conn", ":", "try", ":", "c", "=", "conn", ".", "cursor", "(", ")", "if", "key", "is", "Non...
Retrieve file location from cache DB
[ "Retrieve", "file", "location", "from", "cache", "DB" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L182-L205
train
letuananh/chirptext
chirptext/arsenal.py
JiCache.retrieve_blob
def retrieve_blob(self, key, encoding=None): ''' Retrieve blob in binary format (or string format if encoding is provided) ''' blob_key = self.__retrieve(key) if blob_key is None: return None if not blob_key: raise Exception("Invalid blob_key") elif blob_k...
python
def retrieve_blob(self, key, encoding=None): ''' Retrieve blob in binary format (or string format if encoding is provided) ''' blob_key = self.__retrieve(key) if blob_key is None: return None if not blob_key: raise Exception("Invalid blob_key") elif blob_k...
[ "def", "retrieve_blob", "(", "self", ",", "key", ",", "encoding", "=", "None", ")", ":", "blob_key", "=", "self", ".", "__retrieve", "(", "key", ")", "if", "blob_key", "is", "None", ":", "return", "None", "if", "not", "blob_key", ":", "raise", "Excepti...
Retrieve blob in binary format (or string format if encoding is provided)
[ "Retrieve", "blob", "in", "binary", "format", "(", "or", "string", "format", "if", "encoding", "is", "provided", ")" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/arsenal.py#L233-L246
train
pyout/pyout
pyout/summary.py
Summary.summarize
def summarize(self, rows): """Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the secon...
python
def summarize(self, rows): """Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the secon...
[ "def", "summarize", "(", "self", ",", "rows", ")", ":", "columns", "=", "list", "(", "rows", "[", "0", "]", ".", "keys", "(", ")", ")", "agg_styles", "=", "{", "c", ":", "self", ".", "style", "[", "c", "]", "[", "\"aggregate\"", "]", "for", "c"...
Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the second is a dict of keyword arguments that ...
[ "Return", "summary", "rows", "for", "rows", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/summary.py#L33-L82
train
pyout/pyout
pyout/interface.py
Writer._init
def _init(self, style, streamer, processors=None): """Do writer-specific setup. Parameters ---------- style : dict Style, as passed to __init__. streamer : interface.Stream A stream interface that takes __init__'s `stream` and `interactive` ar...
python
def _init(self, style, streamer, processors=None): """Do writer-specific setup. Parameters ---------- style : dict Style, as passed to __init__. streamer : interface.Stream A stream interface that takes __init__'s `stream` and `interactive` ar...
[ "def", "_init", "(", "self", ",", "style", ",", "streamer", ",", "processors", "=", "None", ")", ":", "self", ".", "_stream", "=", "streamer", "if", "streamer", ".", "interactive", ":", "if", "streamer", ".", "supports_updates", ":", "self", ".", "mode",...
Do writer-specific setup. Parameters ---------- style : dict Style, as passed to __init__. streamer : interface.Stream A stream interface that takes __init__'s `stream` and `interactive` arguments into account. processors : field.StyleProcesso...
[ "Do", "writer", "-", "specific", "setup", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/interface.py#L109-L135
train
pyout/pyout
pyout/interface.py
Writer.ids
def ids(self): """A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name. """ if self._ids is None: if self._columns: if isinstance(self._columns, OrderedDict): return [list(self._columns.k...
python
def ids(self): """A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name. """ if self._ids is None: if self._columns: if isinstance(self._columns, OrderedDict): return [list(self._columns.k...
[ "def", "ids", "(", "self", ")", ":", "if", "self", ".", "_ids", "is", "None", ":", "if", "self", ".", "_columns", ":", "if", "isinstance", "(", "self", ".", "_columns", ",", "OrderedDict", ")", ":", "return", "[", "list", "(", "self", ".", "_column...
A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name.
[ "A", "list", "of", "unique", "IDs", "used", "to", "identify", "a", "row", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/interface.py#L188-L199
train
pyout/pyout
pyout/interface.py
Writer.wait
def wait(self): """Wait for asynchronous calls to return. """ if self._pool is None: return self._pool.close() self._pool.join()
python
def wait(self): """Wait for asynchronous calls to return. """ if self._pool is None: return self._pool.close() self._pool.join()
[ "def", "wait", "(", "self", ")", ":", "if", "self", ".", "_pool", "is", "None", ":", "return", "self", ".", "_pool", ".", "close", "(", ")", "self", ".", "_pool", ".", "join", "(", ")" ]
Wait for asynchronous calls to return.
[ "Wait", "for", "asynchronous", "calls", "to", "return", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/interface.py#L205-L211
train
pyout/pyout
pyout/interface.py
Writer._write_lock
def _write_lock(self): """Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context. """ if self._lock: lgr.de...
python
def _write_lock(self): """Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context. """ if self._lock: lgr.de...
[ "def", "_write_lock", "(", "self", ")", ":", "if", "self", ".", "_lock", ":", "lgr", ".", "debug", "(", "\"Acquiring write lock\"", ")", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "yield", "finally", ":", "if", "self", ".", "_lock", ...
Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context.
[ "Acquire", "and", "release", "the", "lock", "around", "output", "calls", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/interface.py#L214-L229
train
pyout/pyout
pyout/interface.py
Writer._start_callables
def _start_callables(self, row, callables): """Start running `callables` asynchronously. """ id_vals = {c: row[c] for c in self.ids} def callback(tab, cols, result): if isinstance(result, Mapping): pass elif isinstance(result, tuple): ...
python
def _start_callables(self, row, callables): """Start running `callables` asynchronously. """ id_vals = {c: row[c] for c in self.ids} def callback(tab, cols, result): if isinstance(result, Mapping): pass elif isinstance(result, tuple): ...
[ "def", "_start_callables", "(", "self", ",", "row", ",", "callables", ")", ":", "id_vals", "=", "{", "c", ":", "row", "[", "c", "]", "for", "c", "in", "self", ".", "ids", "}", "def", "callback", "(", "tab", ",", "cols", ",", "result", ")", ":", ...
Start running `callables` asynchronously.
[ "Start", "running", "callables", "asynchronously", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/interface.py#L292-L329
train
smnorris/pgdata
pgdata/database.py
Database.schemas
def schemas(self): """ Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database. """ sql = """SELECT schema_name FROM information_schema.schemata ORDER BY schema_name""" schemas = self.query(sql).fetchall() return [...
python
def schemas(self): """ Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database. """ sql = """SELECT schema_name FROM information_schema.schemata ORDER BY schema_name""" schemas = self.query(sql).fetchall() return [...
[ "def", "schemas", "(", "self", ")", ":", "sql", "=", "\"\"\"SELECT schema_name FROM information_schema.schemata\n ORDER BY schema_name\"\"\"", "schemas", "=", "self", ".", "query", "(", "sql", ")", ".", "fetchall", "(", ")", "return", "[", "s", "[", ...
Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database.
[ "Get", "a", "listing", "of", "all", "non", "-", "system", "schemas", "(", "prefixed", "with", "pg_", ")", "that", "exist", "in", "the", "database", "." ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L47-L55
train
smnorris/pgdata
pgdata/database.py
Database.tables
def tables(self): """ Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes """ if self.schema: return...
python
def tables(self): """ Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes """ if self.schema: return...
[ "def", "tables", "(", "self", ")", ":", "if", "self", ".", "schema", ":", "return", "self", ".", "tables_in_schema", "(", "self", ".", "schema", ")", "else", ":", "tables", "=", "[", "]", "for", "schema", "in", "self", ".", "schemas", ":", "tables", ...
Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes
[ "Get", "a", "listing", "of", "all", "tables", "-", "if", "schema", "specified", "on", "connect", "return", "unqualifed", "table", "names", "in", "that", "schema", "-", "in", "no", "schema", "specified", "on", "connect", "return", "all", "tables", "with", "...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L58-L74
train
smnorris/pgdata
pgdata/database.py
Database._valid_table_name
def _valid_table_name(self, table): """Check if the table name is obviously invalid. """ if table is None or not len(table.strip()): raise ValueError("Invalid table name: %r" % table) return table.strip()
python
def _valid_table_name(self, table): """Check if the table name is obviously invalid. """ if table is None or not len(table.strip()): raise ValueError("Invalid table name: %r" % table) return table.strip()
[ "def", "_valid_table_name", "(", "self", ",", "table", ")", ":", "if", "table", "is", "None", "or", "not", "len", "(", "table", ".", "strip", "(", ")", ")", ":", "raise", "ValueError", "(", "\"Invalid table name: %r\"", "%", "table", ")", "return", "tabl...
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/database.py#L87-L92
train
smnorris/pgdata
pgdata/database.py
Database.build_query
def build_query(self, sql, lookup): """ Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE ...
python
def build_query(self, sql, lookup): """ Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE ...
[ "def", "build_query", "(", "self", ",", "sql", ",", "lookup", ")", ":", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "lookup", ")", ":", "sql", "=", "sql", ".", "replace", "(", "\"$\"", "+", "key", ",", "val", ")", "return", "sql...
Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE sql = 'SELECT $myInputField FROM $myInputTable' ...
[ "Modify", "table", "and", "field", "name", "variables", "in", "a", "sql", "string", "with", "a", "dict", ".", "This", "seems", "to", "be", "discouraged", "by", "psycopg2", "docs", "but", "it", "makes", "small", "adjustments", "to", "large", "sql", "strings...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L94-L109
train
smnorris/pgdata
pgdata/database.py
Database.tables_in_schema
def tables_in_schema(self, schema): """Get a listing of all tables in given schema """ sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = %s""" return [t[0] for t in self.query(sql, (schema,)).fetchall()]
python
def tables_in_schema(self, schema): """Get a listing of all tables in given schema """ sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = %s""" return [t[0] for t in self.query(sql, (schema,)).fetchall()]
[ "def", "tables_in_schema", "(", "self", ",", "schema", ")", ":", "sql", "=", "\"\"\"SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = %s\"\"\"", "return", "[", "t", "[", "0", "]", "for", "t", "in", "self", ".", "quer...
Get a listing of all tables in given schema
[ "Get", "a", "listing", "of", "all", "tables", "in", "given", "schema" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L111-L117
train
smnorris/pgdata
pgdata/database.py
Database.parse_table_name
def parse_table_name(self, table): """Parse schema qualified table name """ if "." in table: schema, table = table.split(".") else: schema = None return (schema, table)
python
def parse_table_name(self, table): """Parse schema qualified table name """ if "." in table: schema, table = table.split(".") else: schema = None return (schema, table)
[ "def", "parse_table_name", "(", "self", ",", "table", ")", ":", "if", "\".\"", "in", "table", ":", "schema", ",", "table", "=", "table", ".", "split", "(", "\".\"", ")", "else", ":", "schema", "=", "None", "return", "(", "schema", ",", "table", ")" ]
Parse schema qualified table name
[ "Parse", "schema", "qualified", "table", "name" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L119-L126
train
smnorris/pgdata
pgdata/database.py
Database.load_table
def load_table(self, table): """Loads a table. Returns None if the table does not already exist in db """ table = self._valid_table_name(table) schema, table = self.parse_table_name(table) if not schema: schema = self.schema tables = self.tables el...
python
def load_table(self, table): """Loads a table. Returns None if the table does not already exist in db """ table = self._valid_table_name(table) schema, table = self.parse_table_name(table) if not schema: schema = self.schema tables = self.tables el...
[ "def", "load_table", "(", "self", ",", "table", ")", ":", "table", "=", "self", ".", "_valid_table_name", "(", "table", ")", "schema", ",", "table", "=", "self", ".", "parse_table_name", "(", "table", ")", "if", "not", "schema", ":", "schema", "=", "se...
Loads a table. Returns None if the table does not already exist in db
[ "Loads", "a", "table", ".", "Returns", "None", "if", "the", "table", "does", "not", "already", "exist", "in", "db" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L128-L141
train
smnorris/pgdata
pgdata/database.py
Database.mogrify
def mogrify(self, sql, params): """Return the query string with parameters added """ conn = self.engine.raw_connection() cursor = conn.cursor() return cursor.mogrify(sql, params)
python
def mogrify(self, sql, params): """Return the query string with parameters added """ conn = self.engine.raw_connection() cursor = conn.cursor() return cursor.mogrify(sql, params)
[ "def", "mogrify", "(", "self", ",", "sql", ",", "params", ")", ":", "conn", "=", "self", ".", "engine", ".", "raw_connection", "(", ")", "cursor", "=", "conn", ".", "cursor", "(", ")", "return", "cursor", ".", "mogrify", "(", "sql", ",", "params", ...
Return the query string with parameters added
[ "Return", "the", "query", "string", "with", "parameters", "added" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L143-L148
train
smnorris/pgdata
pgdata/database.py
Database.execute
def execute(self, sql, params=None): """Just a pointer to engine.execute """ # wrap in a transaction to ensure things are committed # https://github.com/smnorris/pgdata/issues/3 with self.engine.begin() as conn: result = conn.execute(sql, params) return result
python
def execute(self, sql, params=None): """Just a pointer to engine.execute """ # wrap in a transaction to ensure things are committed # https://github.com/smnorris/pgdata/issues/3 with self.engine.begin() as conn: result = conn.execute(sql, params) return result
[ "def", "execute", "(", "self", ",", "sql", ",", "params", "=", "None", ")", ":", "# wrap in a transaction to ensure things are committed", "# https://github.com/smnorris/pgdata/issues/3", "with", "self", ".", "engine", ".", "begin", "(", ")", "as", "conn", ":", "res...
Just a pointer to engine.execute
[ "Just", "a", "pointer", "to", "engine", ".", "execute" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L150-L157
train
smnorris/pgdata
pgdata/database.py
Database.query_one
def query_one(self, sql, params=None): """Grab just one record """ r = self.engine.execute(sql, params) return r.fetchone()
python
def query_one(self, sql, params=None): """Grab just one record """ r = self.engine.execute(sql, params) return r.fetchone()
[ "def", "query_one", "(", "self", ",", "sql", ",", "params", "=", "None", ")", ":", "r", "=", "self", ".", "engine", ".", "execute", "(", "sql", ",", "params", ")", "return", "r", ".", "fetchone", "(", ")" ]
Grab just one record
[ "Grab", "just", "one", "record" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L169-L173
train
smnorris/pgdata
pgdata/database.py
Database.create_schema
def create_schema(self, schema): """Create specified schema if it does not already exist """ if schema not in self.schemas: sql = "CREATE SCHEMA " + schema self.execute(sql)
python
def create_schema(self, schema): """Create specified schema if it does not already exist """ if schema not in self.schemas: sql = "CREATE SCHEMA " + schema self.execute(sql)
[ "def", "create_schema", "(", "self", ",", "schema", ")", ":", "if", "schema", "not", "in", "self", ".", "schemas", ":", "sql", "=", "\"CREATE SCHEMA \"", "+", "schema", "self", ".", "execute", "(", "sql", ")" ]
Create specified schema if it does not already exist
[ "Create", "specified", "schema", "if", "it", "does", "not", "already", "exist" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L175-L180
train
smnorris/pgdata
pgdata/database.py
Database.drop_schema
def drop_schema(self, schema, cascade=False): """Drop specified schema """ if schema in self.schemas: sql = "DROP SCHEMA " + schema if cascade: sql = sql + " CASCADE" self.execute(sql)
python
def drop_schema(self, schema, cascade=False): """Drop specified schema """ if schema in self.schemas: sql = "DROP SCHEMA " + schema if cascade: sql = sql + " CASCADE" self.execute(sql)
[ "def", "drop_schema", "(", "self", ",", "schema", ",", "cascade", "=", "False", ")", ":", "if", "schema", "in", "self", ".", "schemas", ":", "sql", "=", "\"DROP SCHEMA \"", "+", "schema", "if", "cascade", ":", "sql", "=", "sql", "+", "\" CASCADE\"", "s...
Drop specified schema
[ "Drop", "specified", "schema" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L182-L189
train
smnorris/pgdata
pgdata/database.py
Database.create_table
def create_table(self, table, columns): """Creates a table """ schema, table = self.parse_table_name(table) table = self._valid_table_name(table) if not schema: schema = self.schema if table in self.tables: return Table(self, schema, table) ...
python
def create_table(self, table, columns): """Creates a table """ schema, table = self.parse_table_name(table) table = self._valid_table_name(table) if not schema: schema = self.schema if table in self.tables: return Table(self, schema, table) ...
[ "def", "create_table", "(", "self", ",", "table", ",", "columns", ")", ":", "schema", ",", "table", "=", "self", ".", "parse_table_name", "(", "table", ")", "table", "=", "self", ".", "_valid_table_name", "(", "table", ")", "if", "not", "schema", ":", ...
Creates a table
[ "Creates", "a", "table" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L197-L207
train
smnorris/pgdata
pgdata/database.py
Database.ogr2pg
def ogr2pg( self, in_file, in_layer=None, out_layer=None, schema="public", s_srs=None, t_srs="EPSG:3005", sql=None, dim=2, cmd_only=False, index=True ): """ Load a layer to provided pgdata database connection usi...
python
def ogr2pg( self, in_file, in_layer=None, out_layer=None, schema="public", s_srs=None, t_srs="EPSG:3005", sql=None, dim=2, cmd_only=False, index=True ): """ Load a layer to provided pgdata database connection usi...
[ "def", "ogr2pg", "(", "self", ",", "in_file", ",", "in_layer", "=", "None", ",", "out_layer", "=", "None", ",", "schema", "=", "\"public\"", ",", "s_srs", "=", "None", ",", "t_srs", "=", "\"EPSG:3005\"", ",", "sql", "=", "None", ",", "dim", "=", "2",...
Load a layer to provided pgdata database connection using OGR2OGR -sql option is like an ESRI where_clause or the ogr2ogr -where option, but to increase flexibility, it is in SQLITE dialect: SELECT * FROM <in_layer> WHERE <sql>
[ "Load", "a", "layer", "to", "provided", "pgdata", "database", "connection", "using", "OGR2OGR" ]
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L209-L284
train
smnorris/pgdata
pgdata/database.py
Database.pg2ogr
def pg2ogr( self, sql, driver, outfile, outlayer=None, column_remap=None, s_srs="EPSG:3005", t_srs=None, geom_type=None, append=False, ): """ A wrapper around ogr2ogr, for quickly dumping a postgis query to file. ...
python
def pg2ogr( self, sql, driver, outfile, outlayer=None, column_remap=None, s_srs="EPSG:3005", t_srs=None, geom_type=None, append=False, ): """ A wrapper around ogr2ogr, for quickly dumping a postgis query to file. ...
[ "def", "pg2ogr", "(", "self", ",", "sql", ",", "driver", ",", "outfile", ",", "outlayer", "=", "None", ",", "column_remap", "=", "None", ",", "s_srs", "=", "\"EPSG:3005\"", ",", "t_srs", "=", "None", ",", "geom_type", "=", "None", ",", "append", "=", ...
A wrapper around ogr2ogr, for quickly dumping a postgis query to file. Suppported formats are ["ESRI Shapefile", "GeoJSON", "FileGDB", "GPKG"] - for GeoJSON, transforms to EPSG:4326 - for Shapefile, consider supplying a column_remap dict - for FileGDB, geom_type is required ...
[ "A", "wrapper", "around", "ogr2ogr", "for", "quickly", "dumping", "a", "postgis", "query", "to", "file", ".", "Suppported", "formats", "are", "[", "ESRI", "Shapefile", "GeoJSON", "FileGDB", "GPKG", "]", "-", "for", "GeoJSON", "transforms", "to", "EPSG", ":",...
8b0294024d5ef30b4ae9184888e2cc7004d1784e
https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/database.py#L286-L391
train
letuananh/chirptext
chirptext/cli.py
setup_logging
def setup_logging(filename, log_dir=None, force_setup=False): ''' Try to load logging configuration from a file. Set level to INFO if failed. ''' if not force_setup and ChirpCLI.SETUP_COMPLETED: logging.debug("Master logging has been setup. This call will be ignored.") return if log_dir ...
python
def setup_logging(filename, log_dir=None, force_setup=False): ''' Try to load logging configuration from a file. Set level to INFO if failed. ''' if not force_setup and ChirpCLI.SETUP_COMPLETED: logging.debug("Master logging has been setup. This call will be ignored.") return if log_dir ...
[ "def", "setup_logging", "(", "filename", ",", "log_dir", "=", "None", ",", "force_setup", "=", "False", ")", ":", "if", "not", "force_setup", "and", "ChirpCLI", ".", "SETUP_COMPLETED", ":", "logging", ".", "debug", "(", "\"Master logging has been setup. This call ...
Try to load logging configuration from a file. Set level to INFO if failed.
[ "Try", "to", "load", "logging", "configuration", "from", "a", "file", ".", "Set", "level", "to", "INFO", "if", "failed", "." ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L35-L55
train
letuananh/chirptext
chirptext/cli.py
config_logging
def config_logging(args): ''' Override root logger's level ''' if args.quiet: logging.getLogger().setLevel(logging.CRITICAL) elif args.verbose: logging.getLogger().setLevel(logging.DEBUG)
python
def config_logging(args): ''' Override root logger's level ''' if args.quiet: logging.getLogger().setLevel(logging.CRITICAL) elif args.verbose: logging.getLogger().setLevel(logging.DEBUG)
[ "def", "config_logging", "(", "args", ")", ":", "if", "args", ".", "quiet", ":", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")", "elif", "args", ".", "verbose", ":", "logging", ".", "getLogger", "(", ")", ...
Override root logger's level
[ "Override", "root", "logger", "s", "level" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L58-L63
train
letuananh/chirptext
chirptext/cli.py
CLIApp.add_task
def add_task(self, task, func=None, **kwargs): ''' Add a task parser ''' if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = self.__tasks.add_par...
python
def add_task(self, task, func=None, **kwargs): ''' Add a task parser ''' if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = self.__tasks.add_par...
[ "def", "add_task", "(", "self", ",", "task", ",", "func", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "__tasks", ":", "raise", "Exception", "(", "\"Tasks subparsers is disabled\"", ")", "if", "'help'", "not", "in", "kwargs",...
Add a task parser
[ "Add", "a", "task", "parser" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L92-L104
train
letuananh/chirptext
chirptext/cli.py
CLIApp.add_vq
def add_vq(self, parser): ''' Add verbose & quiet options ''' group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true")
python
def add_vq(self, parser): ''' Add verbose & quiet options ''' group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true")
[ "def", "add_vq", "(", "self", ",", "parser", ")", ":", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "group", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ")", "group", ".", "add_arg...
Add verbose & quiet options
[ "Add", "verbose", "&", "quiet", "options" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L106-L110
train
letuananh/chirptext
chirptext/cli.py
CLIApp.add_version_func
def add_version_func(self, show_version): ''' Enable --version and -V to show version information ''' if callable(show_version): self.__show_version_func = show_version else: self.__show_version_func = lambda cli, args: print(show_version) self.parser.add_argument...
python
def add_version_func(self, show_version): ''' Enable --version and -V to show version information ''' if callable(show_version): self.__show_version_func = show_version else: self.__show_version_func = lambda cli, args: print(show_version) self.parser.add_argument...
[ "def", "add_version_func", "(", "self", ",", "show_version", ")", ":", "if", "callable", "(", "show_version", ")", ":", "self", ".", "__show_version_func", "=", "show_version", "else", ":", "self", ".", "__show_version_func", "=", "lambda", "cli", ",", "args",...
Enable --version and -V to show version information
[ "Enable", "--", "version", "and", "-", "V", "to", "show", "version", "information" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L112-L118
train
letuananh/chirptext
chirptext/cli.py
CLIApp.logger
def logger(self): ''' Lazy logger ''' if self.__logger is None: self.__logger = logging.getLogger(self.__name) return self.__logger
python
def logger(self): ''' Lazy logger ''' if self.__logger is None: self.__logger = logging.getLogger(self.__name) return self.__logger
[ "def", "logger", "(", "self", ")", ":", "if", "self", ".", "__logger", "is", "None", ":", "self", ".", "__logger", "=", "logging", ".", "getLogger", "(", "self", ".", "__name", ")", "return", "self", ".", "__logger" ]
Lazy logger
[ "Lazy", "logger" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L121-L125
train
letuananh/chirptext
chirptext/cli.py
CLIApp.run
def run(self, func=None): ''' Run the app ''' args = self.parser.parse_args() if self.__add_vq is not None and self.__config_logging: self.__config_logging(args) if self.__show_version_func and args.version and callable(self.__show_version_func): self.__show_versi...
python
def run(self, func=None): ''' Run the app ''' args = self.parser.parse_args() if self.__add_vq is not None and self.__config_logging: self.__config_logging(args) if self.__show_version_func and args.version and callable(self.__show_version_func): self.__show_versi...
[ "def", "run", "(", "self", ",", "func", "=", "None", ")", ":", "args", "=", "self", ".", "parser", ".", "parse_args", "(", ")", "if", "self", ".", "__add_vq", "is", "not", "None", "and", "self", ".", "__config_logging", ":", "self", ".", "__config_lo...
Run the app
[ "Run", "the", "app" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/cli.py#L127-L139
train
letuananh/chirptext
chirptext/leutile.py
header
def header(*msg, level='h1', separator=" ", print_out=print): ''' Print header block in text mode ''' out_string = separator.join(str(x) for x in msg) if level == 'h0': # box_len = 80 if len(msg) < 80 else len(msg) box_len = 80 print_out('+' + '-' * (box_len + 2)) print_o...
python
def header(*msg, level='h1', separator=" ", print_out=print): ''' Print header block in text mode ''' out_string = separator.join(str(x) for x in msg) if level == 'h0': # box_len = 80 if len(msg) < 80 else len(msg) box_len = 80 print_out('+' + '-' * (box_len + 2)) print_o...
[ "def", "header", "(", "*", "msg", ",", "level", "=", "'h1'", ",", "separator", "=", "\" \"", ",", "print_out", "=", "print", ")", ":", "out_string", "=", "separator", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "msg", ")", "if", "le...
Print header block in text mode
[ "Print", "header", "block", "in", "text", "mode" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L49-L68
train
letuananh/chirptext
chirptext/leutile.py
piter.fetch
def fetch(self, value_obj=None): ''' Fetch the next two values ''' val = None try: val = next(self.__iterable) except StopIteration: return None if value_obj is None: value_obj = Value(value=val) else: value_obj.value = val ...
python
def fetch(self, value_obj=None): ''' Fetch the next two values ''' val = None try: val = next(self.__iterable) except StopIteration: return None if value_obj is None: value_obj = Value(value=val) else: value_obj.value = val ...
[ "def", "fetch", "(", "self", ",", "value_obj", "=", "None", ")", ":", "val", "=", "None", "try", ":", "val", "=", "next", "(", "self", ".", "__iterable", ")", "except", "StopIteration", ":", "return", "None", "if", "value_obj", "is", "None", ":", "va...
Fetch the next two values
[ "Fetch", "the", "next", "two", "values" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L109-L120
train
letuananh/chirptext
chirptext/leutile.py
Counter.get_report_order
def get_report_order(self): ''' Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count ''' order_list = [] for x in self.__priority: order_list.append([x, self[x]]) for x in sorted(list(self.keys())): ...
python
def get_report_order(self): ''' Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count ''' order_list = [] for x in self.__priority: order_list.append([x, self[x]]) for x in sorted(list(self.keys())): ...
[ "def", "get_report_order", "(", "self", ")", ":", "order_list", "=", "[", "]", "for", "x", "in", "self", ".", "__priority", ":", "order_list", ".", "append", "(", "[", "x", ",", "self", "[", "x", "]", "]", ")", "for", "x", "in", "sorted", "(", "l...
Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count
[ "Keys", "are", "sorted", "based", "on", "report", "order", "(", "i", ".", "e", ".", "some", "keys", "to", "be", "shown", "first", ")", "Related", ":", "see", "sorted_by_count" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L157-L167
train
letuananh/chirptext
chirptext/leutile.py
TextReport.content
def content(self): ''' Return report content as a string if mode == STRINGIO else an empty string ''' if isinstance(self.__report_file, io.StringIO): return self.__report_file.getvalue() else: return ''
python
def content(self): ''' Return report content as a string if mode == STRINGIO else an empty string ''' if isinstance(self.__report_file, io.StringIO): return self.__report_file.getvalue() else: return ''
[ "def", "content", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__report_file", ",", "io", ".", "StringIO", ")", ":", "return", "self", ".", "__report_file", ".", "getvalue", "(", ")", "else", ":", "return", "''" ]
Return report content as a string if mode == STRINGIO else an empty string
[ "Return", "report", "content", "as", "a", "string", "if", "mode", "==", "STRINGIO", "else", "an", "empty", "string" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L317-L322
train
letuananh/chirptext
chirptext/leutile.py
Table.format
def format(self): ''' Format table to print out ''' self.max_lengths = [] for row in self.rows: if len(self.max_lengths) < len(row): self.max_lengths += [0] * (len(row) - len(self.max_lengths)) for idx, val in enumerate(row): len_ce...
python
def format(self): ''' Format table to print out ''' self.max_lengths = [] for row in self.rows: if len(self.max_lengths) < len(row): self.max_lengths += [0] * (len(row) - len(self.max_lengths)) for idx, val in enumerate(row): len_ce...
[ "def", "format", "(", "self", ")", ":", "self", ".", "max_lengths", "=", "[", "]", "for", "row", "in", "self", ".", "rows", ":", "if", "len", "(", "self", ".", "max_lengths", ")", "<", "len", "(", "row", ")", ":", "self", ".", "max_lengths", "+="...
Format table to print out
[ "Format", "table", "to", "print", "out" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L446-L457
train
letuananh/chirptext
chirptext/leutile.py
FileHelper.getfullfilename
def getfullfilename(file_path): ''' Get full filename (with extension) ''' warnings.warn("getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead", DeprecationWarning) if file_path: return os.path.basename(file_path) e...
python
def getfullfilename(file_path): ''' Get full filename (with extension) ''' warnings.warn("getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead", DeprecationWarning) if file_path: return os.path.basename(file_path) e...
[ "def", "getfullfilename", "(", "file_path", ")", ":", "warnings", ".", "warn", "(", "\"getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead\"", ",", "DeprecationWarning", ")", "if", "file_path", ":", "return", "os", ".", "p...
Get full filename (with extension)
[ "Get", "full", "filename", "(", "with", "extension", ")" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L499-L506
train
letuananh/chirptext
chirptext/leutile.py
FileHelper.replace_ext
def replace_ext(file_path, ext): ''' Change extension of a file_path to something else (provide None to remove) ''' if not file_path: raise Exception("File path cannot be empty") dirname = os.path.dirname(file_path) filename = FileHelper.getfilename(file_path) if ext:...
python
def replace_ext(file_path, ext): ''' Change extension of a file_path to something else (provide None to remove) ''' if not file_path: raise Exception("File path cannot be empty") dirname = os.path.dirname(file_path) filename = FileHelper.getfilename(file_path) if ext:...
[ "def", "replace_ext", "(", "file_path", ",", "ext", ")", ":", "if", "not", "file_path", ":", "raise", "Exception", "(", "\"File path cannot be empty\"", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "file_path", ")", "filename", "=", "FileHelp...
Change extension of a file_path to something else (provide None to remove)
[ "Change", "extension", "of", "a", "file_path", "to", "something", "else", "(", "provide", "None", "to", "remove", ")" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L509-L517
train
letuananh/chirptext
chirptext/leutile.py
FileHelper.replace_name
def replace_name(file_path, new_name): ''' Change the file name in a path but keep the extension ''' if not file_path: raise Exception("File path cannot be empty") elif not new_name: raise Exception("New name cannot be empty") dirname = os.path.dirname(file_path) ...
python
def replace_name(file_path, new_name): ''' Change the file name in a path but keep the extension ''' if not file_path: raise Exception("File path cannot be empty") elif not new_name: raise Exception("New name cannot be empty") dirname = os.path.dirname(file_path) ...
[ "def", "replace_name", "(", "file_path", ",", "new_name", ")", ":", "if", "not", "file_path", ":", "raise", "Exception", "(", "\"File path cannot be empty\"", ")", "elif", "not", "new_name", ":", "raise", "Exception", "(", "\"New name cannot be empty\"", ")", "dir...
Change the file name in a path but keep the extension
[ "Change", "the", "file", "name", "in", "a", "path", "but", "keep", "the", "extension" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L520-L528
train
letuananh/chirptext
chirptext/leutile.py
FileHelper.get_child_folders
def get_child_folders(path): ''' Get all child folders of a folder ''' path = FileHelper.abspath(path) return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))]
python
def get_child_folders(path): ''' Get all child folders of a folder ''' path = FileHelper.abspath(path) return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))]
[ "def", "get_child_folders", "(", "path", ")", ":", "path", "=", "FileHelper", ".", "abspath", "(", "path", ")", "return", "[", "dirname", "for", "dirname", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os"...
Get all child folders of a folder
[ "Get", "all", "child", "folders", "of", "a", "folder" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L544-L547
train
letuananh/chirptext
chirptext/leutile.py
FileHelper.get_child_files
def get_child_files(path): ''' Get all child files of a folder ''' path = FileHelper.abspath(path) return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]
python
def get_child_files(path): ''' Get all child files of a folder ''' path = FileHelper.abspath(path) return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]
[ "def", "get_child_files", "(", "path", ")", ":", "path", "=", "FileHelper", ".", "abspath", "(", "path", ")", "return", "[", "filename", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isfile", "(", "os...
Get all child files of a folder
[ "Get", "all", "child", "files", "of", "a", "folder" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L550-L553
train
letuananh/chirptext
chirptext/leutile.py
FileHelper.remove_file
def remove_file(filepath): ''' Delete a file ''' try: os.remove(os.path.abspath(os.path.expanduser(filepath))) except OSError as e: if e.errno != errno.ENOENT: raise
python
def remove_file(filepath): ''' Delete a file ''' try: os.remove(os.path.abspath(os.path.expanduser(filepath))) except OSError as e: if e.errno != errno.ENOENT: raise
[ "def", "remove_file", "(", "filepath", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filepath", ")", ")", ")", "except", "OSError", "as", "e", ":", "if", "e", "...
Delete a file
[ "Delete", "a", "file" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L556-L562
train
letuananh/chirptext
chirptext/leutile.py
AppConfig._ptn2fn
def _ptn2fn(self, pattern): ''' Pattern to filename ''' return [pattern.format(wd=self.working_dir, n=self.__name, mode=self.__mode), pattern.format(wd=self.working_dir, n='{}.{}'.format(self.__name, self.__mode), mode=self.__mode)]
python
def _ptn2fn(self, pattern): ''' Pattern to filename ''' return [pattern.format(wd=self.working_dir, n=self.__name, mode=self.__mode), pattern.format(wd=self.working_dir, n='{}.{}'.format(self.__name, self.__mode), mode=self.__mode)]
[ "def", "_ptn2fn", "(", "self", ",", "pattern", ")", ":", "return", "[", "pattern", ".", "format", "(", "wd", "=", "self", ".", "working_dir", ",", "n", "=", "self", ".", "__name", ",", "mode", "=", "self", ".", "__mode", ")", ",", "pattern", ".", ...
Pattern to filename
[ "Pattern", "to", "filename" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L601-L604
train
letuananh/chirptext
chirptext/leutile.py
AppConfig.add_potential
def add_potential(self, *patterns): ''' Add a potential config file pattern ''' for ptn in patterns: self.__potential.extend(self._ptn2fn(ptn))
python
def add_potential(self, *patterns): ''' Add a potential config file pattern ''' for ptn in patterns: self.__potential.extend(self._ptn2fn(ptn))
[ "def", "add_potential", "(", "self", ",", "*", "patterns", ")", ":", "for", "ptn", "in", "patterns", ":", "self", ".", "__potential", ".", "extend", "(", "self", ".", "_ptn2fn", "(", "ptn", ")", ")" ]
Add a potential config file pattern
[ "Add", "a", "potential", "config", "file", "pattern" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L606-L609
train
letuananh/chirptext
chirptext/leutile.py
AppConfig.locate_config
def locate_config(self): ''' Locate config file ''' for f in self.__potential: f = FileHelper.abspath(f) if os.path.isfile(f): return f return None
python
def locate_config(self): ''' Locate config file ''' for f in self.__potential: f = FileHelper.abspath(f) if os.path.isfile(f): return f return None
[ "def", "locate_config", "(", "self", ")", ":", "for", "f", "in", "self", ".", "__potential", ":", "f", "=", "FileHelper", ".", "abspath", "(", "f", ")", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", ":", "return", "f", "return", "None" ]
Locate config file
[ "Locate", "config", "file" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L611-L617
train
letuananh/chirptext
chirptext/leutile.py
AppConfig.config
def config(self): ''' Read config automatically if required ''' if self.__config is None: config_path = self.locate_config() if config_path: self.__config = self.read_file(config_path) self.__config_path = config_path return self.__config
python
def config(self): ''' Read config automatically if required ''' if self.__config is None: config_path = self.locate_config() if config_path: self.__config = self.read_file(config_path) self.__config_path = config_path return self.__config
[ "def", "config", "(", "self", ")", ":", "if", "self", ".", "__config", "is", "None", ":", "config_path", "=", "self", ".", "locate_config", "(", ")", "if", "config_path", ":", "self", ".", "__config", "=", "self", ".", "read_file", "(", "config_path", ...
Read config automatically if required
[ "Read", "config", "automatically", "if", "required" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L620-L627
train
letuananh/chirptext
chirptext/leutile.py
AppConfig.read_file
def read_file(self, file_path): ''' Read a configuration file and return configuration data ''' getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path)) if self.__mode == AppConfig.JSON: return json.loads(FileHelper.read(file_path), object_pairs_hook=Ord...
python
def read_file(self, file_path): ''' Read a configuration file and return configuration data ''' getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path)) if self.__mode == AppConfig.JSON: return json.loads(FileHelper.read(file_path), object_pairs_hook=Ord...
[ "def", "read_file", "(", "self", ",", "file_path", ")", ":", "getLogger", "(", ")", ".", "info", "(", "\"Loading app config from {} file: {}\"", ".", "format", "(", "self", ".", "__mode", ",", "file_path", ")", ")", "if", "self", ".", "__mode", "==", "AppC...
Read a configuration file and return configuration data
[ "Read", "a", "configuration", "file", "and", "return", "configuration", "data" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L629-L637
train
letuananh/chirptext
chirptext/leutile.py
AppConfig.load
def load(self, file_path): ''' Load configuration from a specific file ''' self.clear() self.__config = self.read_file(file_path)
python
def load(self, file_path): ''' Load configuration from a specific file ''' self.clear() self.__config = self.read_file(file_path)
[ "def", "load", "(", "self", ",", "file_path", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "__config", "=", "self", ".", "read_file", "(", "file_path", ")" ]
Load configuration from a specific file
[ "Load", "configuration", "from", "a", "specific", "file" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L639-L642
train
alefnula/tea
tea/process/wrapper.py
get_processes
def get_processes(sort_by_name=True): """Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuple...
python
def get_processes(sort_by_name=True): """Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuple...
[ "def", "get_processes", "(", "sort_by_name", "=", "True", ")", ":", "if", "sort_by_name", ":", "return", "sorted", "(", "_list_processes", "(", ")", ",", "key", "=", "cmp_to_key", "(", "lambda", "p1", ",", "p2", ":", "(", "cmp", "(", "p1", ".", "name",...
Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuples.
[ "Retrieve", "a", "list", "of", "processes", "sorted", "by", "name", ".", "Args", ":", "sort_by_name", "(", "bool", ")", ":", "Sort", "the", "list", "by", "name", "or", "by", "process", "ID", "s", ".", "Returns", ":", "list", "of", "(", "int", "str", ...
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/process/wrapper.py#L36-L59
train
alefnula/tea
tea/process/wrapper.py
find
def find(name, arg=None): """Find process by name or by argument in command line. Args: name (str): Process name to search for. arg (str): Command line argument for a process to search for. Returns: tea.process.base.IProcess: Process object if found. """ for p in ...
python
def find(name, arg=None): """Find process by name or by argument in command line. Args: name (str): Process name to search for. arg (str): Command line argument for a process to search for. Returns: tea.process.base.IProcess: Process object if found. """ for p in ...
[ "def", "find", "(", "name", ",", "arg", "=", "None", ")", ":", "for", "p", "in", "get_processes", "(", ")", ":", "if", "p", ".", "name", ".", "lower", "(", ")", ".", "find", "(", "name", ".", "lower", "(", ")", ")", "!=", "-", "1", ":", "if...
Find process by name or by argument in command line. Args: name (str): Process name to search for. arg (str): Command line argument for a process to search for. Returns: tea.process.base.IProcess: Process object if found.
[ "Find", "process", "by", "name", "or", "by", "argument", "in", "command", "line", ".", "Args", ":", "name", "(", "str", ")", ":", "Process", "name", "to", "search", "for", ".", "arg", "(", "str", ")", ":", "Command", "line", "argument", "for", "a", ...
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/process/wrapper.py#L62-L80
train
alefnula/tea
tea/process/wrapper.py
execute
def execute(command, *args, **kwargs): """Execute a command with arguments and wait for output. Arguments should not be quoted! Keyword arguments: env (dict): Dictionary of additional environment variables. wait (bool): Wait for the process to finish. Example:: >>>...
python
def execute(command, *args, **kwargs): """Execute a command with arguments and wait for output. Arguments should not be quoted! Keyword arguments: env (dict): Dictionary of additional environment variables. wait (bool): Wait for the process to finish. Example:: >>>...
[ "def", "execute", "(", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wait", "=", "kwargs", ".", "pop", "(", "\"wait\"", ",", "True", ")", "process", "=", "Process", "(", "command", ",", "args", ",", "env", "=", "kwargs", ".", "...
Execute a command with arguments and wait for output. Arguments should not be quoted! Keyword arguments: env (dict): Dictionary of additional environment variables. wait (bool): Wait for the process to finish. Example:: >>> code = 'import sys;sys.stdout.write('out');sys...
[ "Execute", "a", "command", "with", "arguments", "and", "wait", "for", "output", ".", "Arguments", "should", "not", "be", "quoted!", "Keyword", "arguments", ":", "env", "(", "dict", ")", ":", "Dictionary", "of", "additional", "environment", "variables", ".", ...
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/process/wrapper.py#L83-L109
train
alefnula/tea
tea/process/wrapper.py
execute_and_report
def execute_and_report(command, *args, **kwargs): """Execute a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False. """ logging.info("Execute: %s %s" % (command, " ".join(args...
python
def execute_and_report(command, *args, **kwargs): """Execute a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False. """ logging.info("Execute: %s %s" % (command, " ".join(args...
[ "def", "execute_and_report", "(", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "info", "(", "\"Execute: %s %s\"", "%", "(", "command", ",", "\" \"", ".", "join", "(", "args", ")", ")", ")", "try", ":", "status", ","...
Execute a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False.
[ "Execute", "a", "command", "with", "arguments", "and", "wait", "for", "output", ".", "If", "execution", "was", "successful", "function", "will", "return", "True", "if", "not", "it", "will", "log", "the", "output", "using", "standard", "logging", "and", "retu...
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/process/wrapper.py#L112-L152
train
jonhadfield/creds
lib/creds/ssh.py
read_authorized_keys
def read_authorized_keys(username=None): """Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user. """ authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.for...
python
def read_authorized_keys(username=None): """Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user. """ authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.for...
[ "def", "read_authorized_keys", "(", "username", "=", "None", ")", ":", "authorized_keys_path", "=", "'{0}/.ssh/authorized_keys'", ".", "format", "(", "os", ".", "path", ".", "expanduser", "(", "'~{0}'", ".", "format", "(", "username", ")", ")", ")", "rnd_chars...
Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user.
[ "Read", "public", "keys", "from", "specified", "user", "s", "authorized_keys", "file", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/ssh.py#L63-L87
train
jonhadfield/creds
lib/creds/ssh.py
write_authorized_keys
def write_authorized_keys(user=None): """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user. """ authorized_keys = list() a...
python
def write_authorized_keys(user=None): """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user. """ authorized_keys = list() a...
[ "def", "write_authorized_keys", "(", "user", "=", "None", ")", ":", "authorized_keys", "=", "list", "(", ")", "authorized_keys_dir", "=", "'{0}/.ssh'", ".", "format", "(", "os", ".", "path", ".", "expanduser", "(", "'~{0}'", ".", "format", "(", "user", "."...
Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user.
[ "Write", "public", "keys", "back", "to", "authorized_keys", "file", ".", "Create", "keys", "directory", "if", "it", "doesn", "t", "already", "exist", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/ssh.py#L90-L116
train
jonhadfield/creds
lib/creds/ssh.py
PublicKey.b64encoded
def b64encoded(self): """Return a base64 encoding of the key. returns: str: base64 encoding of the public key """ if self._b64encoded: return text_type(self._b64encoded).strip("\r\n") else: return base64encode(self.raw)
python
def b64encoded(self): """Return a base64 encoding of the key. returns: str: base64 encoding of the public key """ if self._b64encoded: return text_type(self._b64encoded).strip("\r\n") else: return base64encode(self.raw)
[ "def", "b64encoded", "(", "self", ")", ":", "if", "self", ".", "_b64encoded", ":", "return", "text_type", "(", "self", ".", "_b64encoded", ")", ".", "strip", "(", "\"\\r\\n\"", ")", "else", ":", "return", "base64encode", "(", "self", ".", "raw", ")" ]
Return a base64 encoding of the key. returns: str: base64 encoding of the public key
[ "Return", "a", "base64", "encoding", "of", "the", "key", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/ssh.py#L31-L40
train
jonhadfield/creds
lib/creds/ssh.py
PublicKey.raw
def raw(self): """Return raw key. returns: str: raw key """ if self._raw: return text_type(self._raw).strip("\r\n") else: return text_type(base64decode(self._b64encoded)).strip("\r\n")
python
def raw(self): """Return raw key. returns: str: raw key """ if self._raw: return text_type(self._raw).strip("\r\n") else: return text_type(base64decode(self._b64encoded)).strip("\r\n")
[ "def", "raw", "(", "self", ")", ":", "if", "self", ".", "_raw", ":", "return", "text_type", "(", "self", ".", "_raw", ")", ".", "strip", "(", "\"\\r\\n\"", ")", "else", ":", "return", "text_type", "(", "base64decode", "(", "self", ".", "_b64encoded", ...
Return raw key. returns: str: raw key
[ "Return", "raw", "key", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/ssh.py#L43-L52
train
night-crawler/django-docker-helpers
django_docker_helpers/config/backends/consul_parser.py
ConsulParser.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.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exis...
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.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exis...
[ "def", "inner_parser", "(", "self", ")", "->", "BaseParser", ":", "if", "self", ".", "_inner_parser", "is", "not", "None", ":", "return", "self", ".", "_inner_parser", "__index", ",", "response_config", "=", "self", ".", "client", ".", "kv", ".", "get", ...
Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exists :raises config.exceptions.KVStorageValueIsEmpt...
[ "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/consul_parser.py#L80-L108
train
night-crawler/django-docker-helpers
django_docker_helpers/config/backends/consul_parser.py
ConsulParser.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, **kwargs): """ Reads a value of ``variable_path`` from consul kv storage. :param varia...
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, **kwargs): """ Reads a value of ``variable_path`` from consul kv storage. :param varia...
[ "def", "get", "(", "self", ",", "variable_path", ":", "str", ",", "default", ":", "t", ".", "Optional", "[", "t", ".", "Any", "]", "=", "None", ",", "coerce_type", ":", "t", ".", "Optional", "[", "t", ".", "Type", "]", "=", "None", ",", "coercer"...
Reads a value of ``variable_path`` from consul kv storage. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type...
[ "Reads", "a", "value", "of", "variable_path", "from", "consul", "kv", "storage", "." ]
b64f8009101a8eb61d3841124ba19e3ab881aa2f
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/consul_parser.py#L110-L137
train
hufman/flask_rdf
flask_rdf/format.py
add_format
def add_format(mimetype, format, requires_context=False): """ Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph """ ...
python
def add_format(mimetype, format, requires_context=False): """ Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph """ ...
[ "def", "add_format", "(", "mimetype", ",", "format", ",", "requires_context", "=", "False", ")", ":", "global", "formats", "global", "ctxless_mimetypes", "global", "all_mimetypes", "formats", "[", "mimetype", "]", "=", "format", "if", "not", "requires_context", ...
Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph
[ "Registers", "a", "new", "format", "to", "be", "used", "in", "a", "graph", "s", "serialize", "call", "If", "you", "ve", "installed", "an", "rdflib", "serializer", "plugin", "use", "this", "to", "add", "it", "to", "the", "content", "negotiation", "system", ...
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L135-L147
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.add_format
def add_format(self, mimetype, format, requires_context=False): """ Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware gr...
python
def add_format(self, mimetype, format, requires_context=False): """ Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware gr...
[ "def", "add_format", "(", "self", ",", "mimetype", ",", "format", ",", "requires_context", "=", "False", ")", ":", "self", ".", "formats", "[", "mimetype", "]", "=", "format", "if", "not", "requires_context", ":", "self", ".", "ctxless_mimetypes", ".", "ap...
Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph
[ "Registers", "a", "new", "format", "to", "be", "used", "in", "a", "graph", "s", "serialize", "call", "If", "you", "ve", "installed", "an", "rdflib", "serializer", "plugin", "use", "this", "to", "add", "it", "to", "the", "content", "negotiation", "system", ...
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L42-L51
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.get_default_mimetype
def get_default_mimetype(self): """ Returns the default mimetype """ mimetype = self.default_mimetype if mimetype is None: # class inherits from module default mimetype = DEFAULT_MIMETYPE if mimetype is None: # module is set to None? mimetype = 'application/rdf+xml' return mimetype
python
def get_default_mimetype(self): """ Returns the default mimetype """ mimetype = self.default_mimetype if mimetype is None: # class inherits from module default mimetype = DEFAULT_MIMETYPE if mimetype is None: # module is set to None? mimetype = 'application/rdf+xml' return mimetype
[ "def", "get_default_mimetype", "(", "self", ")", ":", "mimetype", "=", "self", ".", "default_mimetype", "if", "mimetype", "is", "None", ":", "# class inherits from module default", "mimetype", "=", "DEFAULT_MIMETYPE", "if", "mimetype", "is", "None", ":", "# module i...
Returns the default mimetype
[ "Returns", "the", "default", "mimetype" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L53-L60
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.get_wildcard_mimetype
def get_wildcard_mimetype(self): """ Returns the mimetype if the client sends */* """ mimetype = self.wildcard_mimetype if mimetype is None: # class inherits from module default mimetype = WILDCARD_MIMETYPE if mimetype is None: # module is set to None? mimetype = 'application/rdf+xml' return mimetype
python
def get_wildcard_mimetype(self): """ Returns the mimetype if the client sends */* """ mimetype = self.wildcard_mimetype if mimetype is None: # class inherits from module default mimetype = WILDCARD_MIMETYPE if mimetype is None: # module is set to None? mimetype = 'application/rdf+xml' return mimetype
[ "def", "get_wildcard_mimetype", "(", "self", ")", ":", "mimetype", "=", "self", ".", "wildcard_mimetype", "if", "mimetype", "is", "None", ":", "# class inherits from module default", "mimetype", "=", "WILDCARD_MIMETYPE", "if", "mimetype", "is", "None", ":", "# modul...
Returns the mimetype if the client sends */*
[ "Returns", "the", "mimetype", "if", "the", "client", "sends", "*", "/", "*" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L62-L69
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.decide_mimetype
def decide_mimetype(self, accepts, context_aware = False): """ Returns what mimetype the client wants to receive Parses the given Accept header and returns the best one that we know how to output An empty Accept will default to application/rdf+xml An Accept with */* use rdf+xml unless a better...
python
def decide_mimetype(self, accepts, context_aware = False): """ Returns what mimetype the client wants to receive Parses the given Accept header and returns the best one that we know how to output An empty Accept will default to application/rdf+xml An Accept with */* use rdf+xml unless a better...
[ "def", "decide_mimetype", "(", "self", ",", "accepts", ",", "context_aware", "=", "False", ")", ":", "mimetype", "=", "None", "# If the client didn't request a thing, use default", "if", "accepts", "is", "None", "or", "accepts", ".", "strip", "(", ")", "==", "''...
Returns what mimetype the client wants to receive Parses the given Accept header and returns the best one that we know how to output An empty Accept will default to application/rdf+xml An Accept with */* use rdf+xml unless a better match is found An Accept that doesn't match anything will ...
[ "Returns", "what", "mimetype", "the", "client", "wants", "to", "receive", "Parses", "the", "given", "Accept", "header", "and", "returns", "the", "best", "one", "that", "we", "know", "how", "to", "output", "An", "empty", "Accept", "will", "default", "to", "...
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L71-L97
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.get_serialize_format
def get_serialize_format(self, mimetype): """ Get the serialization format for the given mimetype """ format = self.formats.get(mimetype, None) if format is None: format = formats.get(mimetype, None) return format
python
def get_serialize_format(self, mimetype): """ Get the serialization format for the given mimetype """ format = self.formats.get(mimetype, None) if format is None: format = formats.get(mimetype, None) return format
[ "def", "get_serialize_format", "(", "self", ",", "mimetype", ")", ":", "format", "=", "self", ".", "formats", ".", "get", "(", "mimetype", ",", "None", ")", "if", "format", "is", "None", ":", "format", "=", "formats", ".", "get", "(", "mimetype", ",", ...
Get the serialization format for the given mimetype
[ "Get", "the", "serialization", "format", "for", "the", "given", "mimetype" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L99-L104
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.decide
def decide(self, accepts, context_aware=False): """ Returns what (mimetype,format) the client wants to receive Parses the given Accept header and picks the best one that we know how to output Returns (mimetype, format) An empty Accept will default to rdf+xml An Accept with */* use rdf+xm...
python
def decide(self, accepts, context_aware=False): """ Returns what (mimetype,format) the client wants to receive Parses the given Accept header and picks the best one that we know how to output Returns (mimetype, format) An empty Accept will default to rdf+xml An Accept with */* use rdf+xm...
[ "def", "decide", "(", "self", ",", "accepts", ",", "context_aware", "=", "False", ")", ":", "mimetype", "=", "self", ".", "decide_mimetype", "(", "accepts", ",", "context_aware", ")", "# return what format to serialize as", "if", "mimetype", "is", "not", "None",...
Returns what (mimetype,format) the client wants to receive Parses the given Accept header and picks the best one that we know how to output Returns (mimetype, format) An empty Accept will default to rdf+xml An Accept with */* use rdf+xml unless a better match is found An Accept that ...
[ "Returns", "what", "(", "mimetype", "format", ")", "the", "client", "wants", "to", "receive", "Parses", "the", "given", "Accept", "header", "and", "picks", "the", "best", "one", "that", "we", "know", "how", "to", "output", "Returns", "(", "mimetype", "form...
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L106-L122
train
hufman/flask_rdf
flask_rdf/format.py
FormatSelector.wants_rdf
def wants_rdf(self, accepts): """ Returns whether this client's Accept header indicates that the client wants to receive RDF """ mimetype = mimeparse.best_match(all_mimetypes + self.all_mimetypes + [WILDCARD], accepts) return mimetype and mimetype != WILDCARD
python
def wants_rdf(self, accepts): """ Returns whether this client's Accept header indicates that the client wants to receive RDF """ mimetype = mimeparse.best_match(all_mimetypes + self.all_mimetypes + [WILDCARD], accepts) return mimetype and mimetype != WILDCARD
[ "def", "wants_rdf", "(", "self", ",", "accepts", ")", ":", "mimetype", "=", "mimeparse", ".", "best_match", "(", "all_mimetypes", "+", "self", ".", "all_mimetypes", "+", "[", "WILDCARD", "]", ",", "accepts", ")", "return", "mimetype", "and", "mimetype", "!...
Returns whether this client's Accept header indicates that the client wants to receive RDF
[ "Returns", "whether", "this", "client", "s", "Accept", "header", "indicates", "that", "the", "client", "wants", "to", "receive", "RDF" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/format.py#L124-L129
train
OCHA-DAP/hdx-data-freshness
src/hdx/freshness/retry.py
send_http
async def send_http(session, method, url, *, retries=1, interval=1, backoff=2, http_status_codes_to_retry=HTTP_STATUS_CODES_TO_RETRY, fn=lambda x:x, **kwargs): """ Sends a HTTP request and imp...
python
async def send_http(session, method, url, *, retries=1, interval=1, backoff=2, http_status_codes_to_retry=HTTP_STATUS_CODES_TO_RETRY, fn=lambda x:x, **kwargs): """ Sends a HTTP request and imp...
[ "async", "def", "send_http", "(", "session", ",", "method", ",", "url", ",", "*", ",", "retries", "=", "1", ",", "interval", "=", "1", ",", "backoff", "=", "2", ",", "http_status_codes_to_retry", "=", "HTTP_STATUS_CODES_TO_RETRY", ",", "fn", "=", "lambda",...
Sends a HTTP request and implements a retry logic. Arguments: session (obj): A client aiohttp session object method (str): Method to use url (str): URL for the request retries (int): Number of times to retry in case of failure interval (float): Time to wait before retries ...
[ "Sends", "a", "HTTP", "request", "and", "implements", "a", "retry", "logic", "." ]
991152a5ec4c4a980a5378411db060b13730cad3
https://github.com/OCHA-DAP/hdx-data-freshness/blob/991152a5ec4c4a980a5378411db060b13730cad3/src/hdx/freshness/retry.py#L31-L106
train
dArignac/pelican-extended-sitemap
extended_sitemap/__init__.py
SitemapGenerator.generate_output
def generate_output(self, writer): """ Generates the sitemap file and the stylesheet file and puts them into the content dir. :param writer: the writer instance :type writer: pelican.writers.Writer """ # write xml stylesheet with codecs_open(os.path.join(os.path.d...
python
def generate_output(self, writer): """ Generates the sitemap file and the stylesheet file and puts them into the content dir. :param writer: the writer instance :type writer: pelican.writers.Writer """ # write xml stylesheet with codecs_open(os.path.join(os.path.d...
[ "def", "generate_output", "(", "self", ",", "writer", ")", ":", "# write xml stylesheet", "with", "codecs_open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'sitemap-stylesheet.xsl'", ")", ",", "...
Generates the sitemap file and the stylesheet file and puts them into the content dir. :param writer: the writer instance :type writer: pelican.writers.Writer
[ "Generates", "the", "sitemap", "file", "and", "the", "stylesheet", "file", "and", "puts", "them", "into", "the", "content", "dir", ".", ":", "param", "writer", ":", "the", "writer", "instance", ":", "type", "writer", ":", "pelican", ".", "writers", ".", ...
1cf7746c071c303db3b321955a91b3a78d9585f8
https://github.com/dArignac/pelican-extended-sitemap/blob/1cf7746c071c303db3b321955a91b3a78d9585f8/extended_sitemap/__init__.py#L86-L186
train
dArignac/pelican-extended-sitemap
extended_sitemap/__init__.py
SitemapGenerator.__get_direct_template_url
def __get_direct_template_url(self, name): """ Returns the URL for the given DIRECT_TEMPLATE name. Favors ${DIRECT_TEMPLATE}_SAVE_AS over the default path. :param name: name of the direct template :return: str """ url = self.pelican_settings.get('{}_SAVE_AS'.forma...
python
def __get_direct_template_url(self, name): """ Returns the URL for the given DIRECT_TEMPLATE name. Favors ${DIRECT_TEMPLATE}_SAVE_AS over the default path. :param name: name of the direct template :return: str """ url = self.pelican_settings.get('{}_SAVE_AS'.forma...
[ "def", "__get_direct_template_url", "(", "self", ",", "name", ")", ":", "url", "=", "self", ".", "pelican_settings", ".", "get", "(", "'{}_SAVE_AS'", ".", "format", "(", "name", ".", "upper", "(", ")", ")", ")", "if", "url", "is", "None", ":", "url", ...
Returns the URL for the given DIRECT_TEMPLATE name. Favors ${DIRECT_TEMPLATE}_SAVE_AS over the default path. :param name: name of the direct template :return: str
[ "Returns", "the", "URL", "for", "the", "given", "DIRECT_TEMPLATE", "name", ".", "Favors", "$", "{", "DIRECT_TEMPLATE", "}", "_SAVE_AS", "over", "the", "default", "path", ".", ":", "param", "name", ":", "name", "of", "the", "direct", "template", ":", "retur...
1cf7746c071c303db3b321955a91b3a78d9585f8
https://github.com/dArignac/pelican-extended-sitemap/blob/1cf7746c071c303db3b321955a91b3a78d9585f8/extended_sitemap/__init__.py#L188-L198
train
dArignac/pelican-extended-sitemap
extended_sitemap/__init__.py
SitemapGenerator.__process_url_wrapper_elements
def __process_url_wrapper_elements(self, elements): """ Creates the url nodes for pelican.urlwrappers.Category and pelican.urlwrappers.Tag. :param elements: list of wrapper elements :type elements: list :return: the processes urls as HTML :rtype: str """ u...
python
def __process_url_wrapper_elements(self, elements): """ Creates the url nodes for pelican.urlwrappers.Category and pelican.urlwrappers.Tag. :param elements: list of wrapper elements :type elements: list :return: the processes urls as HTML :rtype: str """ u...
[ "def", "__process_url_wrapper_elements", "(", "self", ",", "elements", ")", ":", "urls", "=", "''", "for", "url_wrapper", ",", "articles", "in", "elements", ":", "urls", "+=", "self", ".", "__create_url_node_for_content", "(", "url_wrapper", ",", "'others'", ","...
Creates the url nodes for pelican.urlwrappers.Category and pelican.urlwrappers.Tag. :param elements: list of wrapper elements :type elements: list :return: the processes urls as HTML :rtype: str
[ "Creates", "the", "url", "nodes", "for", "pelican", ".", "urlwrappers", ".", "Category", "and", "pelican", ".", "urlwrappers", ".", "Tag", ".", ":", "param", "elements", ":", "list", "of", "wrapper", "elements", ":", "type", "elements", ":", "list", ":", ...
1cf7746c071c303db3b321955a91b3a78d9585f8
https://github.com/dArignac/pelican-extended-sitemap/blob/1cf7746c071c303db3b321955a91b3a78d9585f8/extended_sitemap/__init__.py#L200-L216
train
dArignac/pelican-extended-sitemap
extended_sitemap/__init__.py
SitemapGenerator.__create_url_node_for_content
def __create_url_node_for_content(self, content, content_type, url=None, modification_time=None): """ Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of t...
python
def __create_url_node_for_content(self, content, content_type, url=None, modification_time=None): """ Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of t...
[ "def", "__create_url_node_for_content", "(", "self", ",", "content", ",", "content_type", ",", "url", "=", "None", ",", "modification_time", "=", "None", ")", ":", "loc", "=", "url", "if", "loc", "is", "None", ":", "loc", "=", "urljoin", "(", "self", "."...
Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of the given content to match settings.EXTENDED_SITEMAP_PLUGIN :type content_type; str :param url; if give...
[ "Creates", "the", "required", "<url", ">", "node", "for", "the", "sitemap", "xml", ".", ":", "param", "content", ":", "the", "content", "class", "to", "handle", ":", "type", "content", ":", "pelican", ".", "contents", ".", "Content", "|", "None", ":", ...
1cf7746c071c303db3b321955a91b3a78d9585f8
https://github.com/dArignac/pelican-extended-sitemap/blob/1cf7746c071c303db3b321955a91b3a78d9585f8/extended_sitemap/__init__.py#L218-L251
train
jonhadfield/creds
lib/creds/utils.py
get_missing_commands
def get_missing_commands(_platform): """Check I can identify the necessary commands for managing users.""" missing = list() if _platform in ('Linux', 'OpenBSD'): if not LINUX_CMD_USERADD: missing.append('useradd') if not LINUX_CMD_USERMOD: missing.append('usermod') ...
python
def get_missing_commands(_platform): """Check I can identify the necessary commands for managing users.""" missing = list() if _platform in ('Linux', 'OpenBSD'): if not LINUX_CMD_USERADD: missing.append('useradd') if not LINUX_CMD_USERMOD: missing.append('usermod') ...
[ "def", "get_missing_commands", "(", "_platform", ")", ":", "missing", "=", "list", "(", ")", "if", "_platform", "in", "(", "'Linux'", ",", "'OpenBSD'", ")", ":", "if", "not", "LINUX_CMD_USERADD", ":", "missing", ".", "append", "(", "'useradd'", ")", "if", ...
Check I can identify the necessary commands for managing users.
[ "Check", "I", "can", "identify", "the", "necessary", "commands", "for", "managing", "users", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L32-L52
train
jonhadfield/creds
lib/creds/utils.py
execute_command
def execute_command(command=None): """Execute a command and return the stdout and stderr.""" process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stdin = process.communicate() process.wait() return (stdout, stdin), process.returncode
python
def execute_command(command=None): """Execute a command and return the stdout and stderr.""" process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stdin = process.communicate() process.wait() return (stdout, stdin), process.returncode
[ "def", "execute_command", "(", "command", "=", "None", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "stdin", "=", ...
Execute a command and return the stdout and stderr.
[ "Execute", "a", "command", "and", "return", "the", "stdout", "and", "stderr", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L55-L60
train
jonhadfield/creds
lib/creds/utils.py
base64encode
def base64encode(_input=None): """Return base64 encoded representation of a string.""" if PY2: # pragma: no cover return base64.b64encode(_input) elif PY3: # pragma: no cover if isinstance(_input, bytes): return base64.b64encode(_input).decode('UTF-8') elif isinstance(_...
python
def base64encode(_input=None): """Return base64 encoded representation of a string.""" if PY2: # pragma: no cover return base64.b64encode(_input) elif PY3: # pragma: no cover if isinstance(_input, bytes): return base64.b64encode(_input).decode('UTF-8') elif isinstance(_...
[ "def", "base64encode", "(", "_input", "=", "None", ")", ":", "if", "PY2", ":", "# pragma: no cover", "return", "base64", ".", "b64encode", "(", "_input", ")", "elif", "PY3", ":", "# pragma: no cover", "if", "isinstance", "(", "_input", ",", "bytes", ")", "...
Return base64 encoded representation of a string.
[ "Return", "base64", "encoded", "representation", "of", "a", "string", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L69-L77
train
jonhadfield/creds
lib/creds/utils.py
base64decode
def base64decode(_input=None): """Take a base64 encoded string and return the decoded string.""" missing_padding = 4 - len(_input) % 4 if missing_padding: _input += '=' * missing_padding if PY2: # pragma: no cover return base64.decodestring(_input) elif PY3: # pragma: no cover ...
python
def base64decode(_input=None): """Take a base64 encoded string and return the decoded string.""" missing_padding = 4 - len(_input) % 4 if missing_padding: _input += '=' * missing_padding if PY2: # pragma: no cover return base64.decodestring(_input) elif PY3: # pragma: no cover ...
[ "def", "base64decode", "(", "_input", "=", "None", ")", ":", "missing_padding", "=", "4", "-", "len", "(", "_input", ")", "%", "4", "if", "missing_padding", ":", "_input", "+=", "'='", "*", "missing_padding", "if", "PY2", ":", "# pragma: no cover", "return...
Take a base64 encoded string and return the decoded string.
[ "Take", "a", "base64", "encoded", "string", "and", "return", "the", "decoded", "string", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L80-L91
train
jonhadfield/creds
lib/creds/utils.py
read_sudoers
def read_sudoers(): """ Read the sudoers entry for the specified user. args: username (str): username. returns:`r str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH) tmp_sudoers_path = '/tmp/s...
python
def read_sudoers(): """ Read the sudoers entry for the specified user. args: username (str): username. returns:`r str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH) tmp_sudoers_path = '/tmp/s...
[ "def", "read_sudoers", "(", ")", ":", "sudoers_path", "=", "'/etc/sudoers'", "rnd_chars", "=", "random_string", "(", "length", "=", "RANDOM_FILE_EXT_LENGTH", ")", "tmp_sudoers_path", "=", "'/tmp/sudoers_{0}'", ".", "format", "(", "rnd_chars", ")", "sudoers_entries", ...
Read the sudoers entry for the specified user. args: username (str): username. returns:`r str: sudoers entry for the specified user.
[ "Read", "the", "sudoers", "entry", "for", "the", "specified", "user", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L94-L118
train
jonhadfield/creds
lib/creds/utils.py
write_sudoers_entry
def write_sudoers_entry(username=None, sudoers_entry=None): """Write sudoers entry. args: user (User): Instance of User containing sudoers entry. returns: str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_...
python
def write_sudoers_entry(username=None, sudoers_entry=None): """Write sudoers entry. args: user (User): Instance of User containing sudoers entry. returns: str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_...
[ "def", "write_sudoers_entry", "(", "username", "=", "None", ",", "sudoers_entry", "=", "None", ")", ":", "sudoers_path", "=", "'/etc/sudoers'", "rnd_chars", "=", "random_string", "(", "length", "=", "RANDOM_FILE_EXT_LENGTH", ")", "tmp_sudoers_path", "=", "'/tmp/sudo...
Write sudoers entry. args: user (User): Instance of User containing sudoers entry. returns: str: sudoers entry for the specified user.
[ "Write", "sudoers", "entry", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L121-L157
train
jonhadfield/creds
lib/creds/utils.py
get_sudoers_entry
def get_sudoers_entry(username=None, sudoers_entries=None): """ Find the sudoers entry in the sudoers file for the specified user. args: username (str): username. sudoers_entries (list): list of lines from the sudoers file. returns:`r str: sudoers entry for the specified user. ...
python
def get_sudoers_entry(username=None, sudoers_entries=None): """ Find the sudoers entry in the sudoers file for the specified user. args: username (str): username. sudoers_entries (list): list of lines from the sudoers file. returns:`r str: sudoers entry for the specified user. ...
[ "def", "get_sudoers_entry", "(", "username", "=", "None", ",", "sudoers_entries", "=", "None", ")", ":", "for", "entry", "in", "sudoers_entries", ":", "if", "entry", ".", "startswith", "(", "username", ")", ":", "return", "entry", ".", "replace", "(", "use...
Find the sudoers entry in the sudoers file for the specified user. args: username (str): username. sudoers_entries (list): list of lines from the sudoers file. returns:`r str: sudoers entry for the specified user.
[ "Find", "the", "sudoers", "entry", "in", "the", "sudoers", "file", "for", "the", "specified", "user", "." ]
b2053b43516cf742c6e4c2b79713bc625592f47c
https://github.com/jonhadfield/creds/blob/b2053b43516cf742c6e4c2b79713bc625592f47c/lib/creds/utils.py#L191-L203
train
alefnula/tea
tea/decorators/__init__.py
docstring
def docstring(documentation, prepend=False, join=""): r"""Prepend or append a string to the current documentation of the function. This decorator should be robust even if ``func.__doc__`` is None (for example, if -OO was passed to the interpreter). Usage:: @docstring('Appended this line') ...
python
def docstring(documentation, prepend=False, join=""): r"""Prepend or append a string to the current documentation of the function. This decorator should be robust even if ``func.__doc__`` is None (for example, if -OO was passed to the interpreter). Usage:: @docstring('Appended this line') ...
[ "def", "docstring", "(", "documentation", ",", "prepend", "=", "False", ",", "join", "=", "\"\"", ")", ":", "def", "decorator", "(", "func", ")", ":", "current", "=", "(", "func", ".", "__doc__", "if", "func", ".", "__doc__", "else", "\"\"", ")", "."...
r"""Prepend or append a string to the current documentation of the function. This decorator should be robust even if ``func.__doc__`` is None (for example, if -OO was passed to the interpreter). Usage:: @docstring('Appended this line') def func(): "This docstring will have a l...
[ "r", "Prepend", "or", "append", "a", "string", "to", "the", "current", "documentation", "of", "the", "function", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/decorators/__init__.py#L10-L53
train