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
dacker-team/pyzure
pyzure/send/common.py
print_progress_bar
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : p...
python
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : p...
[ "def", "print_progress_bar", "(", "iteration", ",", "total", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ",", "decimals", "=", "1", ",", "length", "=", "100", ",", "fill", "=", "'█'):", "", "", "percent", "=", "(", "\"{0:.\"", "+", "str", "...
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
[ "Call", "in", "a", "loop", "to", "create", "terminal", "progress", "bar" ]
1e6d202f91ca0f080635adc470d9d18585056d53
https://github.com/dacker-team/pyzure/blob/1e6d202f91ca0f080635adc470d9d18585056d53/pyzure/send/common.py#L77-L96
train
dacker-team/pyzure
pyzure/send/common.py
print_progress_bar_multi_threads
def print_progress_bar_multi_threads(nb_threads, suffix='', decimals=1, length=15, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) ...
python
def print_progress_bar_multi_threads(nb_threads, suffix='', decimals=1, length=15, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) ...
[ "def", "print_progress_bar_multi_threads", "(", "nb_threads", ",", "suffix", "=", "''", ",", "decimals", "=", "1", ",", "length", "=", "15", ",", "fill", "=", "'█'):", "", "", "string", "=", "\"\"", "for", "k", "in", "range", "(", "nb_threads", ")", ":...
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
[ "Call", "in", "a", "loop", "to", "create", "terminal", "progress", "bar" ]
1e6d202f91ca0f080635adc470d9d18585056d53
https://github.com/dacker-team/pyzure/blob/1e6d202f91ca0f080635adc470d9d18585056d53/pyzure/send/common.py#L99-L131
train
novopl/peltak
src/peltak/extra/pypi/logic.py
upload
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) ...
python
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) ...
[ "def", "upload", "(", "target", ")", ":", "# type: (str) -> None", "log", ".", "info", "(", "\"Uploading to pypi server <33>{}\"", ".", "format", "(", "target", ")", ")", "with", "conf", ".", "within_proj_dir", "(", ")", ":", "shell", ".", "run", "(", "'pyth...
Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc
[ "Upload", "the", "release", "to", "a", "pypi", "server", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/pypi/logic.py#L31-L44
train
novopl/peltak
src/peltak/extra/pypi/logic.py
gen_pypirc
def gen_pypirc(username=None, password=None): # type: (str, str) -> None """ Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it...
python
def gen_pypirc(username=None, password=None): # type: (str, str) -> None """ Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it...
[ "def", "gen_pypirc", "(", "username", "=", "None", ",", "password", "=", "None", ")", ":", "# type: (str, str) -> None", "path", "=", "join", "(", "conf", ".", "getenv", "(", "'HOME'", ")", ",", "'.pypirc'", ")", "username", "=", "username", "or", "conf", ...
Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it will try to take it from the `` PYPI_USER`` env variable. passwo...
[ "Generate", "~", "/", ".", "pypirc", "with", "the", "given", "credentials", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/pypi/logic.py#L47-L84
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/file_utils.py
pick_sdf
def pick_sdf(filename, directory=None): """Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned....
python
def pick_sdf(filename, directory=None): """Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned....
[ "def", "pick_sdf", "(", "filename", ",", "directory", "=", "None", ")", ":", "if", "directory", "is", "None", ":", "directory", "=", "utils", ".", "get_undecorated_calling_module", "(", ")", "# If the 'cwd' is not '/output' (which indicates we're in a Container)", "# th...
Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned. If this fails, `None` is returned. :param...
[ "Returns", "a", "full", "path", "to", "the", "chosen", "SDF", "file", ".", "The", "supplied", "file", "is", "not", "expected", "to", "contain", "a", "recognised", "SDF", "extension", "this", "is", "added", "automatically", ".", "If", "a", "file", "with", ...
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/file_utils.py#L53-L83
train
cons3rt/pycons3rt
pycons3rt/slack.py
main
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(descrip...
python
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(descrip...
[ "def", "main", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.main'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'This Python module allows '", "'sending Slack messages.'", ")", "parser", ...
Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None
[ "Handles", "external", "calling", "for", "this", "module" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L293-L340
train
cons3rt/pycons3rt
pycons3rt/slack.py
SlackMessage.set_text
def set_text(self, text): """Sets the text attribute of the payload :param text: (str) Text of the message :return: None """ log = logging.getLogger(self.cls_logger + '.set_text') if not isinstance(text, basestring): msg = 'text arg must be a string' ...
python
def set_text(self, text): """Sets the text attribute of the payload :param text: (str) Text of the message :return: None """ log = logging.getLogger(self.cls_logger + '.set_text') if not isinstance(text, basestring): msg = 'text arg must be a string' ...
[ "def", "set_text", "(", "self", ",", "text", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.set_text'", ")", "if", "not", "isinstance", "(", "text", ",", "basestring", ")", ":", "msg", "=", "'text arg must be a...
Sets the text attribute of the payload :param text: (str) Text of the message :return: None
[ "Sets", "the", "text", "attribute", "of", "the", "payload" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L86-L98
train
cons3rt/pycons3rt
pycons3rt/slack.py
SlackMessage.set_icon
def set_icon(self, icon_url): """Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None """ log = logging.getLogger(self.cls_logger + '.set_icon') if not isinstance(icon_url, basestring): msg = 'icon_url arg must be a string' ...
python
def set_icon(self, icon_url): """Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None """ log = logging.getLogger(self.cls_logger + '.set_icon') if not isinstance(icon_url, basestring): msg = 'icon_url arg must be a string' ...
[ "def", "set_icon", "(", "self", ",", "icon_url", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.set_icon'", ")", "if", "not", "isinstance", "(", "icon_url", ",", "basestring", ")", ":", "msg", "=", "'icon_url a...
Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None
[ "Sets", "the", "icon_url", "for", "the", "message" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L100-L112
train
cons3rt/pycons3rt
pycons3rt/slack.py
SlackMessage.add_attachment
def add_attachment(self, attachment): """Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None """ log = logging.getLogger(self.cls_logger + '.add_at...
python
def add_attachment(self, attachment): """Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None """ log = logging.getLogger(self.cls_logger + '.add_at...
[ "def", "add_attachment", "(", "self", ",", "attachment", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.add_attachment'", ")", "if", "not", "isinstance", "(", "attachment", ",", "SlackAttachment", ")", ":", "msg", ...
Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None
[ "Adds", "an", "attachment", "to", "the", "SlackMessage", "payload" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L114-L129
train
cons3rt/pycons3rt
pycons3rt/slack.py
SlackMessage.send
def send(self): """Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: None :raises: OSError """ log = logging.getLogger(self.cls_logger + '.send') if self.attachment...
python
def send(self): """Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: None :raises: OSError """ log = logging.getLogger(self.cls_logger + '.send') if self.attachment...
[ "def", "send", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.send'", ")", "if", "self", ".", "attachments", ":", "self", ".", "payload", "[", "'attachments'", "]", "=", "self", ".", "attachments...
Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: None :raises: OSError
[ "Sends", "the", "Slack", "message" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L131-L173
train
cons3rt/pycons3rt
pycons3rt/slack.py
Cons3rtSlacker.send_cons3rt_agent_logs
def send_cons3rt_agent_logs(self): """Sends a Slack message with an attachment for each cons3rt agent log :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log...
python
def send_cons3rt_agent_logs(self): """Sends a Slack message with an attachment for each cons3rt agent log :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log...
[ "def", "send_cons3rt_agent_logs", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.send_cons3rt_agent_logs'", ")", "log", ".", "debug", "(", "'Searching for log files in directory: {d}'", ".", "format", "(", "...
Sends a Slack message with an attachment for each cons3rt agent log :return:
[ "Sends", "a", "Slack", "message", "with", "an", "attachment", "for", "each", "cons3rt", "agent", "log" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L234-L257
train
cons3rt/pycons3rt
pycons3rt/slack.py
Cons3rtSlacker.send_text_file
def send_text_file(self, text_file): """Sends a Slack message with the contents of a text file :param: test_file: (str) Full path to text file to send :return: None :raises: Cons3rtSlackerError """ log = logging.getLogger(self.cls_logger + '.send_text_file') if ...
python
def send_text_file(self, text_file): """Sends a Slack message with the contents of a text file :param: test_file: (str) Full path to text file to send :return: None :raises: Cons3rtSlackerError """ log = logging.getLogger(self.cls_logger + '.send_text_file') if ...
[ "def", "send_text_file", "(", "self", ",", "text_file", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.send_text_file'", ")", "if", "not", "isinstance", "(", "text_file", ",", "basestring", ")", ":", "msg", "=", ...
Sends a Slack message with the contents of a text file :param: test_file: (str) Full path to text file to send :return: None :raises: Cons3rtSlackerError
[ "Sends", "a", "Slack", "message", "with", "the", "contents", "of", "a", "text", "file" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/slack.py#L259-L290
train
novopl/peltak
src/peltak_appengine/cli.py
deploy
def deploy(project, version, promote, quiet): """ Deploy the app to the target environment. The target environments can be configured using the ENVIRONMENTS conf variable. This will also collect all static files and compile translation messages """ from . import logic logic.deploy(project,...
python
def deploy(project, version, promote, quiet): """ Deploy the app to the target environment. The target environments can be configured using the ENVIRONMENTS conf variable. This will also collect all static files and compile translation messages """ from . import logic logic.deploy(project,...
[ "def", "deploy", "(", "project", ",", "version", ",", "promote", ",", "quiet", ")", ":", "from", ".", "import", "logic", "logic", ".", "deploy", "(", "project", ",", "version", ",", "promote", ",", "quiet", ")" ]
Deploy the app to the target environment. The target environments can be configured using the ENVIRONMENTS conf variable. This will also collect all static files and compile translation messages
[ "Deploy", "the", "app", "to", "the", "target", "environment", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak_appengine/cli.py#L59-L68
train
novopl/peltak
src/peltak_appengine/cli.py
devserver
def devserver(port, admin_port, clear): # type: (int, int, bool) -> None """ Run devserver. """ from . import logic logic.devserver(port, admin_port, clear)
python
def devserver(port, admin_port, clear): # type: (int, int, bool) -> None """ Run devserver. """ from . import logic logic.devserver(port, admin_port, clear)
[ "def", "devserver", "(", "port", ",", "admin_port", ",", "clear", ")", ":", "# type: (int, int, bool) -> None", "from", ".", "import", "logic", "logic", ".", "devserver", "(", "port", ",", "admin_port", ",", "clear", ")" ]
Run devserver.
[ "Run", "devserver", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak_appengine/cli.py#L76-L81
train
Vital-Fernandez/dazer
bin/lib/Astro_Libraries/old_versions/attributes_declaration.py
gaussian_filter1d_ppxf
def gaussian_filter1d_ppxf(spec, sig): """ Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. ...
python
def gaussian_filter1d_ppxf(spec, sig): """ Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. ...
[ "def", "gaussian_filter1d_ppxf", "(", "spec", ",", "sig", ")", ":", "sig", "=", "sig", ".", "clip", "(", "0.01", ")", "# forces zero sigmas to have 0.01 pixels", "p", "=", "int", "(", "np", ".", "ceil", "(", "np", ".", "max", "(", "3", "*", "sig", ")",...
Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. When creating a template library for SDSS data,...
[ "Convolve", "a", "spectrum", "by", "a", "Gaussian", "with", "different", "sigma", "for", "every", "pixel", ".", "If", "all", "sigma", "are", "the", "same", "this", "routine", "produces", "the", "same", "output", "as", "scipy", ".", "ndimage", ".", "gaussia...
3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244
https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/old_versions/attributes_declaration.py#L1-L40
train
Varkal/chuda
chuda/app.py
App.call_plugins
def call_plugins(self, step): ''' For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin ''' for plugin in self.plugins: try: getattr(plugin, step)() e...
python
def call_plugins(self, step): ''' For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin ''' for plugin in self.plugins: try: getattr(plugin, step)() e...
[ "def", "call_plugins", "(", "self", ",", "step", ")", ":", "for", "plugin", "in", "self", ".", "plugins", ":", "try", ":", "getattr", "(", "plugin", ",", "step", ")", "(", ")", "except", "AttributeError", ":", "self", ".", "logger", ".", "debug", "("...
For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin
[ "For", "each", "plugins", "check", "if", "a", "step", "method", "exist", "on", "it", "and", "call", "it" ]
0d93b716dede35231c21be97bcc19a656655983f
https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/app.py#L206-L219
train
Varkal/chuda
chuda/app.py
App.run
def run(self): """ Run the application """ self.call_plugins("on_run") if vars(self.arguments).get("version", None): self.logger.info("{app_name}: {version}".format(app_name=self.app_name, version=self.version)) else: if self.arguments.command == "...
python
def run(self): """ Run the application """ self.call_plugins("on_run") if vars(self.arguments).get("version", None): self.logger.info("{app_name}: {version}".format(app_name=self.app_name, version=self.version)) else: if self.arguments.command == "...
[ "def", "run", "(", "self", ")", ":", "self", ".", "call_plugins", "(", "\"on_run\"", ")", "if", "vars", "(", "self", ".", "arguments", ")", ".", "get", "(", "\"version\"", ",", "None", ")", ":", "self", ".", "logger", ".", "info", "(", "\"{app_name}:...
Run the application
[ "Run", "the", "application" ]
0d93b716dede35231c21be97bcc19a656655983f
https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/app.py#L266-L278
train
novopl/peltak
src/peltak/commands/__init__.py
pretend_option
def pretend_option(fn): # type: (FunctionType) -> FunctionType """ Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command n...
python
def pretend_option(fn): # type: (FunctionType) -> FunctionType """ Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command n...
[ "def", "pretend_option", "(", "fn", ")", ":", "# type: (FunctionType) -> FunctionType", "def", "set_pretend", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=missing-docstring", "# type: (click.Context, str, Any) -> None", "from", "peltak", ".", "core...
Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command needs it. To get the current value you can do: >>> from peltak.comm...
[ "Decorator", "to", "add", "a", "--", "pretend", "option", "to", "any", "click", "command", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/__init__.py#L57-L92
train
novopl/peltak
src/peltak/commands/__init__.py
verbose_option
def verbose_option(fn): """ Decorator to add a --verbose option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'verbose' if the command needs it. To get the current value you can d...
python
def verbose_option(fn): """ Decorator to add a --verbose option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'verbose' if the command needs it. To get the current value you can d...
[ "def", "verbose_option", "(", "fn", ")", ":", "def", "set_verbose", "(", "ctx", ",", "param", ",", "value", ")", ":", "# pylint: disable=missing-docstring", "# type: (click.Context, str, Any) -> None", "from", "peltak", ".", "core", "import", "context", "context", "...
Decorator to add a --verbose option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'verbose' if the command needs it. To get the current value you can do: >>> from peltak.core...
[ "Decorator", "to", "add", "a", "--", "verbose", "option", "to", "any", "click", "command", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/__init__.py#L134-L159
train
novopl/peltak
src/peltak/extra/changelog/logic.py
changelog
def changelog(): # type: () -> str """ Print change log since last release. """ # Skip 'v' prefix versions = [x for x in git.tags() if versioning.is_valid(x[1:])] cmd = 'git log --format=%H' if versions: cmd += ' {}..HEAD'.format(versions[-1]) hashes = shell.run(cmd, capture=True)....
python
def changelog(): # type: () -> str """ Print change log since last release. """ # Skip 'v' prefix versions = [x for x in git.tags() if versioning.is_valid(x[1:])] cmd = 'git log --format=%H' if versions: cmd += ' {}..HEAD'.format(versions[-1]) hashes = shell.run(cmd, capture=True)....
[ "def", "changelog", "(", ")", ":", "# type: () -> str", "# Skip 'v' prefix", "versions", "=", "[", "x", "for", "x", "in", "git", ".", "tags", "(", ")", "if", "versioning", ".", "is_valid", "(", "x", "[", "1", ":", "]", ")", "]", "cmd", "=", "'git log...
Print change log since last release.
[ "Print", "change", "log", "since", "last", "release", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/changelog/logic.py#L34-L80
train
novopl/peltak
src/peltak/extra/changelog/logic.py
extract_changelog_items
def extract_changelog_items(text, tags): # type: (str) -> Dict[str, List[str]] """ Extract all tagged items from text. Args: text (str): Text to extract the tagged items from. Each tagged item is a paragraph that starts with a tag. It can also be a text list item. Retur...
python
def extract_changelog_items(text, tags): # type: (str) -> Dict[str, List[str]] """ Extract all tagged items from text. Args: text (str): Text to extract the tagged items from. Each tagged item is a paragraph that starts with a tag. It can also be a text list item. Retur...
[ "def", "extract_changelog_items", "(", "text", ",", "tags", ")", ":", "# type: (str) -> Dict[str, List[str]]", "patterns", "=", "{", "x", "[", "'header'", "]", ":", "tag_re", "(", "x", "[", "'tag'", "]", ")", "for", "x", "in", "tags", "}", "items", "=", ...
Extract all tagged items from text. Args: text (str): Text to extract the tagged items from. Each tagged item is a paragraph that starts with a tag. It can also be a text list item. Returns: tuple[list[str], list[str], list[str]]: A tuple of `(features, chan...
[ "Extract", "all", "tagged", "items", "from", "text", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/changelog/logic.py#L83-L130
train
katyukha/extend-me
extend_me.py
ExtensibleType._
def _(mcs, cls_name="Object", with_meta=None): """ Method to generate real metaclass to be used:: mc = ExtensibleType._("MyClass") # note this line @six.add_metaclass(mc) class MyClassBase(object): pass :param str cls_name: name ...
python
def _(mcs, cls_name="Object", with_meta=None): """ Method to generate real metaclass to be used:: mc = ExtensibleType._("MyClass") # note this line @six.add_metaclass(mc) class MyClassBase(object): pass :param str cls_name: name ...
[ "def", "_", "(", "mcs", ",", "cls_name", "=", "\"Object\"", ",", "with_meta", "=", "None", ")", ":", "if", "with_meta", "is", "not", "None", ":", "class", "EXType", "(", "with_meta", ",", "mcs", ")", ":", "_cls_name", "=", "cls_name", "_base_classes", ...
Method to generate real metaclass to be used:: mc = ExtensibleType._("MyClass") # note this line @six.add_metaclass(mc) class MyClassBase(object): pass :param str cls_name: name of generated class :param class with_meta: Mix ...
[ "Method", "to", "generate", "real", "metaclass", "to", "be", "used", "::" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L377-L401
train
katyukha/extend-me
extend_me.py
ExtensibleType.get_class
def get_class(mcs): """ Generates new class to gether logic of all available extensions :: mc = ExtensibleType._("MyClass") @six.add_metaclass(mc) class MyClassBase(object): pass # get class with all extensions ena...
python
def get_class(mcs): """ Generates new class to gether logic of all available extensions :: mc = ExtensibleType._("MyClass") @six.add_metaclass(mc) class MyClassBase(object): pass # get class with all extensions ena...
[ "def", "get_class", "(", "mcs", ")", ":", "if", "mcs", ".", "_generated_class", "is", "None", ":", "mcs", ".", "_generated_class", "=", "type", "(", "mcs", ".", "_cls_name", ",", "tuple", "(", "mcs", ".", "_base_classes", ")", ",", "{", "'_generated'", ...
Generates new class to gether logic of all available extensions :: mc = ExtensibleType._("MyClass") @six.add_metaclass(mc) class MyClassBase(object): pass # get class with all extensions enabled MyClass = m...
[ "Generates", "new", "class", "to", "gether", "logic", "of", "all", "available", "extensions", "::" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L404-L422
train
katyukha/extend-me
extend_me.py
ExtensibleByHashType._add_base_class
def _add_base_class(mcs, cls): """ Adds new class *cls* to base classes """ # Do all magic only if subclass had defined required attributes if getattr(mcs, '_base_classes_hash', None) is not None: meta = getattr(cls, 'Meta', None) _hash = getattr(meta, mcs._hashat...
python
def _add_base_class(mcs, cls): """ Adds new class *cls* to base classes """ # Do all magic only if subclass had defined required attributes if getattr(mcs, '_base_classes_hash', None) is not None: meta = getattr(cls, 'Meta', None) _hash = getattr(meta, mcs._hashat...
[ "def", "_add_base_class", "(", "mcs", ",", "cls", ")", ":", "# Do all magic only if subclass had defined required attributes", "if", "getattr", "(", "mcs", ",", "'_base_classes_hash'", ",", "None", ")", "is", "not", "None", ":", "meta", "=", "getattr", "(", "cls",...
Adds new class *cls* to base classes
[ "Adds", "new", "class", "*", "cls", "*", "to", "base", "classes" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L578-L590
train
katyukha/extend-me
extend_me.py
ExtensibleByHashType._
def _(mcs, cls_name='Object', with_meta=None, hashattr='_name'): """ Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass ...
python
def _(mcs, cls_name='Object', with_meta=None, hashattr='_name'): """ Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass ...
[ "def", "_", "(", "mcs", ",", "cls_name", "=", "'Object'", ",", "with_meta", "=", "None", ",", "hashattr", "=", "'_name'", ")", ":", "extype", "=", "super", "(", "ExtensibleByHashType", ",", "mcs", ")", ".", "_", "(", "cls_name", "=", "cls_name", ",", ...
Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass @six.add_metaclass(mc) class MyClassBase(object): ...
[ "Method", "to", "generate", "real", "metaclass", "to", "be", "used", "::" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L593-L623
train
katyukha/extend-me
extend_me.py
ExtensibleByHashType.get_class
def get_class(mcs, name, default=False): """ Generates new class to gether logic of all available extensions :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Use metaclass *mc* to create base class for extensions ...
python
def get_class(mcs, name, default=False): """ Generates new class to gether logic of all available extensions :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Use metaclass *mc* to create base class for extensions ...
[ "def", "get_class", "(", "mcs", ",", "name", ",", "default", "=", "False", ")", ":", "if", "default", "is", "False", "and", "name", "not", "in", "mcs", ".", "_base_classes_hash", ":", "raise", "ValueError", "(", "\"There is no class registered for key '%s'\"", ...
Generates new class to gether logic of all available extensions :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Use metaclass *mc* to create base class for extensions @six.add_metaclass(mc) ...
[ "Generates", "new", "class", "to", "gether", "logic", "of", "all", "available", "extensions", "::" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L626-L663
train
katyukha/extend-me
extend_me.py
ExtensibleByHashType.get_registered_names
def get_registered_names(mcs): """ Return's list of names (keys) registered in this tree. For each name specific classes exists """ return [k for k, v in six.iteritems(mcs._base_classes_hash) if v]
python
def get_registered_names(mcs): """ Return's list of names (keys) registered in this tree. For each name specific classes exists """ return [k for k, v in six.iteritems(mcs._base_classes_hash) if v]
[ "def", "get_registered_names", "(", "mcs", ")", ":", "return", "[", "k", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "mcs", ".", "_base_classes_hash", ")", "if", "v", "]" ]
Return's list of names (keys) registered in this tree. For each name specific classes exists
[ "Return", "s", "list", "of", "names", "(", "keys", ")", "registered", "in", "this", "tree", ".", "For", "each", "name", "specific", "classes", "exists" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L673-L677
train
kajala/django-jutil
jutil/dates.py
get_last_day_of_month
def get_last_day_of_month(t: datetime) -> int: """ Returns day number of the last day of the month :param t: datetime :return: int """ tn = t + timedelta(days=32) tn = datetime(year=tn.year, month=tn.month, day=1) tt = tn - timedelta(hours=1) return tt.day
python
def get_last_day_of_month(t: datetime) -> int: """ Returns day number of the last day of the month :param t: datetime :return: int """ tn = t + timedelta(days=32) tn = datetime(year=tn.year, month=tn.month, day=1) tt = tn - timedelta(hours=1) return tt.day
[ "def", "get_last_day_of_month", "(", "t", ":", "datetime", ")", "->", "int", ":", "tn", "=", "t", "+", "timedelta", "(", "days", "=", "32", ")", "tn", "=", "datetime", "(", "year", "=", "tn", ".", "year", ",", "month", "=", "tn", ".", "month", ",...
Returns day number of the last day of the month :param t: datetime :return: int
[ "Returns", "day", "number", "of", "the", "last", "day", "of", "the", "month", ":", "param", "t", ":", "datetime", ":", "return", ":", "int" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L37-L46
train
kajala/django-jutil
jutil/dates.py
localize_time_range
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime): """ Localizes time range. Uses pytz.utc if None provided. :param begin: Begin datetime :param end: End datetime :param tz: pytz timezone or None (default UTC) :return: begin, end """ if not tz: ...
python
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime): """ Localizes time range. Uses pytz.utc if None provided. :param begin: Begin datetime :param end: End datetime :param tz: pytz timezone or None (default UTC) :return: begin, end """ if not tz: ...
[ "def", "localize_time_range", "(", "begin", ":", "datetime", ",", "end", ":", "datetime", ",", "tz", "=", "None", ")", "->", "(", "datetime", ",", "datetime", ")", ":", "if", "not", "tz", ":", "tz", "=", "pytz", ".", "utc", "return", "tz", ".", "lo...
Localizes time range. Uses pytz.utc if None provided. :param begin: Begin datetime :param end: End datetime :param tz: pytz timezone or None (default UTC) :return: begin, end
[ "Localizes", "time", "range", ".", "Uses", "pytz", ".", "utc", "if", "None", "provided", ".", ":", "param", "begin", ":", "Begin", "datetime", ":", "param", "end", ":", "End", "datetime", ":", "param", "tz", ":", "pytz", "timezone", "or", "None", "(", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L49-L59
train
kajala/django-jutil
jutil/dates.py
this_week
def this_week(today: datetime=None, tz=None): """ Returns this week begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
python
def this_week(today: datetime=None, tz=None): """ Returns this week begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
[ "def", "this_week", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "today", "-", "timedelta", "(", "days", "=", "today...
Returns this week begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
[ "Returns", "this", "week", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(", "defaults", "pytz", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L62-L73
train
kajala/django-jutil
jutil/dates.py
this_month
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
python
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
[ "def", "this_month", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "datetime", "(", "day", "=", "1", ",", "month", ...
Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
[ "Returns", "current", "month", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "in", "the", "month", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L76-L88
train
kajala/django-jutil
jutil/dates.py
next_month
def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: toda...
python
def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: toda...
[ "def", "next_month", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "datetime", "(", "day", "=", "1", ",", "month", ...
Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
[ "Returns", "next", "month", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "in", "the", "month", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L105-L119
train
kajala/django-jutil
jutil/dates.py
last_year
def last_year(today: datetime=None, tz=None): """ Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
python
def last_year(today: datetime=None, tz=None): """ Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
[ "def", "last_year", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "end", "=", "datetime", "(", "day", "=", "1", ",", "month", "="...
Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
[ "Returns", "last", "year", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(", "defaults", "pytz", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L151-L163
train
kajala/django-jutil
jutil/dates.py
add_month
def add_month(t: datetime, n: int=1) -> datetime: """ Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime """ t2 = t for count in range(abs(n)): if n > 0: t2 = datetime(year=t2.year, month=t2....
python
def add_month(t: datetime, n: int=1) -> datetime: """ Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime """ t2 = t for count in range(abs(n)): if n > 0: t2 = datetime(year=t2.year, month=t2....
[ "def", "add_month", "(", "t", ":", "datetime", ",", "n", ":", "int", "=", "1", ")", "->", "datetime", ":", "t2", "=", "t", "for", "count", "in", "range", "(", "abs", "(", "n", ")", ")", ":", "if", "n", ">", "0", ":", "t2", "=", "datetime", ...
Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime
[ "Adds", "+", "-", "n", "months", "to", "datetime", ".", "Clamps", "to", "number", "of", "days", "in", "given", "month", ".", ":", "param", "t", ":", "datetime", ":", "param", "n", ":", "count", ":", "return", ":", "datetime" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L181-L200
train
kajala/django-jutil
jutil/dates.py
per_delta
def per_delta(start: datetime, end: datetime, delta: timedelta): """ Iterates over time range in steps specified in delta. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param delta: Step interval :return: Iterable collection of [(start+td*0, start+td*...
python
def per_delta(start: datetime, end: datetime, delta: timedelta): """ Iterates over time range in steps specified in delta. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param delta: Step interval :return: Iterable collection of [(start+td*0, start+td*...
[ "def", "per_delta", "(", "start", ":", "datetime", ",", "end", ":", "datetime", ",", "delta", ":", "timedelta", ")", ":", "curr", "=", "start", "while", "curr", "<", "end", ":", "curr_end", "=", "curr", "+", "delta", "yield", "curr", ",", "curr_end", ...
Iterates over time range in steps specified in delta. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param delta: Step interval :return: Iterable collection of [(start+td*0, start+td*1), (start+td*1, start+td*2), ..., end)
[ "Iterates", "over", "time", "range", "in", "steps", "specified", "in", "delta", "." ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L203-L217
train
kajala/django-jutil
jutil/dates.py
per_month
def per_month(start: datetime, end: datetime, n: int=1): """ Iterates over time range in one month steps. Clamps to number of days in given month. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param n: Number of months to step. Default is 1. :retu...
python
def per_month(start: datetime, end: datetime, n: int=1): """ Iterates over time range in one month steps. Clamps to number of days in given month. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param n: Number of months to step. Default is 1. :retu...
[ "def", "per_month", "(", "start", ":", "datetime", ",", "end", ":", "datetime", ",", "n", ":", "int", "=", "1", ")", ":", "curr", "=", "start", ".", "replace", "(", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second",...
Iterates over time range in one month steps. Clamps to number of days in given month. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param n: Number of months to step. Default is 1. :return: Iterable collection of [(month+0, month+1), (month+1, month+2), ....
[ "Iterates", "over", "time", "range", "in", "one", "month", "steps", ".", "Clamps", "to", "number", "of", "days", "in", "given", "month", "." ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L220-L235
train
MarcAureleCoste/sqla-filters
setup.py
get_requirements
def get_requirements() -> List[str]: """Return the requirements as a list of string.""" requirements_path = os.path.join( os.path.dirname(__file__), 'requirements.txt' ) with open(requirements_path) as f: return f.read().split()
python
def get_requirements() -> List[str]: """Return the requirements as a list of string.""" requirements_path = os.path.join( os.path.dirname(__file__), 'requirements.txt' ) with open(requirements_path) as f: return f.read().split()
[ "def", "get_requirements", "(", ")", "->", "List", "[", "str", "]", ":", "requirements_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'requirements.txt'", ")", "with", "open", "(", "requi...
Return the requirements as a list of string.
[ "Return", "the", "requirements", "as", "a", "list", "of", "string", "." ]
a9596f660a11d275bf0e831ecd9e502b0af2a087
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/setup.py#L14-L20
train
novopl/peltak
src/peltak/commands/root.py
project_dev_requirements
def project_dev_requirements(): """ List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured co...
python
def project_dev_requirements(): """ List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured co...
[ "def", "project_dev_requirements", "(", ")", ":", "from", "peltak", ".", "core", "import", "conf", "from", "peltak", ".", "core", "import", "shell", "for", "dep", "in", "sorted", "(", "conf", ".", "requirements", ")", ":", "shell", ".", "cprint", "(", "d...
List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured commands to work.
[ "List", "requirements", "for", "peltak", "commands", "configured", "for", "the", "project", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/root.py#L89-L100
train
inplat/aioapp
aioapp/misc.py
get_func_params
def get_func_params(method, called_params): """ :type method: function :type called_params: dict :return: """ insp = inspect.getfullargspec(method) if not isinstance(called_params, dict): raise UserWarning() _called_params = called_params.copy() params = {} arg_count = le...
python
def get_func_params(method, called_params): """ :type method: function :type called_params: dict :return: """ insp = inspect.getfullargspec(method) if not isinstance(called_params, dict): raise UserWarning() _called_params = called_params.copy() params = {} arg_count = le...
[ "def", "get_func_params", "(", "method", ",", "called_params", ")", ":", "insp", "=", "inspect", ".", "getfullargspec", "(", "method", ")", "if", "not", "isinstance", "(", "called_params", ",", "dict", ")", ":", "raise", "UserWarning", "(", ")", "_called_par...
:type method: function :type called_params: dict :return:
[ ":", "type", "method", ":", "function", ":", "type", "called_params", ":", "dict", ":", "return", ":" ]
4ccb026264eaab69806512b58681c0b2f9544621
https://github.com/inplat/aioapp/blob/4ccb026264eaab69806512b58681c0b2f9544621/aioapp/misc.py#L60-L96
train
inplat/aioapp
aioapp/misc.py
parse_dsn
def parse_dsn(dsn, default_port=5432, protocol='http://'): """ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type de...
python
def parse_dsn(dsn, default_port=5432, protocol='http://'): """ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type de...
[ "def", "parse_dsn", "(", "dsn", ",", "default_port", "=", "5432", ",", "protocol", "=", "'http://'", ")", ":", "parsed", "=", "urlparse", "(", "protocol", "+", "dsn", ")", "return", "[", "parsed", ".", "hostname", "or", "'localhost'", ",", "parsed", ".",...
Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type default_port: int :params protocol :type protocol str :return...
[ "Разбирает", "строку", "подключения", "к", "БД", "и", "возвращает", "список", "из", "(", "host", "port", "username", "password", "dbname", ")" ]
4ccb026264eaab69806512b58681c0b2f9544621
https://github.com/inplat/aioapp/blob/4ccb026264eaab69806512b58681c0b2f9544621/aioapp/misc.py#L124-L146
train
novopl/peltak
src/peltak/extra/docker/logic.py
build_images
def build_images(): # type: () -> None """ Build all docker images for the project. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) for image in docker_images: build_image(registry, image)
python
def build_images(): # type: () -> None """ Build all docker images for the project. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) for image in docker_images: build_image(registry, image)
[ "def", "build_images", "(", ")", ":", "# type: () -> None", "registry", "=", "conf", ".", "get", "(", "'docker.registry'", ")", "docker_images", "=", "conf", ".", "get", "(", "'docker.images'", ",", "[", "]", ")", "for", "image", "in", "docker_images", ":", ...
Build all docker images for the project.
[ "Build", "all", "docker", "images", "for", "the", "project", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L34-L41
train
novopl/peltak
src/peltak/extra/docker/logic.py
push_images
def push_images(): # type: () -> None """ Push all project docker images to a remote registry. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) if registry is None: log.err("You must define docker.registry conf variable to push images") sys.ex...
python
def push_images(): # type: () -> None """ Push all project docker images to a remote registry. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) if registry is None: log.err("You must define docker.registry conf variable to push images") sys.ex...
[ "def", "push_images", "(", ")", ":", "# type: () -> None", "registry", "=", "conf", ".", "get", "(", "'docker.registry'", ")", "docker_images", "=", "conf", ".", "get", "(", "'docker.images'", ",", "[", "]", ")", "if", "registry", "is", "None", ":", "log",...
Push all project docker images to a remote registry.
[ "Push", "all", "project", "docker", "images", "to", "a", "remote", "registry", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L44-L55
train
novopl/peltak
src/peltak/extra/docker/logic.py
docker_list
def docker_list(registry_pass): # type: (str) -> None """ List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password. """ registry = conf.get('docker.registry', None) if registry is None: log.err("You must define doc...
python
def docker_list(registry_pass): # type: (str) -> None """ List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password. """ registry = conf.get('docker.registry', None) if registry is None: log.err("You must define doc...
[ "def", "docker_list", "(", "registry_pass", ")", ":", "# type: (str) -> None", "registry", "=", "conf", ".", "get", "(", "'docker.registry'", ",", "None", ")", "if", "registry", "is", "None", ":", "log", ".", "err", "(", "\"You must define docker.registry conf var...
List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password.
[ "List", "docker", "images", "stored", "in", "the", "remote", "registry", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L58-L84
train
novopl/peltak
src/peltak/extra/docker/logic.py
build_image
def build_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Build docker image. Args: registry (str): The name of the registry this image belongs to. If not given, the resulting image will have a name without the registry. image (dict[str, Any]): ...
python
def build_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Build docker image. Args: registry (str): The name of the registry this image belongs to. If not given, the resulting image will have a name without the registry. image (dict[str, Any]): ...
[ "def", "build_image", "(", "registry", ",", "image", ")", ":", "# type: (str, Dict[str, Any]) -> None", "if", "':'", "in", "image", "[", "'name'", "]", ":", "_", ",", "tag", "=", "image", "[", "'name'", "]", ".", "split", "(", "':'", ",", "1", ")", "el...
Build docker image. Args: registry (str): The name of the registry this image belongs to. If not given, the resulting image will have a name without the registry. image (dict[str, Any]): The dict containing the information about the built image. This is ...
[ "Build", "docker", "image", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L87-L126
train
novopl/peltak
src/peltak/extra/docker/logic.py
push_image
def push_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) ...
python
def push_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) ...
[ "def", "push_image", "(", "registry", ",", "image", ")", ":", "# type: (str, Dict[str, Any]) -> None", "values", "=", "{", "'registry'", ":", "registry", ",", "'image'", ":", "image", "[", "'name'", "]", ",", "}", "log", ".", "info", "(", "\"Pushing <33>{regis...
Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) image (dict[str, Any]): The dict containing the information abou...
[ "Push", "the", "given", "image", "to", "selected", "repository", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L129-L147
train
paydunya/paydunya-python
paydunya/opr.py
OPR._build_opr_data
def _build_opr_data(self, data, store): """Returns a well formatted OPR data""" return { "invoice_data": { "invoice": { "total_amount": data.get("total_amount"), "description": data.get("description") }, ...
python
def _build_opr_data(self, data, store): """Returns a well formatted OPR data""" return { "invoice_data": { "invoice": { "total_amount": data.get("total_amount"), "description": data.get("description") }, ...
[ "def", "_build_opr_data", "(", "self", ",", "data", ",", "store", ")", ":", "return", "{", "\"invoice_data\"", ":", "{", "\"invoice\"", ":", "{", "\"total_amount\"", ":", "data", ".", "get", "(", "\"total_amount\"", ")", ",", "\"description\"", ":", "data", ...
Returns a well formatted OPR data
[ "Returns", "a", "well", "formatted", "OPR", "data" ]
bb55791e2814788aec74162d9d78970815f37c30
https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L13-L26
train
paydunya/paydunya-python
paydunya/opr.py
OPR.create
def create(self, data={}, store=None): """Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token """ _store = store or self.store _data = self._build_opr_data(data, _store) if data else self._opr_data return self._proce...
python
def create(self, data={}, store=None): """Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token """ _store = store or self.store _data = self._build_opr_data(data, _store) if data else self._opr_data return self._proce...
[ "def", "create", "(", "self", ",", "data", "=", "{", "}", ",", "store", "=", "None", ")", ":", "_store", "=", "store", "or", "self", ".", "store", "_data", "=", "self", ".", "_build_opr_data", "(", "data", ",", "_store", ")", "if", "data", "else", ...
Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token
[ "Initiazes", "an", "OPR" ]
bb55791e2814788aec74162d9d78970815f37c30
https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L28-L36
train
paydunya/paydunya-python
paydunya/opr.py
OPR.charge
def charge(self, data): """Second stage of an OPR request""" token = data.get("token", self._response["token"]) data = { "token": token, "confirm_token": data.get("confirm_token") } return self._process('opr/charge', data)
python
def charge(self, data): """Second stage of an OPR request""" token = data.get("token", self._response["token"]) data = { "token": token, "confirm_token": data.get("confirm_token") } return self._process('opr/charge', data)
[ "def", "charge", "(", "self", ",", "data", ")", ":", "token", "=", "data", ".", "get", "(", "\"token\"", ",", "self", ".", "_response", "[", "\"token\"", "]", ")", "data", "=", "{", "\"token\"", ":", "token", ",", "\"confirm_token\"", ":", "data", "....
Second stage of an OPR request
[ "Second", "stage", "of", "an", "OPR", "request" ]
bb55791e2814788aec74162d9d78970815f37c30
https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L38-L45
train
novopl/peltak
src/cliform/core.py
Form.get_value
def get_value(self, field, quick): # type: (Field, bool) -> Any """ Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quic...
python
def get_value(self, field, quick): # type: (Field, bool) -> Any """ Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quic...
[ "def", "get_value", "(", "self", ",", "field", ",", "quick", ")", ":", "# type: (Field, bool) -> Any", "if", "callable", "(", "field", ".", "default", ")", ":", "default", "=", "field", ".", "default", "(", "self", ")", "else", ":", "default", "=", "fiel...
Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quick mode, the form will reduce the number of question asked by using d...
[ "Ask", "user", "the", "question", "represented", "by", "this", "instance", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/cliform/core.py#L123-L157
train
cons3rt/pycons3rt
pycons3rt/awsapi/images.py
ImageUtil.update_image
def update_image(self, ami_id, instance_id): """Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None...
python
def update_image(self, ami_id, instance_id): """Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None...
[ "def", "update_image", "(", "self", ",", "ami_id", ",", "instance_id", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.update_image'", ")", "if", "not", "isinstance", "(", "ami_id", ",", "basestring", ")", ":", ...
Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None
[ "Replaces", "an", "existing", "AMI", "ID", "with", "an", "image", "created", "from", "the", "provided", "instance", "ID", ":", "param", "ami_id", ":", "(", "str", ")", "ID", "of", "the", "AMI", "to", "delete", "and", "replace", ":", "param", "instance_id...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/images.py#L70-L207
train
cons3rt/pycons3rt
pycons3rt/awsapi/images.py
ImageUtil.create_cons3rt_template
def create_cons3rt_template(self, instance_id, name, description='CONS3RT OS template'): """Created a new CONS3RT-ready template from an instance ID :param instance_id: (str) Instance ID to create the image from :param name: (str) Name of the new image :param description: (str) ...
python
def create_cons3rt_template(self, instance_id, name, description='CONS3RT OS template'): """Created a new CONS3RT-ready template from an instance ID :param instance_id: (str) Instance ID to create the image from :param name: (str) Name of the new image :param description: (str) ...
[ "def", "create_cons3rt_template", "(", "self", ",", "instance_id", ",", "name", ",", "description", "=", "'CONS3RT OS template'", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.create_cons3rt_template'", ")", "if", "no...
Created a new CONS3RT-ready template from an instance ID :param instance_id: (str) Instance ID to create the image from :param name: (str) Name of the new image :param description: (str) Description of the new image :return: None
[ "Created", "a", "new", "CONS3RT", "-", "ready", "template", "from", "an", "instance", "ID", ":", "param", "instance_id", ":", "(", "str", ")", "Instance", "ID", "to", "create", "the", "image", "from", ":", "param", "name", ":", "(", "str", ")", "Name",...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/images.py#L209-L266
train
cons3rt/pycons3rt
pycons3rt/awsapi/images.py
ImageUtil.copy_cons3rt_template
def copy_cons3rt_template(self, ami_id): """ :param ami_id: :return: """ log = logging.getLogger(self.cls_logger + '.copy_cons3rt_template') # Get the current AMI info try: ami_info = self.ec2.describe_images(DryRun=False, ImageIds=[ami_id],...
python
def copy_cons3rt_template(self, ami_id): """ :param ami_id: :return: """ log = logging.getLogger(self.cls_logger + '.copy_cons3rt_template') # Get the current AMI info try: ami_info = self.ec2.describe_images(DryRun=False, ImageIds=[ami_id],...
[ "def", "copy_cons3rt_template", "(", "self", ",", "ami_id", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.copy_cons3rt_template'", ")", "# Get the current AMI info", "try", ":", "ami_info", "=", "self", ".", "ec2", ...
:param ami_id: :return:
[ ":", "param", "ami_id", ":", ":", "return", ":" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/images.py#L268-L300
train
jaredLunde/vital-tools
vital/tools/encoding.py
uniorbytes
def uniorbytes(s, result=str, enc="utf-8", err="strict"): """ This function was made to avoid byte / str type errors received in packages like base64. Accepts all input types and will recursively encode entire lists and dicts. @s: the #bytes or #str item you are attempting to encode or decode @...
python
def uniorbytes(s, result=str, enc="utf-8", err="strict"): """ This function was made to avoid byte / str type errors received in packages like base64. Accepts all input types and will recursively encode entire lists and dicts. @s: the #bytes or #str item you are attempting to encode or decode @...
[ "def", "uniorbytes", "(", "s", ",", "result", "=", "str", ",", "enc", "=", "\"utf-8\"", ",", "err", "=", "\"strict\"", ")", ":", "if", "isinstance", "(", "s", ",", "result", ")", ":", "# the input is the desired one, return as is", "return", "s", "if", "is...
This function was made to avoid byte / str type errors received in packages like base64. Accepts all input types and will recursively encode entire lists and dicts. @s: the #bytes or #str item you are attempting to encode or decode @result: the desired output, either #str or #bytes @enc: the desire...
[ "This", "function", "was", "made", "to", "avoid", "byte", "/", "str", "type", "errors", "received", "in", "packages", "like", "base64", ".", "Accepts", "all", "input", "types", "and", "will", "recursively", "encode", "entire", "lists", "and", "dicts", "." ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L36-L75
train
jaredLunde/vital-tools
vital/tools/encoding.py
recode_unicode
def recode_unicode(s, encoding='utf-8'): """ Inputs are encoded to utf-8 and then decoded to the desired output encoding @encoding: the desired encoding -> #str with the desired @encoding """ if isinstance(s, str): return s.encode().decode(encoding) return s
python
def recode_unicode(s, encoding='utf-8'): """ Inputs are encoded to utf-8 and then decoded to the desired output encoding @encoding: the desired encoding -> #str with the desired @encoding """ if isinstance(s, str): return s.encode().decode(encoding) return s
[ "def", "recode_unicode", "(", "s", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", ":", "return", "s", ".", "encode", "(", ")", ".", "decode", "(", "encoding", ")", "return", "s" ]
Inputs are encoded to utf-8 and then decoded to the desired output encoding @encoding: the desired encoding -> #str with the desired @encoding
[ "Inputs", "are", "encoded", "to", "utf", "-", "8", "and", "then", "decoded", "to", "the", "desired", "output", "encoding" ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L78-L88
train
jaredLunde/vital-tools
vital/tools/encoding.py
fix_bad_unicode
def fix_bad_unicode(text): u"""Copyright: http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ Something you will find all over the place, in real-world text, is text that's mistakenly encoded as utf-8, decoded in some ugly format like latin-1 or even Windows codepage 1252, and...
python
def fix_bad_unicode(text): u"""Copyright: http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ Something you will find all over the place, in real-world text, is text that's mistakenly encoded as utf-8, decoded in some ugly format like latin-1 or even Windows codepage 1252, and...
[ "def", "fix_bad_unicode", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "return", "text", "if", "len", "(", "text", ")", "==", "0", ":", "return", "text", "maxord", "=", "max", "(", "ord", "(", "char", ")", ...
u"""Copyright: http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ Something you will find all over the place, in real-world text, is text that's mistakenly encoded as utf-8, decoded in some ugly format like latin-1 or even Windows codepage 1252, and encoded as utf-8 again. T...
[ "u", "Copyright", ":", "http", ":", "//", "blog", ".", "luminoso", ".", "com", "/", "2012", "/", "08", "/", "20", "/", "fix", "-", "unicode", "-", "mistakes", "-", "with", "-", "python", "/" ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L91-L188
train
jaredLunde/vital-tools
vital/tools/encoding.py
text_badness
def text_badness(text): u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird things: - Adjacent letters from two different scripts - Letters ...
python
def text_badness(text): u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird things: - Adjacent letters from two different scripts - Letters ...
[ "def", "text_badness", "(", "text", ")", ":", "assert", "isinstance", "(", "text", ",", "str", ")", "errors", "=", "0", "very_weird_things", "=", "0", "weird_things", "=", "0", "prev_letter_script", "=", "None", "unicodedata_name", "=", "unicodedata", ".", "...
u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird things: - Adjacent letters from two different scripts - Letters in scripts that are very rar...
[ "u", "Look", "for", "red", "flags", "that", "text", "is", "encoded", "incorrectly", ":" ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L216-L279
train
cons3rt/pycons3rt
pycons3rt/osutil.py
get_pycons3rt_home_dir
def get_pycons3rt_home_dir(): """Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError """ if platform.system() == 'Linux': return os.path.join(os.path.sep, 'etc', 'pycons3rt') elif platform.system() == 'Windows': return os....
python
def get_pycons3rt_home_dir(): """Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError """ if platform.system() == 'Linux': return os.path.join(os.path.sep, 'etc', 'pycons3rt') elif platform.system() == 'Windows': return os....
[ "def", "get_pycons3rt_home_dir", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Linux'", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "sep", ",", "'etc'", ",", "'pycons3rt'", ")", "elif", "platform", ...
Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError
[ "Returns", "the", "pycons3rt", "home", "directory", "based", "on", "OS" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/osutil.py#L75-L88
train
cons3rt/pycons3rt
pycons3rt/osutil.py
initialize_pycons3rt_dirs
def initialize_pycons3rt_dirs(): """Initializes the pycons3rt directories :return: None :raises: OSError """ for pycons3rt_dir in [get_pycons3rt_home_dir(), get_pycons3rt_user_dir(), get_pycons3rt_conf_dir(), get_pycons3r...
python
def initialize_pycons3rt_dirs(): """Initializes the pycons3rt directories :return: None :raises: OSError """ for pycons3rt_dir in [get_pycons3rt_home_dir(), get_pycons3rt_user_dir(), get_pycons3rt_conf_dir(), get_pycons3r...
[ "def", "initialize_pycons3rt_dirs", "(", ")", ":", "for", "pycons3rt_dir", "in", "[", "get_pycons3rt_home_dir", "(", ")", ",", "get_pycons3rt_user_dir", "(", ")", ",", "get_pycons3rt_conf_dir", "(", ")", ",", "get_pycons3rt_log_dir", "(", ")", ",", "get_pycons3rt_sr...
Initializes the pycons3rt directories :return: None :raises: OSError
[ "Initializes", "the", "pycons3rt", "directories" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/osutil.py#L123-L143
train
cons3rt/pycons3rt
pycons3rt/osutil.py
main
def main(): # Create the pycons3rt directories try: initialize_pycons3rt_dirs() except OSError as ex: traceback.print_exc() return 1 # Replace log directory paths log_dir_path = get_pycons3rt_log_dir() + os.path.sep conf_contents = default_logging_conf_file_contents.re...
python
def main(): # Create the pycons3rt directories try: initialize_pycons3rt_dirs() except OSError as ex: traceback.print_exc() return 1 # Replace log directory paths log_dir_path = get_pycons3rt_log_dir() + os.path.sep conf_contents = default_logging_conf_file_contents.re...
[ "def", "main", "(", ")", ":", "# Create the pycons3rt directories", "try", ":", "initialize_pycons3rt_dirs", "(", ")", "except", "OSError", "as", "ex", ":", "traceback", ".", "print_exc", "(", ")", "return", "1", "# Replace log directory paths", "log_dir_path", "=",...
for line in fileinput.input(logging_config_file_dest, inplace=True): if re.search(replace_str, line): new_line = re.sub(replace_str, log_dir_path, line, count=0) sys.stdout.write(new_line) else: sys.stdout.write(line)
[ "for", "line", "in", "fileinput", ".", "input", "(", "logging_config_file_dest", "inplace", "=", "True", ")", ":", "if", "re", ".", "search", "(", "replace_str", "line", ")", ":", "new_line", "=", "re", ".", "sub", "(", "replace_str", "log_dir_path", "line...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/osutil.py#L146-L173
train
novopl/peltak
src/peltak/logic/git.py
add_hooks
def add_hooks(): # type: () -> None """ Add git hooks for commit and push to run linting and tests. """ # Detect virtualenv the hooks should use # Detect virtualenv virtual_env = conf.getenv('VIRTUAL_ENV') if virtual_env is None: log.err("You are not inside a virtualenv") confi...
python
def add_hooks(): # type: () -> None """ Add git hooks for commit and push to run linting and tests. """ # Detect virtualenv the hooks should use # Detect virtualenv virtual_env = conf.getenv('VIRTUAL_ENV') if virtual_env is None: log.err("You are not inside a virtualenv") confi...
[ "def", "add_hooks", "(", ")", ":", "# type: () -> None", "# Detect virtualenv the hooks should use", "# Detect virtualenv", "virtual_env", "=", "conf", ".", "getenv", "(", "'VIRTUAL_ENV'", ")", "if", "virtual_env", "is", "None", ":", "log", ".", "err", "(", "\"You a...
Add git hooks for commit and push to run linting and tests.
[ "Add", "git", "hooks", "for", "commit", "and", "push", "to", "run", "linting", "and", "tests", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/git.py#L35-L88
train
novopl/peltak
src/peltak/extra/gitflow/logic/feature.py
start
def start(name): # type: (str) -> None """ Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. """ feature_name = 'feature/' + common.to_branch_name(name) ...
python
def start(name): # type: (str) -> None """ Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. """ feature_name = 'feature/' + common.to_branch_name(name) ...
[ "def", "start", "(", "name", ")", ":", "# type: (str) -> None", "feature_name", "=", "'feature/'", "+", "common", ".", "to_branch_name", "(", "name", ")", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "common", ".", "a...
Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature.
[ "Start", "working", "on", "a", "new", "feature", "by", "branching", "off", "develop", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/feature.py#L30-L44
train
novopl/peltak
src/peltak/extra/gitflow/logic/feature.py
update
def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(refresh=True) develop = conf.get('git.devel_branch', 'develop') common.assert_branch_type('feature') commo...
python
def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(refresh=True) develop = conf.get('git.devel_branch', 'develop') common.assert_branch_type('feature') commo...
[ "def", "update", "(", ")", ":", "# type: () -> None", "branch", "=", "git", ".", "current_branch", "(", "refresh", "=", "True", ")", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "common", ".", "assert_branch_type", "(...
Update the feature with updates committed to develop. This will merge current develop into the current branch.
[ "Update", "the", "feature", "with", "updates", "committed", "to", "develop", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/feature.py#L47-L60
train
novopl/peltak
src/peltak/extra/gitflow/logic/feature.py
merged
def merged(): # type: () -> None """ Cleanup a remotely merged branch. """ develop = conf.get('git.devel_branch', 'develop') branch = git.current_branch(refresh=True) common.assert_branch_type('feature') # Pull develop with the merged feature common.git_checkout(develop) common.git_pul...
python
def merged(): # type: () -> None """ Cleanup a remotely merged branch. """ develop = conf.get('git.devel_branch', 'develop') branch = git.current_branch(refresh=True) common.assert_branch_type('feature') # Pull develop with the merged feature common.git_checkout(develop) common.git_pul...
[ "def", "merged", "(", ")", ":", "# type: () -> None", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "branch", "=", "git", ".", "current_branch", "(", "refresh", "=", "True", ")", "common", ".", "assert_branch_type", "(...
Cleanup a remotely merged branch.
[ "Cleanup", "a", "remotely", "merged", "branch", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/feature.py#L105-L121
train
novopl/peltak
src/peltak/logic/root.py
clean
def clean(exclude): # type: (bool, List[str]) -> None """ Remove all unnecessary files. Args: pretend (bool): If set to **True**, do not delete any files, just show what would be deleted. exclude (list[str]): A list of path patterns to exclude from deleti...
python
def clean(exclude): # type: (bool, List[str]) -> None """ Remove all unnecessary files. Args: pretend (bool): If set to **True**, do not delete any files, just show what would be deleted. exclude (list[str]): A list of path patterns to exclude from deleti...
[ "def", "clean", "(", "exclude", ")", ":", "# type: (bool, List[str]) -> None", "pretend", "=", "context", ".", "get", "(", "'pretend'", ",", "False", ")", "exclude", "=", "list", "(", "exclude", ")", "+", "conf", ".", "get", "(", "'clean.exclude'", ",", "[...
Remove all unnecessary files. Args: pretend (bool): If set to **True**, do not delete any files, just show what would be deleted. exclude (list[str]): A list of path patterns to exclude from deletion.
[ "Remove", "all", "unnecessary", "files", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/root.py#L38-L79
train
novopl/peltak
src/peltak/logic/root.py
init
def init(quick): # type: () -> None """ Create an empty pelconf.yaml from template """ config_file = 'pelconf.yaml' prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file) if exists(config_file) and not click.confirm(shell.fmt(prompt)): log.info("Canceled") return ...
python
def init(quick): # type: () -> None """ Create an empty pelconf.yaml from template """ config_file = 'pelconf.yaml' prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file) if exists(config_file) and not click.confirm(shell.fmt(prompt)): log.info("Canceled") return ...
[ "def", "init", "(", "quick", ")", ":", "# type: () -> None", "config_file", "=", "'pelconf.yaml'", "prompt", "=", "\"-- <35>{} <32>already exists. Wipe it?<0>\"", ".", "format", "(", "config_file", ")", "if", "exists", "(", "config_file", ")", "and", "not", "click",...
Create an empty pelconf.yaml from template
[ "Create", "an", "empty", "pelconf", ".", "yaml", "from", "template" ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/root.py#L114-L128
train
lmacken/tbgrep
tbgrep/__init__.py
tracebacks_from_lines
def tracebacks_from_lines(lines_iter): """Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings """ tbgrep = TracebackGrep() for line in lines_iter: tb ...
python
def tracebacks_from_lines(lines_iter): """Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings """ tbgrep = TracebackGrep() for line in lines_iter: tb ...
[ "def", "tracebacks_from_lines", "(", "lines_iter", ")", ":", "tbgrep", "=", "TracebackGrep", "(", ")", "for", "line", "in", "lines_iter", ":", "tb", "=", "tbgrep", ".", "process", "(", "line", ")", "if", "tb", ":", "yield", "tb" ]
Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings
[ "Generator", "that", "yields", "tracebacks", "found", "in", "a", "lines", "iterator" ]
3bc0030906d9bb82aebace585576c495111ba40c
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L64-L79
train
lmacken/tbgrep
tbgrep/__init__.py
tracebacks_from_file
def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. """ if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) ...
python
def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. """ if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) ...
[ "def", "tracebacks_from_file", "(", "fileobj", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "lines", "=", "deque", "(", ")", "for", "line", "in", "BackwardsReader", "(", "fileobj", ")", ":", "lines", ".", "appendleft", "(", "line", ")", ...
Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file.
[ "Generator", "that", "yields", "tracebacks", "found", "in", "a", "file", "object" ]
3bc0030906d9bb82aebace585576c495111ba40c
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L82-L98
train
lmacken/tbgrep
tbgrep/__init__.py
BackwardsReader
def BackwardsReader(file, BLKSIZE = 4096): """Read a file line by line, backwards""" buf = "" file.seek(0, 2) lastchar = file.read(1) trailing_newline = (lastchar == "\n") while 1: newline_pos = buf.rfind("\n") pos = file.tell() if newline_pos != -1: # Foun...
python
def BackwardsReader(file, BLKSIZE = 4096): """Read a file line by line, backwards""" buf = "" file.seek(0, 2) lastchar = file.read(1) trailing_newline = (lastchar == "\n") while 1: newline_pos = buf.rfind("\n") pos = file.tell() if newline_pos != -1: # Foun...
[ "def", "BackwardsReader", "(", "file", ",", "BLKSIZE", "=", "4096", ")", ":", "buf", "=", "\"\"", "file", ".", "seek", "(", "0", ",", "2", ")", "lastchar", "=", "file", ".", "read", "(", "1", ")", "trailing_newline", "=", "(", "lastchar", "==", "\"...
Read a file line by line, backwards
[ "Read", "a", "file", "line", "by", "line", "backwards" ]
3bc0030906d9bb82aebace585576c495111ba40c
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L110-L139
train
alvarosg/pynverse
pynverse/inverse.py
inversefunc
def inversefunc(func, y_values=None, domain=None, image=None, open_domain=None, args=(), accuracy=2): r"""Obtain the inverse of a function. Returns the numerical inverse of the function `f`. It may return a callable...
python
def inversefunc(func, y_values=None, domain=None, image=None, open_domain=None, args=(), accuracy=2): r"""Obtain the inverse of a function. Returns the numerical inverse of the function `f`. It may return a callable...
[ "def", "inversefunc", "(", "func", ",", "y_values", "=", "None", ",", "domain", "=", "None", ",", "image", "=", "None", ",", "open_domain", "=", "None", ",", "args", "=", "(", ")", ",", "accuracy", "=", "2", ")", ":", "domain", ",", "image", ",", ...
r"""Obtain the inverse of a function. Returns the numerical inverse of the function `f`. It may return a callable that can be used to calculate the inverse, or the inverse of certain points depending on the `y_values` argument. In order for the numerical inverse to exist in its domain, the input fu...
[ "r", "Obtain", "the", "inverse", "of", "a", "function", "." ]
ced4099bcebc49ef341ddccd8d4eccda5a5a7939
https://github.com/alvarosg/pynverse/blob/ced4099bcebc49ef341ddccd8d4eccda5a5a7939/pynverse/inverse.py#L9-L203
train
ASMfreaK/habitipy
habitipy/util.py
progressed_bar
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10): """render a progressed.io like progress bar""" status = status or '' suffix = suffix or '%' assert isinstance(count, int) count_normalized = count if count <= total else total filled_len = int(round(bar_len * count_norma...
python
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10): """render a progressed.io like progress bar""" status = status or '' suffix = suffix or '%' assert isinstance(count, int) count_normalized = count if count <= total else total filled_len = int(round(bar_len * count_norma...
[ "def", "progressed_bar", "(", "count", ",", "total", "=", "100", ",", "status", "=", "None", ",", "suffix", "=", "None", ",", "bar_len", "=", "10", ")", ":", "status", "=", "status", "or", "''", "suffix", "=", "suffix", "or", "'%'", "assert", "isinst...
render a progressed.io like progress bar
[ "render", "a", "progressed", ".", "io", "like", "progress", "bar" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L22-L42
train
ASMfreaK/habitipy
habitipy/util.py
prettify
def prettify(string): """ replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ``` """ ...
python
def prettify(string): """ replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ``` """ ...
[ "def", "prettify", "(", "string", ")", ":", "string", "=", "emojize", "(", "string", ",", "use_aliases", "=", "True", ")", "if", "emojize", "else", "string", "string", "=", "progressed", "(", "string", ")", "return", "string" ]
replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ```
[ "replace", "markup", "emoji", "and", "progressbars", "with", "actual", "things" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L89-L104
train
ASMfreaK/habitipy
habitipy/util.py
assert_secure_file
def assert_secure_file(file): """checks if a file is stored securely""" if not is_secure_file(file): msg = """ File {0} can be read by other users. This is not secure. Please run 'chmod 600 "{0}"'""" raise SecurityError(dedent(msg).replace('\n', ' ').format(file)) return True
python
def assert_secure_file(file): """checks if a file is stored securely""" if not is_secure_file(file): msg = """ File {0} can be read by other users. This is not secure. Please run 'chmod 600 "{0}"'""" raise SecurityError(dedent(msg).replace('\n', ' ').format(file)) return True
[ "def", "assert_secure_file", "(", "file", ")", ":", "if", "not", "is_secure_file", "(", "file", ")", ":", "msg", "=", "\"\"\"\n File {0} can be read by other users.\n This is not secure. Please run 'chmod 600 \"{0}\"'\"\"\"", "raise", "SecurityError", "(", "dedent...
checks if a file is stored securely
[ "checks", "if", "a", "file", "is", "stored", "securely" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L144-L151
train
ASMfreaK/habitipy
habitipy/util.py
get_translation_for
def get_translation_for(package_name: str) -> gettext.NullTranslations: """find and return gettext translation for package""" localedir = None for localedir in pkg_resources.resource_filename(package_name, 'i18n'), None: localefile = gettext.find(package_name, localedir) # type: ignore if l...
python
def get_translation_for(package_name: str) -> gettext.NullTranslations: """find and return gettext translation for package""" localedir = None for localedir in pkg_resources.resource_filename(package_name, 'i18n'), None: localefile = gettext.find(package_name, localedir) # type: ignore if l...
[ "def", "get_translation_for", "(", "package_name", ":", "str", ")", "->", "gettext", ".", "NullTranslations", ":", "localedir", "=", "None", "for", "localedir", "in", "pkg_resources", ".", "resource_filename", "(", "package_name", ",", "'i18n'", ")", ",", "None"...
find and return gettext translation for package
[ "find", "and", "return", "gettext", "translation", "for", "package" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L154-L163
train
ASMfreaK/habitipy
habitipy/util.py
get_translation_functions
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)): """finds and installs translation functions for package""" translation = get_translation_for(package_name) return [getattr(translation, x) for x in names]
python
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)): """finds and installs translation functions for package""" translation = get_translation_for(package_name) return [getattr(translation, x) for x in names]
[ "def", "get_translation_functions", "(", "package_name", ":", "str", ",", "names", ":", "Tuple", "[", "str", ",", "...", "]", "=", "(", "'gettext'", ",", ")", ")", ":", "translation", "=", "get_translation_for", "(", "package_name", ")", "return", "[", "ge...
finds and installs translation functions for package
[ "finds", "and", "installs", "translation", "functions", "for", "package" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L166-L169
train
ASMfreaK/habitipy
habitipy/api.py
escape_keywords
def escape_keywords(arr): """append _ to all python keywords""" for i in arr: i = i if i not in kwlist else i + '_' i = i if '-' not in i else i.replace('-', '_') yield i
python
def escape_keywords(arr): """append _ to all python keywords""" for i in arr: i = i if i not in kwlist else i + '_' i = i if '-' not in i else i.replace('-', '_') yield i
[ "def", "escape_keywords", "(", "arr", ")", ":", "for", "i", "in", "arr", ":", "i", "=", "i", "if", "i", "not", "in", "kwlist", "else", "i", "+", "'_'", "i", "=", "i", "if", "'-'", "not", "in", "i", "else", "i", ".", "replace", "(", "'-'", ","...
append _ to all python keywords
[ "append", "_", "to", "all", "python", "keywords" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L91-L96
train
ASMfreaK/habitipy
habitipy/api.py
download_api
def download_api(branch=None) -> str: """download API documentation from _branch_ of Habitica\'s repo on Github""" habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica' if not branch: branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name'] curl = local...
python
def download_api(branch=None) -> str: """download API documentation from _branch_ of Habitica\'s repo on Github""" habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica' if not branch: branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name'] curl = local...
[ "def", "download_api", "(", "branch", "=", "None", ")", "->", "str", ":", "habitica_github_api", "=", "'https://api.github.com/repos/HabitRPG/habitica'", "if", "not", "branch", ":", "branch", "=", "requests", ".", "get", "(", "habitica_github_api", "+", "'/releases/...
download API documentation from _branch_ of Habitica\'s repo on Github
[ "download", "API", "documentation", "from", "_branch_", "of", "Habitica", "\\", "s", "repo", "on", "Github" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L287-L297
train
ASMfreaK/habitipy
habitipy/api.py
save_apidoc
def save_apidoc(text: str) -> None: """save `text` to apidoc cache""" apidoc_local = local.path(APIDOC_LOCAL_FILE) if not apidoc_local.dirname.exists(): apidoc_local.dirname.mkdir() with open(apidoc_local, 'w') as f: f.write(text)
python
def save_apidoc(text: str) -> None: """save `text` to apidoc cache""" apidoc_local = local.path(APIDOC_LOCAL_FILE) if not apidoc_local.dirname.exists(): apidoc_local.dirname.mkdir() with open(apidoc_local, 'w') as f: f.write(text)
[ "def", "save_apidoc", "(", "text", ":", "str", ")", "->", "None", ":", "apidoc_local", "=", "local", ".", "path", "(", "APIDOC_LOCAL_FILE", ")", "if", "not", "apidoc_local", ".", "dirname", ".", "exists", "(", ")", ":", "apidoc_local", ".", "dirname", "....
save `text` to apidoc cache
[ "save", "text", "to", "apidoc", "cache" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L300-L306
train
ASMfreaK/habitipy
habitipy/api.py
parse_apidoc
def parse_apidoc( file_or_branch, from_github=False, save_github_version=True ) -> List['ApiEndpoint']: """read file and parse apiDoc lines""" apis = [] # type: List[ApiEndpoint] regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *' regex += r'(?P<field>[^ ]*) *(?P<description>.*)...
python
def parse_apidoc( file_or_branch, from_github=False, save_github_version=True ) -> List['ApiEndpoint']: """read file and parse apiDoc lines""" apis = [] # type: List[ApiEndpoint] regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *' regex += r'(?P<field>[^ ]*) *(?P<description>.*)...
[ "def", "parse_apidoc", "(", "file_or_branch", ",", "from_github", "=", "False", ",", "save_github_version", "=", "True", ")", "->", "List", "[", "'ApiEndpoint'", "]", ":", "apis", "=", "[", "]", "# type: List[ApiEndpoint]", "regex", "=", "r'(?P<group>\\([^)]*\\)){...
read file and parse apiDoc lines
[ "read", "file", "and", "parse", "apiDoc", "lines" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L309-L353
train
ASMfreaK/habitipy
habitipy/api.py
ApiNode.into
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
python
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
[ "def", "into", "(", "self", ",", "val", ":", "str", ")", "->", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ":", "if", "val", "in", "self", ".", "paths", ":", "return", "self", ".", "paths", "[", "val", "]", "if", "self", ".", "param", "...
Get another leaf node with name `val` if possible
[ "Get", "another", "leaf", "node", "with", "name", "val", "if", "possible" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L52-L58
train
ASMfreaK/habitipy
habitipy/api.py
ApiNode.can_into
def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
python
def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
[ "def", "can_into", "(", "self", ",", "val", ":", "str", ")", "->", "bool", ":", "return", "val", "in", "self", ".", "paths", "or", "(", "self", ".", "param", "and", "self", ".", "param_name", "==", "val", ")" ]
Determine if there is a leaf node with name `val`
[ "Determine", "if", "there", "is", "a", "leaf", "node", "with", "name", "val" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L60-L62
train
ASMfreaK/habitipy
habitipy/api.py
ApiNode.place
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
python
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
[ "def", "place", "(", "self", ",", "part", ":", "str", ",", "val", ":", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ")", ":", "if", "part", ".", "startswith", "(", "':'", ")", ":", "if", "self", ".", "param", "and", "self", ".", "param", ...
place a leaf node
[ "place", "a", "leaf", "node" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L64-L74
train
ASMfreaK/habitipy
habitipy/api.py
ApiNode.keys
def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
python
def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
[ "def", "keys", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "if", "self", ".", "param", ":", "yield", "self", ".", "param_name", "yield", "from", "self", ".", "paths", ".", "keys", "(", ")" ]
return all possible paths one can take from this ApiNode
[ "return", "all", "possible", "paths", "one", "can", "take", "from", "this", "ApiNode" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L76-L80
train
ASMfreaK/habitipy
habitipy/api.py
ApiEndpoint.add_param
def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p
python
def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p
[ "def", "add_param", "(", "self", ",", "group", "=", "None", ",", "type_", "=", "''", ",", "field", "=", "''", ",", "description", "=", "''", ")", ":", "group", "=", "group", "or", "'(Parameter)'", "group", "=", "group", ".", "lower", "(", ")", "[",...
parse and append a param
[ "parse", "and", "append", "a", "param" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L368-L373
train
ASMfreaK/habitipy
habitipy/api.py
ApiEndpoint.add_success
def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more re...
python
def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more re...
[ "def", "add_success", "(", "self", ",", "group", "=", "None", ",", "type_", "=", "''", ",", "field", "=", "''", ",", "description", "=", "''", ")", ":", "group", "=", "group", "or", "'(200)'", "group", "=", "int", "(", "group", ".", "lower", "(", ...
parse and append a success data param
[ "parse", "and", "append", "a", "success", "data", "param" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L375-L384
train
ASMfreaK/habitipy
habitipy/api.py
ApiEndpoint.render_docstring
def render_docstring(self): """make a nice docstring for ipython""" res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for param in params.v...
python
def render_docstring(self): """make a nice docstring for ipython""" res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for param in params.v...
[ "def", "render_docstring", "(", "self", ")", ":", "res", "=", "'{{{self.method}}} {self.uri} {self.title}\\n'", ".", "format", "(", "self", "=", "self", ")", "if", "self", ".", "params", ":", "for", "group", ",", "params", "in", "self", ".", "params", ".", ...
make a nice docstring for ipython
[ "make", "a", "nice", "docstring", "for", "ipython" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L389-L397
train
ASMfreaK/habitipy
habitipy/api.py
Param.validate
def validate(self, obj): """check if obj has this api param""" if self.path: for i in self.path: obj = obj[i] obj = obj[self.field] raise NotImplementedError('Validation is not implemented yet')
python
def validate(self, obj): """check if obj has this api param""" if self.path: for i in self.path: obj = obj[i] obj = obj[self.field] raise NotImplementedError('Validation is not implemented yet')
[ "def", "validate", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "path", ":", "for", "i", "in", "self", ".", "path", ":", "obj", "=", "obj", "[", "i", "]", "obj", "=", "obj", "[", "self", ".", "field", "]", "raise", "NotImplementedError",...
check if obj has this api param
[ "check", "if", "obj", "has", "this", "api", "param" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L439-L446
train
ASMfreaK/habitipy
habitipy/api.py
Param.render_docstring
def render_docstring(self): """make a nice docstring for ipython""" default = (' = ' + str(self.default)) if self.default else '' opt = 'optional' if self.is_optional else '' can_be = ' '.join(self.possible_values) if self.possible_values else '' can_be = 'one of [{}]'.format(can...
python
def render_docstring(self): """make a nice docstring for ipython""" default = (' = ' + str(self.default)) if self.default else '' opt = 'optional' if self.is_optional else '' can_be = ' '.join(self.possible_values) if self.possible_values else '' can_be = 'one of [{}]'.format(can...
[ "def", "render_docstring", "(", "self", ")", ":", "default", "=", "(", "' = '", "+", "str", "(", "self", ".", "default", ")", ")", "if", "self", ".", "default", "else", "''", "opt", "=", "'optional'", "if", "self", ".", "is_optional", "else", "''", "...
make a nice docstring for ipython
[ "make", "a", "nice", "docstring", "for", "ipython" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L448-L456
train
ASMfreaK/habitipy
habitipy/cli.py
is_uuid
def is_uuid(u): """validator for plumbum prompt""" if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex: return u return False
python
def is_uuid(u): """validator for plumbum prompt""" if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex: return u return False
[ "def", "is_uuid", "(", "u", ")", ":", "if", "isinstance", "(", "u", ",", "str", ")", "and", "u", ".", "replace", "(", "'-'", ",", "''", ")", "==", "uuid", ".", "UUID", "(", "u", ")", ".", "hex", ":", "return", "u", "return", "False" ]
validator for plumbum prompt
[ "validator", "for", "plumbum", "prompt" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L48-L52
train
ASMfreaK/habitipy
habitipy/cli.py
load_conf
def load_conf(configfile, config=None): """Get authentication data from the AUTH_CONF file.""" default_login = 'your-login-for-api-here' default_password = 'your-password-for-api-here' config = config or {} configfile = local.path(configfile) if not configfile.exists(): configfile.dirnam...
python
def load_conf(configfile, config=None): """Get authentication data from the AUTH_CONF file.""" default_login = 'your-login-for-api-here' default_password = 'your-password-for-api-here' config = config or {} configfile = local.path(configfile) if not configfile.exists(): configfile.dirnam...
[ "def", "load_conf", "(", "configfile", ",", "config", "=", "None", ")", ":", "default_login", "=", "'your-login-for-api-here'", "default_password", "=", "'your-password-for-api-here'", "config", "=", "config", "or", "{", "}", "configfile", "=", "local", ".", "path...
Get authentication data from the AUTH_CONF file.
[ "Get", "authentication", "data", "from", "the", "AUTH_CONF", "file", "." ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L55-L97
train
ASMfreaK/habitipy
habitipy/cli.py
get_content
def get_content(api, rebuild_cache=False): """get content from server or cache""" if hasattr(get_content, 'cache') and not rebuild_cache: return get_content.cache if not os.path.exists(CONTENT_JSON) or rebuild_cache: import locale content_endpoint = api.content.get # pylint: ...
python
def get_content(api, rebuild_cache=False): """get content from server or cache""" if hasattr(get_content, 'cache') and not rebuild_cache: return get_content.cache if not os.path.exists(CONTENT_JSON) or rebuild_cache: import locale content_endpoint = api.content.get # pylint: ...
[ "def", "get_content", "(", "api", ",", "rebuild_cache", "=", "False", ")", ":", "if", "hasattr", "(", "get_content", ",", "'cache'", ")", "and", "not", "rebuild_cache", ":", "return", "get_content", ".", "cache", "if", "not", "os", ".", "path", ".", "exi...
get content from server or cache
[ "get", "content", "from", "server", "or", "cache" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L126-L164
train
ASMfreaK/habitipy
habitipy/cli.py
get_additional_rewards
def get_additional_rewards(api): """returns list of non-user rewards (potion, armoire, gear)""" c = get_content(api) tasks = [c[i] for i in ['potion', 'armoire']] tasks.extend(api.user.inventory.buy.get()) for task in tasks: task['id'] = task['alias'] = task['key'] return tasks
python
def get_additional_rewards(api): """returns list of non-user rewards (potion, armoire, gear)""" c = get_content(api) tasks = [c[i] for i in ['potion', 'armoire']] tasks.extend(api.user.inventory.buy.get()) for task in tasks: task['id'] = task['alias'] = task['key'] return tasks
[ "def", "get_additional_rewards", "(", "api", ")", ":", "c", "=", "get_content", "(", "api", ")", "tasks", "=", "[", "c", "[", "i", "]", "for", "i", "in", "[", "'potion'", ",", "'armoire'", "]", "]", "tasks", ".", "extend", "(", "api", ".", "user", ...
returns list of non-user rewards (potion, armoire, gear)
[ "returns", "list", "of", "non", "-", "user", "rewards", "(", "potion", "armoire", "gear", ")" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L365-L372
train
ASMfreaK/habitipy
habitipy/cli.py
ScoreInfo.color
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
python
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
[ "def", "color", "(", "cls", ",", "value", ")", ":", "index", "=", "bisect", "(", "cls", ".", "breakpoints", ",", "value", ")", "return", "colors", ".", "fg", "(", "cls", ".", "colors_", "[", "index", "]", ")" ]
task value/score color
[ "task", "value", "/", "score", "color" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L289-L292
train
maxalbert/tohu
tohu/v6/custom_generator/custom_generator.py
augment_init_method
def augment_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): super(CustomGenerator, self).__init__() # TODO: does this ...
python
def augment_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): super(CustomGenerator, self).__init__() # TODO: does this ...
[ "def", "augment_init_method", "(", "cls", ")", ":", "orig_init", "=", "cls", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "CustomGenerator", ",", "self", ")", ".", "__init__", "(", ...
Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping.
[ "Replace", "the", "existing", "cls", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "also", "initialises", "the", "field", "generators", "and", "similar", "bookkeeping", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/custom_generator.py#L9-L39
train
maxalbert/tohu
tohu/v2/custom_generator.py
find_field_generators
def find_field_generators(obj): """ Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces. """ cls_dict = obj.__class__.__dict__ obj_dict = obj.__dict__ #debug_print_dict(cls_dict, 'cls_dict') #debug_prin...
python
def find_field_generators(obj): """ Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces. """ cls_dict = obj.__class__.__dict__ obj_dict = obj.__dict__ #debug_print_dict(cls_dict, 'cls_dict') #debug_prin...
[ "def", "find_field_generators", "(", "obj", ")", ":", "cls_dict", "=", "obj", ".", "__class__", ".", "__dict__", "obj_dict", "=", "obj", ".", "__dict__", "#debug_print_dict(cls_dict, 'cls_dict')", "#debug_print_dict(obj_dict, 'obj_dict')", "field_gens", "=", "{", "}", ...
Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces.
[ "Return", "dictionary", "with", "the", "names", "and", "instances", "of", "all", "tohu", ".", "BaseGenerator", "occurring", "in", "the", "given", "object", "s", "class", "&", "instance", "namespaces", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L20-L36
train
maxalbert/tohu
tohu/v2/custom_generator.py
set_item_class_name
def set_item_class_name(cls_obj): """ Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux """ if '__tohu__items__name__' in...
python
def set_item_class_name(cls_obj): """ Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux """ if '__tohu__items__name__' in...
[ "def", "set_item_class_name", "(", "cls_obj", ")", ":", "if", "'__tohu__items__name__'", "in", "cls_obj", ".", "__dict__", ":", "logger", ".", "debug", "(", "f\"Using item class name '{cls_obj.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')\"", ")", "else",...
Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux
[ "Return", "the", "first", "part", "of", "the", "class", "name", "of", "this", "custom", "generator", ".", "This", "will", "be", "used", "for", "the", "class", "name", "of", "the", "items", "produced", "by", "this", "generator", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L39-L59
train
maxalbert/tohu
tohu/v2/custom_generator.py
make_item_class_for_custom_generator
def make_item_class_for_custom_generator(obj): """ obj: The custom generator instance for which to create an item class """ clsname = obj.__tohu_items_name__ attr_names = obj.field_gens.keys() return make_item_class(clsname, attr_names)
python
def make_item_class_for_custom_generator(obj): """ obj: The custom generator instance for which to create an item class """ clsname = obj.__tohu_items_name__ attr_names = obj.field_gens.keys() return make_item_class(clsname, attr_names)
[ "def", "make_item_class_for_custom_generator", "(", "obj", ")", ":", "clsname", "=", "obj", ".", "__tohu_items_name__", "attr_names", "=", "obj", ".", "field_gens", ".", "keys", "(", ")", "return", "make_item_class", "(", "clsname", ",", "attr_names", ")" ]
obj: The custom generator instance for which to create an item class
[ "obj", ":", "The", "custom", "generator", "instance", "for", "which", "to", "create", "an", "item", "class" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L108-L115
train
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_init_method
def add_new_init_method(obj): """ Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. ...
python
def add_new_init_method(obj): """ Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. ...
[ "def", "add_new_init_method", "(", "obj", ")", ":", "orig_init", "=", "obj", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "f\"Initialising new {self}\"", ")", "# Call ori...
Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. (2) ..to do..
[ "Replace", "the", "existing", "obj", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "calls", "the", "original", "one", "and", "in", "addition", "performs", "the", "following", "actions", ":" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L118-L192
train
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_reset_method
def add_new_reset_method(obj): """ Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`. """ # # Create and assign automatically generated reset() method # def ne...
python
def add_new_reset_method(obj): """ Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`. """ # # Create and assign automatically generated reset() method # def ne...
[ "def", "add_new_reset_method", "(", "obj", ")", ":", "#", "# Create and assign automatically generated reset() method", "#", "def", "new_reset", "(", "self", ",", "seed", "=", "None", ")", ":", "logger", ".", "debug", "(", "f'[EEE] Inside automatically generated reset()...
Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`.
[ "Attach", "a", "new", "reset", "()", "method", "to", "obj", "which", "resets", "the", "internal", "seed", "generator", "of", "obj", "and", "then", "resets", "each", "of", "its", "constituent", "field", "generators", "found", "in", "obj", ".", "field_gens", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L195-L225
train
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_next_method
def add_new_next_method(obj): """ TODO """ def new_next(self): field_values = [next(g) for g in self.field_gens.values()] return self.item_cls(*field_values) obj.__next__ = new_next
python
def add_new_next_method(obj): """ TODO """ def new_next(self): field_values = [next(g) for g in self.field_gens.values()] return self.item_cls(*field_values) obj.__next__ = new_next
[ "def", "add_new_next_method", "(", "obj", ")", ":", "def", "new_next", "(", "self", ")", ":", "field_values", "=", "[", "next", "(", "g", ")", "for", "g", "in", "self", ".", "field_gens", ".", "values", "(", ")", "]", "return", "self", ".", "item_cls...
TODO
[ "TODO" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L228-L237
train
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_spawn_method
def add_new_spawn_method(obj): """ TODO """ def new_spawn(self): # TODO/FIXME: Check that this does the right thing: # (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour) # (ii) ensure that it...
python
def add_new_spawn_method(obj): """ TODO """ def new_spawn(self): # TODO/FIXME: Check that this does the right thing: # (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour) # (ii) ensure that it...
[ "def", "add_new_spawn_method", "(", "obj", ")", ":", "def", "new_spawn", "(", "self", ")", ":", "# TODO/FIXME: Check that this does the right thing:", "# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviou...
TODO
[ "TODO" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L240-L252
train