partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
ExtensibleByHashType._
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): ...
extend_me.py
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'): """ Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass ...
[ "Method", "to", "generate", "real", "metaclass", "to", "be", "used", "::" ]
katyukha/extend-me
python
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L593-L623
[ "def", "_", "(", "mcs", ",", "cls_name", "=", "'Object'", ",", "with_meta", "=", "None", ",", "hashattr", "=", "'_name'", ")", ":", "extype", "=", "super", "(", "ExtensibleByHashType", ",", "mcs", ")", ".", "_", "(", "cls_name", "=", "cls_name", ",", ...
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
train
ExtensibleByHashType.get_class
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) ...
extend_me.py
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): """ 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 ...
[ "Generates", "new", "class", "to", "gether", "logic", "of", "all", "available", "extensions", "::" ]
katyukha/extend-me
python
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L626-L663
[ "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'\"", ...
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
train
ExtensibleByHashType.get_registered_names
Return's list of names (keys) registered in this tree. For each name specific classes exists
extend_me.py
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'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]
[ "Return", "s", "list", "of", "names", "(", "keys", ")", "registered", "in", "this", "tree", ".", "For", "each", "name", "specific", "classes", "exists" ]
katyukha/extend-me
python
https://github.com/katyukha/extend-me/blob/d45bc7bfcf071740ff927e7c4b8b035dbee75c13/extend_me.py#L673-L677
[ "def", "get_registered_names", "(", "mcs", ")", ":", "return", "[", "k", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "mcs", ".", "_base_classes_hash", ")", "if", "v", "]" ]
d45bc7bfcf071740ff927e7c4b8b035dbee75c13
train
get_last_day_of_month
Returns day number of the last day of the month :param t: datetime :return: int
jutil/dates.py
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: """ 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
[ "Returns", "day", "number", "of", "the", "last", "day", "of", "the", "month", ":", "param", "t", ":", "datetime", ":", "return", ":", "int" ]
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L37-L46
[ "def", "get_last_day_of_month", "(", "t", ":", "datetime", ")", "->", "int", ":", "tn", "=", "t", "+", "timedelta", "(", "days", "=", "32", ")", "tn", "=", "datetime", "(", "year", "=", "tn", ".", "year", ",", "month", "=", "tn", ".", "month", ",...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
localize_time_range
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
jutil/dates.py
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): """ 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: ...
[ "Localizes", "time", "range", ".", "Uses", "pytz", ".", "utc", "if", "None", "provided", ".", ":", "param", "begin", ":", "Begin", "datetime", ":", "param", "end", ":", "End", "datetime", ":", "param", "tz", ":", "pytz", "timezone", "or", "None", "(", ...
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L49-L59
[ "def", "localize_time_range", "(", "begin", ":", "datetime", ",", "end", ":", "datetime", ",", "tz", "=", "None", ")", "->", "(", "datetime", ",", "datetime", ")", ":", "if", "not", "tz", ":", "tz", "=", "pytz", ".", "utc", "return", "tz", ".", "lo...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
this_week
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)
jutil/dates.py
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): """ 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...
[ "Returns", "this", "week", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(", "defaults", "pytz", ...
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L62-L73
[ "def", "this_week", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "today", "-", "timedelta", "(", "days", "=", "today...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
this_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)
jutil/dates.py
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): """ 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...
[ "Returns", "current", "month", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "in", "the", "month", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", ...
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L76-L88
[ "def", "this_month", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "datetime", "(", "day", "=", "1", ",", "month", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
next_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)
jutil/dates.py
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): """ 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...
[ "Returns", "next", "month", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "in", "the", "month", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(...
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L105-L119
[ "def", "next_month", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "datetime", "(", "day", "=", "1", ",", "month", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
last_year
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)
jutil/dates.py
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): """ 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...
[ "Returns", "last", "year", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(", "defaults", "pytz", ...
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L151-L163
[ "def", "last_year", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "end", "=", "datetime", "(", "day", "=", "1", ",", "month", "="...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
add_month
Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime
jutil/dates.py
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: """ 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....
[ "Adds", "+", "-", "n", "months", "to", "datetime", ".", "Clamps", "to", "number", "of", "days", "in", "given", "month", ".", ":", "param", "t", ":", "datetime", ":", "param", "n", ":", "count", ":", "return", ":", "datetime" ]
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L181-L200
[ "def", "add_month", "(", "t", ":", "datetime", ",", "n", ":", "int", "=", "1", ")", "->", "datetime", ":", "t2", "=", "t", "for", "count", "in", "range", "(", "abs", "(", "n", ")", ")", ":", "if", "n", ">", "0", ":", "t2", "=", "datetime", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
per_delta
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)
jutil/dates.py
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): """ 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*...
[ "Iterates", "over", "time", "range", "in", "steps", "specified", "in", "delta", "." ]
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L203-L217
[ "def", "per_delta", "(", "start", ":", "datetime", ",", "end", ":", "datetime", ",", "delta", ":", "timedelta", ")", ":", "curr", "=", "start", "while", "curr", "<", "end", ":", "curr_end", "=", "curr", "+", "delta", "yield", "curr", ",", "curr_end", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
per_month
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), ....
jutil/dates.py
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): """ 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...
[ "Iterates", "over", "time", "range", "in", "one", "month", "steps", ".", "Clamps", "to", "number", "of", "days", "in", "given", "month", "." ]
kajala/django-jutil
python
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L220-L235
[ "def", "per_month", "(", "start", ":", "datetime", ",", "end", ":", "datetime", ",", "n", ":", "int", "=", "1", ")", ":", "curr", "=", "start", ".", "replace", "(", "day", "=", "1", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second",...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
train
get_requirements
Return the requirements as a list of string.
setup.py
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]: """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()
[ "Return", "the", "requirements", "as", "a", "list", "of", "string", "." ]
MarcAureleCoste/sqla-filters
python
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/setup.py#L14-L20
[ "def", "get_requirements", "(", ")", "->", "List", "[", "str", "]", ":", "requirements_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'requirements.txt'", ")", "with", "open", "(", "requi...
a9596f660a11d275bf0e831ecd9e502b0af2a087
train
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 commands to work.
src/peltak/commands/root.py
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(): """ 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...
[ "List", "requirements", "for", "peltak", "commands", "configured", "for", "the", "project", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/root.py#L89-L100
[ "def", "project_dev_requirements", "(", ")", ":", "from", "peltak", ".", "core", "import", "conf", "from", "peltak", ".", "core", "import", "shell", "for", "dep", "in", "sorted", "(", "conf", ".", "requirements", ")", ":", "shell", ".", "cprint", "(", "d...
b627acc019e3665875fe76cdca0a14773b69beaa
train
get_func_params
:type method: function :type called_params: dict :return:
aioapp/misc.py
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): """ :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...
[ ":", "type", "method", ":", "function", ":", "type", "called_params", ":", "dict", ":", "return", ":" ]
inplat/aioapp
python
https://github.com/inplat/aioapp/blob/4ccb026264eaab69806512b58681c0b2f9544621/aioapp/misc.py#L60-L96
[ "def", "get_func_params", "(", "method", ",", "called_params", ")", ":", "insp", "=", "inspect", ".", "getfullargspec", "(", "method", ")", "if", "not", "isinstance", "(", "called_params", ",", "dict", ")", ":", "raise", "UserWarning", "(", ")", "_called_par...
4ccb026264eaab69806512b58681c0b2f9544621
train
parse_dsn
Разбирает строку подключения к БД и возвращает список из (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...
aioapp/misc.py
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://'): """ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type de...
[ "Разбирает", "строку", "подключения", "к", "БД", "и", "возвращает", "список", "из", "(", "host", "port", "username", "password", "dbname", ")" ]
inplat/aioapp
python
https://github.com/inplat/aioapp/blob/4ccb026264eaab69806512b58681c0b2f9544621/aioapp/misc.py#L124-L146
[ "def", "parse_dsn", "(", "dsn", ",", "default_port", "=", "5432", ",", "protocol", "=", "'http://'", ")", ":", "parsed", "=", "urlparse", "(", "protocol", "+", "dsn", ")", "return", "[", "parsed", ".", "hostname", "or", "'localhost'", ",", "parsed", ".",...
4ccb026264eaab69806512b58681c0b2f9544621
train
build_images
Build all docker images for the project.
src/peltak/extra/docker/logic.py
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 """ 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)
[ "Build", "all", "docker", "images", "for", "the", "project", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L34-L41
[ "def", "build_images", "(", ")", ":", "# type: () -> None", "registry", "=", "conf", ".", "get", "(", "'docker.registry'", ")", "docker_images", "=", "conf", ".", "get", "(", "'docker.images'", ",", "[", "]", ")", "for", "image", "in", "docker_images", ":", ...
b627acc019e3665875fe76cdca0a14773b69beaa
train
push_images
Push all project docker images to a remote registry.
src/peltak/extra/docker/logic.py
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 """ 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...
[ "Push", "all", "project", "docker", "images", "to", "a", "remote", "registry", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L44-L55
[ "def", "push_images", "(", ")", ":", "# type: () -> None", "registry", "=", "conf", ".", "get", "(", "'docker.registry'", ")", "docker_images", "=", "conf", ".", "get", "(", "'docker.images'", ",", "[", "]", ")", "if", "registry", "is", "None", ":", "log",...
b627acc019e3665875fe76cdca0a14773b69beaa
train
docker_list
List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password.
src/peltak/extra/docker/logic.py
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 """ 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...
[ "List", "docker", "images", "stored", "in", "the", "remote", "registry", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L58-L84
[ "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...
b627acc019e3665875fe76cdca0a14773b69beaa
train
build_image
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 ...
src/peltak/extra/docker/logic.py
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 """ 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]): ...
[ "Build", "docker", "image", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L87-L126
[ "def", "build_image", "(", "registry", ",", "image", ")", ":", "# type: (str, Dict[str, Any]) -> None", "if", "':'", "in", "image", "[", "'name'", "]", ":", "_", ",", "tag", "=", "image", "[", "'name'", "]", ".", "split", "(", "':'", ",", "1", ")", "el...
b627acc019e3665875fe76cdca0a14773b69beaa
train
push_image
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...
src/peltak/extra/docker/logic.py
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 """ 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)://) ...
[ "Push", "the", "given", "image", "to", "selected", "repository", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/logic.py#L129-L147
[ "def", "push_image", "(", "registry", ",", "image", ")", ":", "# type: (str, Dict[str, Any]) -> None", "values", "=", "{", "'registry'", ":", "registry", ",", "'image'", ":", "image", "[", "'name'", "]", ",", "}", "log", ".", "info", "(", "\"Pushing <33>{regis...
b627acc019e3665875fe76cdca0a14773b69beaa
train
OPR._build_opr_data
Returns a well formatted OPR data
paydunya/opr.py
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): """Returns a well formatted OPR data""" return { "invoice_data": { "invoice": { "total_amount": data.get("total_amount"), "description": data.get("description") }, ...
[ "Returns", "a", "well", "formatted", "OPR", "data" ]
paydunya/paydunya-python
python
https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L13-L26
[ "def", "_build_opr_data", "(", "self", ",", "data", ",", "store", ")", ":", "return", "{", "\"invoice_data\"", ":", "{", "\"invoice\"", ":", "{", "\"total_amount\"", ":", "data", ".", "get", "(", "\"total_amount\"", ")", ",", "\"description\"", ":", "data", ...
bb55791e2814788aec74162d9d78970815f37c30
train
OPR.create
Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token
paydunya/opr.py
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): """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...
[ "Initiazes", "an", "OPR" ]
paydunya/paydunya-python
python
https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L28-L36
[ "def", "create", "(", "self", ",", "data", "=", "{", "}", ",", "store", "=", "None", ")", ":", "_store", "=", "store", "or", "self", ".", "store", "_data", "=", "self", ".", "_build_opr_data", "(", "data", ",", "_store", ")", "if", "data", "else", ...
bb55791e2814788aec74162d9d78970815f37c30
train
OPR.charge
Second stage of an OPR request
paydunya/opr.py
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): """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)
[ "Second", "stage", "of", "an", "OPR", "request" ]
paydunya/paydunya-python
python
https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L38-L45
[ "def", "charge", "(", "self", ",", "data", ")", ":", "token", "=", "data", ".", "get", "(", "\"token\"", ",", "self", ".", "_response", "[", "\"token\"", "]", ")", "data", "=", "{", "\"token\"", ":", "token", ",", "\"confirm_token\"", ":", "data", "....
bb55791e2814788aec74162d9d78970815f37c30
train
Form.get_value
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...
src/cliform/core.py
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 """ 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...
[ "Ask", "user", "the", "question", "represented", "by", "this", "instance", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/cliform/core.py#L123-L157
[ "def", "get_value", "(", "self", ",", "field", ",", "quick", ")", ":", "# type: (Field, bool) -> Any", "if", "callable", "(", "field", ".", "default", ")", ":", "default", "=", "field", ".", "default", "(", "self", ")", "else", ":", "default", "=", "fiel...
b627acc019e3665875fe76cdca0a14773b69beaa
train
ImageUtil.update_image
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
pycons3rt/awsapi/images.py
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): """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...
cons3rt/pycons3rt
python
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/images.py#L70-L207
[ "def", "update_image", "(", "self", ",", "ami_id", ",", "instance_id", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.update_image'", ")", "if", "not", "isinstance", "(", "ami_id", ",", "basestring", ")", ":", ...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
train
ImageUtil.create_cons3rt_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) Description of the new image :return: None
pycons3rt/awsapi/images.py
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'): """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) ...
[ "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",...
cons3rt/pycons3rt
python
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/images.py#L209-L266
[ "def", "create_cons3rt_template", "(", "self", ",", "instance_id", ",", "name", ",", "description", "=", "'CONS3RT OS template'", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.create_cons3rt_template'", ")", "if", "no...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
train
ImageUtil.copy_cons3rt_template
:param ami_id: :return:
pycons3rt/awsapi/images.py
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): """ :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],...
[ ":", "param", "ami_id", ":", ":", "return", ":" ]
cons3rt/pycons3rt
python
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/awsapi/images.py#L268-L300
[ "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", ...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
train
uniorbytes
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...
vital/tools/encoding.py
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"): """ 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 @...
[ "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", "." ]
jaredLunde/vital-tools
python
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L36-L75
[ "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...
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
train
recode_unicode
Inputs are encoded to utf-8 and then decoded to the desired output encoding @encoding: the desired encoding -> #str with the desired @encoding
vital/tools/encoding.py
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'): """ 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
[ "Inputs", "are", "encoded", "to", "utf", "-", "8", "and", "then", "decoded", "to", "the", "desired", "output", "encoding" ]
jaredLunde/vital-tools
python
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L78-L88
[ "def", "recode_unicode", "(", "s", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", ":", "return", "s", ".", "encode", "(", ")", ".", "decode", "(", "encoding", ")", "return", "s" ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
train
fix_bad_unicode
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...
vital/tools/encoding.py
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): 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...
[ "u", "Copyright", ":", "http", ":", "//", "blog", ".", "luminoso", ".", "com", "/", "2012", "/", "08", "/", "20", "/", "fix", "-", "unicode", "-", "mistakes", "-", "with", "-", "python", "/" ]
jaredLunde/vital-tools
python
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L91-L188
[ "def", "fix_bad_unicode", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "return", "text", "if", "len", "(", "text", ")", "==", "0", ":", "return", "text", "maxord", "=", "max", "(", "ord", "(", "char", ")", ...
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
train
text_badness
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...
vital/tools/encoding.py
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): 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 ...
[ "u", "Look", "for", "red", "flags", "that", "text", "is", "encoded", "incorrectly", ":" ]
jaredLunde/vital-tools
python
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L216-L279
[ "def", "text_badness", "(", "text", ")", ":", "assert", "isinstance", "(", "text", ",", "str", ")", "errors", "=", "0", "very_weird_things", "=", "0", "weird_things", "=", "0", "prev_letter_script", "=", "None", "unicodedata_name", "=", "unicodedata", ".", "...
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
train
get_pycons3rt_home_dir
Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError
pycons3rt/osutil.py
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(): """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....
[ "Returns", "the", "pycons3rt", "home", "directory", "based", "on", "OS" ]
cons3rt/pycons3rt
python
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/osutil.py#L75-L88
[ "def", "get_pycons3rt_home_dir", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Linux'", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "sep", ",", "'etc'", ",", "'pycons3rt'", ")", "elif", "platform", ...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
train
initialize_pycons3rt_dirs
Initializes the pycons3rt directories :return: None :raises: OSError
pycons3rt/osutil.py
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(): """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...
[ "Initializes", "the", "pycons3rt", "directories" ]
cons3rt/pycons3rt
python
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/osutil.py#L123-L143
[ "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...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
train
main
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)
pycons3rt/osutil.py
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 = get_pycons3rt_log_dir() + os.path.sep conf_contents = default_logging_conf_file_contents.re...
[ "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...
cons3rt/pycons3rt
python
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/osutil.py#L146-L173
[ "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", "=",...
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
train
add_hooks
Add git hooks for commit and push to run linting and tests.
src/peltak/logic/git.py
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 """ 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...
[ "Add", "git", "hooks", "for", "commit", "and", "push", "to", "run", "linting", "and", "tests", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/git.py#L35-L88
[ "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...
b627acc019e3665875fe76cdca0a14773b69beaa
train
start
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.
src/peltak/extra/gitflow/logic/feature.py
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 """ 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) ...
[ "Start", "working", "on", "a", "new", "feature", "by", "branching", "off", "develop", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/feature.py#L30-L44
[ "def", "start", "(", "name", ")", ":", "# type: (str) -> None", "feature_name", "=", "'feature/'", "+", "common", ".", "to_branch_name", "(", "name", ")", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "common", ".", "a...
b627acc019e3665875fe76cdca0a14773b69beaa
train
update
Update the feature with updates committed to develop. This will merge current develop into the current branch.
src/peltak/extra/gitflow/logic/feature.py
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 """ 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...
[ "Update", "the", "feature", "with", "updates", "committed", "to", "develop", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/feature.py#L47-L60
[ "def", "update", "(", ")", ":", "# type: () -> None", "branch", "=", "git", ".", "current_branch", "(", "refresh", "=", "True", ")", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "common", ".", "assert_branch_type", "(...
b627acc019e3665875fe76cdca0a14773b69beaa
train
merged
Cleanup a remotely merged branch.
src/peltak/extra/gitflow/logic/feature.py
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 """ 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...
[ "Cleanup", "a", "remotely", "merged", "branch", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/feature.py#L105-L121
[ "def", "merged", "(", ")", ":", "# type: () -> None", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "branch", "=", "git", ".", "current_branch", "(", "refresh", "=", "True", ")", "common", ".", "assert_branch_type", "(...
b627acc019e3665875fe76cdca0a14773b69beaa
train
clean
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.
src/peltak/logic/root.py
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 """ 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...
[ "Remove", "all", "unnecessary", "files", "." ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/root.py#L38-L79
[ "def", "clean", "(", "exclude", ")", ":", "# type: (bool, List[str]) -> None", "pretend", "=", "context", ".", "get", "(", "'pretend'", ",", "False", ")", "exclude", "=", "list", "(", "exclude", ")", "+", "conf", ".", "get", "(", "'clean.exclude'", ",", "[...
b627acc019e3665875fe76cdca0a14773b69beaa
train
init
Create an empty pelconf.yaml from template
src/peltak/logic/root.py
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 """ 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 ...
[ "Create", "an", "empty", "pelconf", ".", "yaml", "from", "template" ]
novopl/peltak
python
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/root.py#L114-L128
[ "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",...
b627acc019e3665875fe76cdca0a14773b69beaa
train
tracebacks_from_lines
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/__init__.py
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): """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 ...
[ "Generator", "that", "yields", "tracebacks", "found", "in", "a", "lines", "iterator" ]
lmacken/tbgrep
python
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L64-L79
[ "def", "tracebacks_from_lines", "(", "lines_iter", ")", ":", "tbgrep", "=", "TracebackGrep", "(", ")", "for", "line", "in", "lines_iter", ":", "tb", "=", "tbgrep", ".", "process", "(", "line", ")", "if", "tb", ":", "yield", "tb" ]
3bc0030906d9bb82aebace585576c495111ba40c
train
tracebacks_from_file
Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file.
tbgrep/__init__.py
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): """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) ...
[ "Generator", "that", "yields", "tracebacks", "found", "in", "a", "file", "object" ]
lmacken/tbgrep
python
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L82-L98
[ "def", "tracebacks_from_file", "(", "fileobj", ",", "reverse", "=", "False", ")", ":", "if", "reverse", ":", "lines", "=", "deque", "(", ")", "for", "line", "in", "BackwardsReader", "(", "fileobj", ")", ":", "lines", ".", "appendleft", "(", "line", ")", ...
3bc0030906d9bb82aebace585576c495111ba40c
train
BackwardsReader
Read a file line by line, backwards
tbgrep/__init__.py
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): """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...
[ "Read", "a", "file", "line", "by", "line", "backwards" ]
lmacken/tbgrep
python
https://github.com/lmacken/tbgrep/blob/3bc0030906d9bb82aebace585576c495111ba40c/tbgrep/__init__.py#L110-L139
[ "def", "BackwardsReader", "(", "file", ",", "BLKSIZE", "=", "4096", ")", ":", "buf", "=", "\"\"", "file", ".", "seek", "(", "0", ",", "2", ")", "lastchar", "=", "file", ".", "read", "(", "1", ")", "trailing_newline", "=", "(", "lastchar", "==", "\"...
3bc0030906d9bb82aebace585576c495111ba40c
train
inversefunc
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...
pynverse/inverse.py
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): r"""Obtain the inverse of a function. Returns the numerical inverse of the function `f`. It may return a callable...
[ "r", "Obtain", "the", "inverse", "of", "a", "function", "." ]
alvarosg/pynverse
python
https://github.com/alvarosg/pynverse/blob/ced4099bcebc49ef341ddccd8d4eccda5a5a7939/pynverse/inverse.py#L9-L203
[ "def", "inversefunc", "(", "func", ",", "y_values", "=", "None", ",", "domain", "=", "None", ",", "image", "=", "None", ",", "open_domain", "=", "None", ",", "args", "=", "(", ")", ",", "accuracy", "=", "2", ")", ":", "domain", ",", "image", ",", ...
ced4099bcebc49ef341ddccd8d4eccda5a5a7939
train
progressed_bar
render a progressed.io like progress bar
habitipy/util.py
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): """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...
[ "render", "a", "progressed", ".", "io", "like", "progress", "bar" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L22-L42
[ "def", "progressed_bar", "(", "count", ",", "total", "=", "100", ",", "status", "=", "None", ",", "suffix", "=", "None", ",", "bar_len", "=", "10", ")", ":", "status", "=", "status", "or", "''", "suffix", "=", "suffix", "or", "'%'", "assert", "isinst...
555b8b20faf6d553353092614a8a0d612f0adbde
train
prettify
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% ```
habitipy/util.py
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): """ 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" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L89-L104
[ "def", "prettify", "(", "string", ")", ":", "string", "=", "emojize", "(", "string", ",", "use_aliases", "=", "True", ")", "if", "emojize", "else", "string", "string", "=", "progressed", "(", "string", ")", "return", "string" ]
555b8b20faf6d553353092614a8a0d612f0adbde
train
assert_secure_file
checks if a file is stored securely
habitipy/util.py
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): """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
[ "checks", "if", "a", "file", "is", "stored", "securely" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L144-L151
[ "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...
555b8b20faf6d553353092614a8a0d612f0adbde
train
get_translation_for
find and return gettext translation for package
habitipy/util.py
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: """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...
[ "find", "and", "return", "gettext", "translation", "for", "package" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L154-L163
[ "def", "get_translation_for", "(", "package_name", ":", "str", ")", "->", "gettext", ".", "NullTranslations", ":", "localedir", "=", "None", "for", "localedir", "in", "pkg_resources", ".", "resource_filename", "(", "package_name", ",", "'i18n'", ")", ",", "None"...
555b8b20faf6d553353092614a8a0d612f0adbde
train
get_translation_functions
finds and installs translation functions for package
habitipy/util.py
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',)): """finds and installs translation functions for package""" translation = get_translation_for(package_name) return [getattr(translation, x) for x in names]
[ "finds", "and", "installs", "translation", "functions", "for", "package" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/util.py#L166-L169
[ "def", "get_translation_functions", "(", "package_name", ":", "str", ",", "names", ":", "Tuple", "[", "str", ",", "...", "]", "=", "(", "'gettext'", ",", ")", ")", ":", "translation", "=", "get_translation_for", "(", "package_name", ")", "return", "[", "ge...
555b8b20faf6d553353092614a8a0d612f0adbde
train
escape_keywords
append _ to all python keywords
habitipy/api.py
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): """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
[ "append", "_", "to", "all", "python", "keywords" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L91-L96
[ "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", "(", "'-'", ","...
555b8b20faf6d553353092614a8a0d612f0adbde
train
download_api
download API documentation from _branch_ of Habitica\'s repo on Github
habitipy/api.py
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: """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...
[ "download", "API", "documentation", "from", "_branch_", "of", "Habitica", "\\", "s", "repo", "on", "Github" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L287-L297
[ "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/...
555b8b20faf6d553353092614a8a0d612f0adbde
train
save_apidoc
save `text` to apidoc cache
habitipy/api.py
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: """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)
[ "save", "text", "to", "apidoc", "cache" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L300-L306
[ "def", "save_apidoc", "(", "text", ":", "str", ")", "->", "None", ":", "apidoc_local", "=", "local", ".", "path", "(", "APIDOC_LOCAL_FILE", ")", "if", "not", "apidoc_local", ".", "dirname", ".", "exists", "(", ")", ":", "apidoc_local", ".", "dirname", "....
555b8b20faf6d553353092614a8a0d612f0adbde
train
parse_apidoc
read file and parse apiDoc lines
habitipy/api.py
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']: """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>.*)...
[ "read", "file", "and", "parse", "apiDoc", "lines" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L309-L353
[ "def", "parse_apidoc", "(", "file_or_branch", ",", "from_github", "=", "False", ",", "save_github_version", "=", "True", ")", "->", "List", "[", "'ApiEndpoint'", "]", ":", "apis", "=", "[", "]", "# type: List[ApiEndpoint]", "regex", "=", "r'(?P<group>\\([^)]*\\)){...
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiNode.into
Get another leaf node with name `val` if possible
habitipy/api.py
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']: """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))
[ "Get", "another", "leaf", "node", "with", "name", "val", "if", "possible" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L52-L58
[ "def", "into", "(", "self", ",", "val", ":", "str", ")", "->", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ":", "if", "val", "in", "self", ".", "paths", ":", "return", "self", ".", "paths", "[", "val", "]", "if", "self", ".", "param", "...
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiNode.can_into
Determine if there is a leaf node with name `val`
habitipy/api.py
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: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
[ "Determine", "if", "there", "is", "a", "leaf", "node", "with", "name", "val" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L60-L62
[ "def", "can_into", "(", "self", ",", "val", ":", "str", ")", "->", "bool", ":", "return", "val", "in", "self", ".", "paths", "or", "(", "self", ".", "param", "and", "self", ".", "param_name", "==", "val", ")" ]
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiNode.place
place a leaf node
habitipy/api.py
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']): """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...
[ "place", "a", "leaf", "node" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L64-L74
[ "def", "place", "(", "self", ",", "part", ":", "str", ",", "val", ":", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ")", ":", "if", "part", ".", "startswith", "(", "':'", ")", ":", "if", "self", ".", "param", "and", "self", ".", "param", ...
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiNode.keys
return all possible paths one can take from this ApiNode
habitipy/api.py
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]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
[ "return", "all", "possible", "paths", "one", "can", "take", "from", "this", "ApiNode" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L76-L80
[ "def", "keys", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "if", "self", ".", "param", ":", "yield", "self", ".", "param_name", "yield", "from", "self", ".", "paths", ".", "keys", "(", ")" ]
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiEndpoint.add_param
parse and append a param
habitipy/api.py
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=''): """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
[ "parse", "and", "append", "a", "param" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L368-L373
[ "def", "add_param", "(", "self", ",", "group", "=", "None", ",", "type_", "=", "''", ",", "field", "=", "''", ",", "description", "=", "''", ")", ":", "group", "=", "group", "or", "'(Parameter)'", "group", "=", "group", ".", "lower", "(", ")", "[",...
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiEndpoint.add_success
parse and append a success data param
habitipy/api.py
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=''): """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...
[ "parse", "and", "append", "a", "success", "data", "param" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L375-L384
[ "def", "add_success", "(", "self", ",", "group", "=", "None", ",", "type_", "=", "''", ",", "field", "=", "''", ",", "description", "=", "''", ")", ":", "group", "=", "group", "or", "'(200)'", "group", "=", "int", "(", "group", ".", "lower", "(", ...
555b8b20faf6d553353092614a8a0d612f0adbde
train
ApiEndpoint.render_docstring
make a nice docstring for ipython
habitipy/api.py
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): """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...
[ "make", "a", "nice", "docstring", "for", "ipython" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L389-L397
[ "def", "render_docstring", "(", "self", ")", ":", "res", "=", "'{{{self.method}}} {self.uri} {self.title}\\n'", ".", "format", "(", "self", "=", "self", ")", "if", "self", ".", "params", ":", "for", "group", ",", "params", "in", "self", ".", "params", ".", ...
555b8b20faf6d553353092614a8a0d612f0adbde
train
Param.validate
check if obj has this api param
habitipy/api.py
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): """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')
[ "check", "if", "obj", "has", "this", "api", "param" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L439-L446
[ "def", "validate", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "path", ":", "for", "i", "in", "self", ".", "path", ":", "obj", "=", "obj", "[", "i", "]", "obj", "=", "obj", "[", "self", ".", "field", "]", "raise", "NotImplementedError",...
555b8b20faf6d553353092614a8a0d612f0adbde
train
Param.render_docstring
make a nice docstring for ipython
habitipy/api.py
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): """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...
[ "make", "a", "nice", "docstring", "for", "ipython" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L448-L456
[ "def", "render_docstring", "(", "self", ")", ":", "default", "=", "(", "' = '", "+", "str", "(", "self", ".", "default", ")", ")", "if", "self", ".", "default", "else", "''", "opt", "=", "'optional'", "if", "self", ".", "is_optional", "else", "''", "...
555b8b20faf6d553353092614a8a0d612f0adbde
train
is_uuid
validator for plumbum prompt
habitipy/cli.py
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): """validator for plumbum prompt""" if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex: return u return False
[ "validator", "for", "plumbum", "prompt" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L48-L52
[ "def", "is_uuid", "(", "u", ")", ":", "if", "isinstance", "(", "u", ",", "str", ")", "and", "u", ".", "replace", "(", "'-'", ",", "''", ")", "==", "uuid", ".", "UUID", "(", "u", ")", ".", "hex", ":", "return", "u", "return", "False" ]
555b8b20faf6d553353092614a8a0d612f0adbde
train
load_conf
Get authentication data from the AUTH_CONF file.
habitipy/cli.py
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): """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...
[ "Get", "authentication", "data", "from", "the", "AUTH_CONF", "file", "." ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L55-L97
[ "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...
555b8b20faf6d553353092614a8a0d612f0adbde
train
get_content
get content from server or cache
habitipy/cli.py
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): """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: ...
[ "get", "content", "from", "server", "or", "cache" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L126-L164
[ "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...
555b8b20faf6d553353092614a8a0d612f0adbde
train
get_additional_rewards
returns list of non-user rewards (potion, armoire, gear)
habitipy/cli.py
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): """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
[ "returns", "list", "of", "non", "-", "user", "rewards", "(", "potion", "armoire", "gear", ")" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L365-L372
[ "def", "get_additional_rewards", "(", "api", ")", ":", "c", "=", "get_content", "(", "api", ")", "tasks", "=", "[", "c", "[", "i", "]", "for", "i", "in", "[", "'potion'", ",", "'armoire'", "]", "]", "tasks", ".", "extend", "(", "api", ".", "user", ...
555b8b20faf6d553353092614a8a0d612f0adbde
train
ScoreInfo.color
task value/score color
habitipy/cli.py
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
[ "task", "value", "/", "score", "color" ]
ASMfreaK/habitipy
python
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L289-L292
[ "def", "color", "(", "cls", ",", "value", ")", ":", "index", "=", "bisect", "(", "cls", ".", "breakpoints", ",", "value", ")", "return", "colors", ".", "fg", "(", "cls", ".", "colors_", "[", "index", "]", ")" ]
555b8b20faf6d553353092614a8a0d612f0adbde
train
augment_init_method
Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping.
tohu/v6/custom_generator/custom_generator.py
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): """ 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 ...
[ "Replace", "the", "existing", "cls", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "also", "initialises", "the", "field", "generators", "and", "similar", "bookkeeping", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/custom_generator.py#L9-L39
[ "def", "augment_init_method", "(", "cls", ")", ":", "orig_init", "=", "cls", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "CustomGenerator", ",", "self", ")", ".", "__init__", "(", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
find_field_generators
Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces.
tohu/v2/custom_generator.py
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): """ 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...
[ "Return", "dictionary", "with", "the", "names", "and", "instances", "of", "all", "tohu", ".", "BaseGenerator", "occurring", "in", "the", "given", "object", "s", "class", "&", "instance", "namespaces", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L20-L36
[ "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", "=", "{", "}", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
set_item_class_name
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
tohu/v2/custom_generator.py
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): """ 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...
[ "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", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L39-L59
[ "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",...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
make_item_class_for_custom_generator
obj: The custom generator instance for which to create an item class
tohu/v2/custom_generator.py
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): """ 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)
[ "obj", ":", "The", "custom", "generator", "instance", "for", "which", "to", "create", "an", "item", "class" ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L108-L115
[ "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", ")" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_init_method
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..
tohu/v2/custom_generator.py
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): """ 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`. ...
[ "Replace", "the", "existing", "obj", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "calls", "the", "original", "one", "and", "in", "addition", "performs", "the", "following", "actions", ":" ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L118-L192
[ "def", "add_new_init_method", "(", "obj", ")", ":", "orig_init", "=", "obj", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "f\"Initialising new {self}\"", ")", "# Call ori...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_reset_method
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`.
tohu/v2/custom_generator.py
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): """ 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...
[ "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", ...
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L195-L225
[ "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()...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_next_method
TODO
tohu/v2/custom_generator.py
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): """ 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
[ "TODO" ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L228-L237
[ "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...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_spawn_method
TODO
tohu/v2/custom_generator.py
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): """ 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...
[ "TODO" ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L240-L252
[ "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...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
check_that_operator_can_be_applied_to_produces_items
Helper function to check that the operator `op` can be applied to items produced by g1 and g2.
tohu/v6/set_special_methods.py
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2): """ Helper function to check that the operator `op` can be applied to items produced by g1 and g2. """ g1_tmp_copy = g1.spawn() g2_tmp_copy = g2.spawn() sample_item_1 = next(g1_tmp_copy) sample_item_2 = next(g2_tmp_copy) ...
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2): """ Helper function to check that the operator `op` can be applied to items produced by g1 and g2. """ g1_tmp_copy = g1.spawn() g2_tmp_copy = g2.spawn() sample_item_1 = next(g1_tmp_copy) sample_item_2 = next(g2_tmp_copy) ...
[ "Helper", "function", "to", "check", "that", "the", "operator", "op", "can", "be", "applied", "to", "items", "produced", "by", "g1", "and", "g2", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/set_special_methods.py#L16-L28
[ "def", "check_that_operator_can_be_applied_to_produces_items", "(", "op", ",", "g1", ",", "g2", ")", ":", "g1_tmp_copy", "=", "g1", ".", "spawn", "(", ")", "g2_tmp_copy", "=", "g2", ".", "spawn", "(", ")", "sample_item_1", "=", "next", "(", "g1_tmp_copy", ")...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_init_method
Replace the existing cls.__init__() method with a new one which also initialises the _dependent_generators attribute to an empty list.
tohu/v2/base.py
def add_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _dependent_generators attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): self._dependent_generators = [] orig_init(s...
def add_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _dependent_generators attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): self._dependent_generators = [] orig_init(s...
[ "Replace", "the", "existing", "cls", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "also", "initialises", "the", "_dependent_generators", "attribute", "to", "an", "empty", "list", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L113-L125
[ "def", "add_new_init_method", "(", "cls", ")", ":", "orig_init", "=", "cls", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_dependent_generators", "=", "[", "]", "orig_init", "(", "s...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_repr_method
Add default __repr__ method in case no user-defined one is present.
tohu/v2/base.py
def add_new_repr_method(cls): """ Add default __repr__ method in case no user-defined one is present. """ if isinstance(cls.__repr__, WrapperDescriptorType): cls.__repr__ = lambda self: f"<{self.__class__.__name__}, id={hex(id(self))}>" else: # Keep the user-defined __repr__ method ...
def add_new_repr_method(cls): """ Add default __repr__ method in case no user-defined one is present. """ if isinstance(cls.__repr__, WrapperDescriptorType): cls.__repr__ = lambda self: f"<{self.__class__.__name__}, id={hex(id(self))}>" else: # Keep the user-defined __repr__ method ...
[ "Add", "default", "__repr__", "method", "in", "case", "no", "user", "-", "defined", "one", "is", "present", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L128-L137
[ "def", "add_new_repr_method", "(", "cls", ")", ":", "if", "isinstance", "(", "cls", ".", "__repr__", ",", "WrapperDescriptorType", ")", ":", "cls", ".", "__repr__", "=", "lambda", "self", ":", "f\"<{self.__class__.__name__}, id={hex(id(self))}>\"", "else", ":", "#...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
add_new_reset_method
Replace existing cls.reset() method with a new one which also calls reset() on any clones.
tohu/v2/base.py
def add_new_reset_method(cls): """ Replace existing cls.reset() method with a new one which also calls reset() on any clones. """ orig_reset = cls.reset def new_reset(self, seed=None): logger.debug(f"Calling reset() on {self} (seed={seed})") orig_reset(self, seed) for c ...
def add_new_reset_method(cls): """ Replace existing cls.reset() method with a new one which also calls reset() on any clones. """ orig_reset = cls.reset def new_reset(self, seed=None): logger.debug(f"Calling reset() on {self} (seed={seed})") orig_reset(self, seed) for c ...
[ "Replace", "existing", "cls", ".", "reset", "()", "method", "with", "a", "new", "one", "which", "also", "calls", "reset", "()", "on", "any", "clones", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L141-L155
[ "def", "add_new_reset_method", "(", "cls", ")", ":", "orig_reset", "=", "cls", ".", "reset", "def", "new_reset", "(", "self", ",", "seed", "=", "None", ")", ":", "logger", ".", "debug", "(", "f\"Calling reset() on {self} (seed={seed})\"", ")", "orig_reset", "(...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
UltraBaseGenerator.generate
Return sequence of `N` elements. If `seed` is not None, the generator is reset using this seed before generating the elements.
tohu/v2/base.py
def generate(self, N, *, seed=None, progressbar=False): """ Return sequence of `N` elements. If `seed` is not None, the generator is reset using this seed before generating the elements. """ if seed is not None: self.reset(seed) items = islice(self, N...
def generate(self, N, *, seed=None, progressbar=False): """ Return sequence of `N` elements. If `seed` is not None, the generator is reset using this seed before generating the elements. """ if seed is not None: self.reset(seed) items = islice(self, N...
[ "Return", "sequence", "of", "N", "elements", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L34-L50
[ "def", "generate", "(", "self", ",", "N", ",", "*", ",", "seed", "=", "None", ",", "progressbar", "=", "False", ")", ":", "if", "seed", "is", "not", "None", ":", "self", ".", "reset", "(", "seed", ")", "items", "=", "islice", "(", "self", ",", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
TohuUltraBaseGenerator.tohu_id
Return (truncated) md5 hash representing this generator. We truncate the hash simply for readability, as this is purely intended for debugging purposes and the risk of any collisions will be negligible.
tohu/v2/base_NEW.py
def tohu_id(self): """ Return (truncated) md5 hash representing this generator. We truncate the hash simply for readability, as this is purely intended for debugging purposes and the risk of any collisions will be negligible. """ myhash = hashlib.md5(str(id(self))...
def tohu_id(self): """ Return (truncated) md5 hash representing this generator. We truncate the hash simply for readability, as this is purely intended for debugging purposes and the risk of any collisions will be negligible. """ myhash = hashlib.md5(str(id(self))...
[ "Return", "(", "truncated", ")", "md5", "hash", "representing", "this", "generator", ".", "We", "truncate", "the", "hash", "simply", "for", "readability", "as", "this", "is", "purely", "intended", "for", "debugging", "purposes", "and", "the", "risk", "of", "...
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base_NEW.py#L122-L130
[ "def", "tohu_id", "(", "self", ")", ":", "myhash", "=", "hashlib", ".", "md5", "(", "str", "(", "id", "(", "self", ")", ")", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "return", "myhash", "[", ":", "12", "]" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
CustomGenerator._set_item_class
cls: The custom generator class for which to create an item-class
tohu/v4/custom_generator.py
def _set_item_class(self): """ cls: The custom generator class for which to create an item-class """ clsname = self.__tohu_items_name__ self.item_cls = make_item_class(clsname, self.field_names)
def _set_item_class(self): """ cls: The custom generator class for which to create an item-class """ clsname = self.__tohu_items_name__ self.item_cls = make_item_class(clsname, self.field_names)
[ "cls", ":", "The", "custom", "generator", "class", "for", "which", "to", "create", "an", "item", "-", "class" ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/custom_generator.py#L130-L136
[ "def", "_set_item_class", "(", "self", ")", ":", "clsname", "=", "self", ".", "__tohu_items_name__", "self", ".", "item_cls", "=", "make_item_class", "(", "clsname", ",", "self", ".", "field_names", ")" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
CustomGenerator._find_field_generator_templates
Return a dictionary of the form {name: field_generator} containing all tohu generators defined in the class and instance namespace of this custom generator.
tohu/v4/custom_generator.py
def _find_field_generator_templates(self): """ Return a dictionary of the form {name: field_generator} containing all tohu generators defined in the class and instance namespace of this custom generator. """ field_gen_templates = {} # Extract field generators fro...
def _find_field_generator_templates(self): """ Return a dictionary of the form {name: field_generator} containing all tohu generators defined in the class and instance namespace of this custom generator. """ field_gen_templates = {} # Extract field generators fro...
[ "Return", "a", "dictionary", "of", "the", "form", "{", "name", ":", "field_generator", "}", "containing", "all", "tohu", "generators", "defined", "in", "the", "class", "and", "instance", "namespace", "of", "this", "custom", "generator", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/custom_generator.py#L142-L160
[ "def", "_find_field_generator_templates", "(", "self", ")", ":", "field_gen_templates", "=", "{", "}", "# Extract field generators from class dict", "for", "name", ",", "g", "in", "self", ".", "__class__", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isi...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
_generate_csv_header_line
Helper function to generate a CSV header line depending on the combination of arguments provided.
tohu/v4/item_list.py
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'): """ Helper function to generate a CSV header line depending on the combination of arguments provided. """ if isinstance(header, str): # user-provided header line header_line = header + newl...
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'): """ Helper function to generate a CSV header line depending on the combination of arguments provided. """ if isinstance(header, str): # user-provided header line header_line = header + newl...
[ "Helper", "function", "to", "generate", "a", "CSV", "header", "line", "depending", "on", "the", "combination", "of", "arguments", "provided", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L14-L29
[ "def", "_generate_csv_header_line", "(", "*", ",", "header_names", ",", "header_prefix", "=", "''", ",", "header", "=", "True", ",", "sep", "=", "','", ",", "newline", "=", "'\\n'", ")", ":", "if", "isinstance", "(", "header", ",", "str", ")", ":", "# ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
_extract_schema_if_given
Return a pair (schema, table) derived from the given `table_name` (anything before the first '.' if the name contains one; otherwise the return value of `schema` is None). Examples: >>> _extract_schema_if_given('some_schema.my_table') ('some_schema', 'my_table') >>> _extract_schem...
tohu/v4/item_list.py
def _extract_schema_if_given(table_name): """ Return a pair (schema, table) derived from the given `table_name` (anything before the first '.' if the name contains one; otherwise the return value of `schema` is None). Examples: >>> _extract_schema_if_given('some_schema.my_table') (...
def _extract_schema_if_given(table_name): """ Return a pair (schema, table) derived from the given `table_name` (anything before the first '.' if the name contains one; otherwise the return value of `schema` is None). Examples: >>> _extract_schema_if_given('some_schema.my_table') (...
[ "Return", "a", "pair", "(", "schema", "table", ")", "derived", "from", "the", "given", "table_name", "(", "anything", "before", "the", "first", ".", "if", "the", "name", "contains", "one", ";", "otherwise", "the", "return", "value", "of", "schema", "is", ...
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L32-L49
[ "def", "_extract_schema_if_given", "(", "table_name", ")", ":", "pattern", "=", "'^(([^.]+)\\.)?(.+)$'", "m", "=", "re", ".", "match", "(", "pattern", ",", "table_name", ")", "schema", ",", "table_name", "=", "m", ".", "group", "(", "2", ")", ",", "m", "...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
ItemList.to_df
Export items as rows in a pandas dataframe table. Parameters ---------- fields: list or dict List of field names to export, or dictionary mapping output column names to attribute names of the generators. Examples: fields=['field_name_1', 'fie...
tohu/v4/item_list.py
def to_df(self, fields=None): """ Export items as rows in a pandas dataframe table. Parameters ---------- fields: list or dict List of field names to export, or dictionary mapping output column names to attribute names of the generators. Exa...
def to_df(self, fields=None): """ Export items as rows in a pandas dataframe table. Parameters ---------- fields: list or dict List of field names to export, or dictionary mapping output column names to attribute names of the generators. Exa...
[ "Export", "items", "as", "rows", "in", "a", "pandas", "dataframe", "table", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L101-L130
[ "def", "to_df", "(", "self", ",", "fields", "=", "None", ")", ":", "if", "isinstance", "(", "fields", ",", "(", "list", ",", "tuple", ")", ")", ":", "fields", "=", "{", "name", ":", "name", "for", "name", "in", "fields", "}", "if", "fields", "is"...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
ItemList.to_csv
Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `append=True` to open the file in append mode instead. If filename is None, the generated CSV output is returned instead of writt...
tohu/v4/item_list.py
def to_csv(self, filename=None, *, fields=None, append=False, header=True, header_prefix='', sep=',', newline='\n'): """ Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `app...
def to_csv(self, filename=None, *, fields=None, append=False, header=True, header_prefix='', sep=',', newline='\n'): """ Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `app...
[ "Parameters", "----------", "filename", ":", "str", "or", "None", "The", "file", "to", "which", "output", "will", "be", "written", ".", "By", "default", "any", "existing", "content", "is", "overwritten", ".", "Use", "append", "=", "True", "to", "open", "th...
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L132-L206
[ "def", "to_csv", "(", "self", ",", "filename", "=", "None", ",", "*", ",", "fields", "=", "None", ",", "append", "=", "False", ",", "header", "=", "True", ",", "header_prefix", "=", "''", ",", "sep", "=", "','", ",", "newline", "=", "'\\n'", ")", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
SpawnMapping.spawn_generator
Return a fresh spawn of g unless g is already contained in this SpawnMapping, in which case return the previously spawned generator.
tohu/v5/base.py
def spawn_generator(self, g): """ Return a fresh spawn of g unless g is already contained in this SpawnMapping, in which case return the previously spawned generator. """ try: return self.mapping[g] except KeyError: return g._spawn(self)
def spawn_generator(self, g): """ Return a fresh spawn of g unless g is already contained in this SpawnMapping, in which case return the previously spawned generator. """ try: return self.mapping[g] except KeyError: return g._spawn(self)
[ "Return", "a", "fresh", "spawn", "of", "g", "unless", "g", "is", "already", "contained", "in", "this", "SpawnMapping", "in", "which", "case", "return", "the", "previously", "spawned", "generator", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L30-L39
[ "def", "spawn_generator", "(", "self", ",", "g", ")", ":", "try", ":", "return", "self", ".", "mapping", "[", "g", "]", "except", "KeyError", ":", "return", "g", ".", "_spawn", "(", "self", ")" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
TohuBaseGenerator.spawn
Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) but is otherwise independent, i.e. there is no link between the two generators (as opposed to a cloned generator, which is automatically reset whenever the original gene...
tohu/v5/base.py
def spawn(self, spawn_mapping=None): """ Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) but is otherwise independent, i.e. there is no link between the two generators (as opposed to a cloned generator, which ...
def spawn(self, spawn_mapping=None): """ Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) but is otherwise independent, i.e. there is no link between the two generators (as opposed to a cloned generator, which ...
[ "Return", "an", "exact", "copy", "of", "this", "generator", "which", "behaves", "the", "same", "way", "(", "i", ".", "e", ".", "produces", "the", "same", "elements", "in", "the", "same", "order", ")", "but", "is", "otherwise", "independent", "i", ".", ...
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L171-L189
[ "def", "spawn", "(", "self", ",", "spawn_mapping", "=", "None", ")", ":", "spawn_mapping", "=", "spawn_mapping", "or", "SpawnMapping", "(", ")", "if", "self", ".", "parent", "is", "not", "None", ":", "if", "self", ".", "parent", "in", "spawn_mapping", ":...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
TohuBaseGenerator.clone
Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) and which is automatically reset whenever the original generator is reset.
tohu/v5/base.py
def clone(self, spawn_mapping=None): """ Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) and which is automatically reset whenever the original generator is reset. """ c = self.spawn(spawn_mapping) ...
def clone(self, spawn_mapping=None): """ Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) and which is automatically reset whenever the original generator is reset. """ c = self.spawn(spawn_mapping) ...
[ "Return", "an", "exact", "copy", "of", "this", "generator", "which", "behaves", "the", "same", "way", "(", "i", ".", "e", ".", "produces", "the", "same", "elements", "in", "the", "same", "order", ")", "and", "which", "is", "automatically", "reset", "when...
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L195-L204
[ "def", "clone", "(", "self", ",", "spawn_mapping", "=", "None", ")", ":", "c", "=", "self", ".", "spawn", "(", "spawn_mapping", ")", "self", ".", "register_clone", "(", "c", ")", "c", ".", "register_parent", "(", "self", ")", "return", "c" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
FuncArgGens.all_generators
Convenience property to iterate over all generators in arg_gens and kwarg_gens.
tohu/v4/derived_generators.py
def all_generators(self): """ Convenience property to iterate over all generators in arg_gens and kwarg_gens. """ for arg_gen in self.arg_gens: yield arg_gen for kwarg_gen in self.kwarg_gens.values(): yield kwarg_gen
def all_generators(self): """ Convenience property to iterate over all generators in arg_gens and kwarg_gens. """ for arg_gen in self.arg_gens: yield arg_gen for kwarg_gen in self.kwarg_gens.values(): yield kwarg_gen
[ "Convenience", "property", "to", "iterate", "over", "all", "generators", "in", "arg_gens", "and", "kwarg_gens", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/derived_generators.py#L40-L48
[ "def", "all_generators", "(", "self", ")", ":", "for", "arg_gen", "in", "self", ".", "arg_gens", ":", "yield", "arg_gen", "for", "kwarg_gen", "in", "self", ".", "kwarg_gens", ".", "values", "(", ")", ":", "yield", "kwarg_gen" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
Split
Split a tuple generator into individual generators. Parameters ---------- g: tohu generator The generator to be split. The items produced by `g` must be tuples. maxbuffer: integer Maximum number of items produced by `g` that will be buffered.
tohu/v2/generators.py
def Split(g, *, maxbuffer=10, tuple_len=None): """ Split a tuple generator into individual generators. Parameters ---------- g: tohu generator The generator to be split. The items produced by `g` must be tuples. maxbuffer: integer Maximum number of items produced by `g` that wil...
def Split(g, *, maxbuffer=10, tuple_len=None): """ Split a tuple generator into individual generators. Parameters ---------- g: tohu generator The generator to be split. The items produced by `g` must be tuples. maxbuffer: integer Maximum number of items produced by `g` that wil...
[ "Split", "a", "tuple", "generator", "into", "individual", "generators", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/generators.py#L956-L975
[ "def", "Split", "(", "g", ",", "*", ",", "maxbuffer", "=", "10", ",", "tuple_len", "=", "None", ")", ":", "if", "tuple_len", "is", "None", ":", "try", ":", "tuple_len", "=", "g", ".", "tuple_len", "except", "AttributeError", ":", "raise", "ValueError",...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
TupleGenerator.tuple_len
Length of tuples produced by this generator.
tohu/v2/generators.py
def tuple_len(self): """ Length of tuples produced by this generator. """ try: return self._tuple_len except AttributeError: raise NotImplementedError("Class {} does not implement attribute 'tuple_len'.".format(self.__class__.__name__))
def tuple_len(self): """ Length of tuples produced by this generator. """ try: return self._tuple_len except AttributeError: raise NotImplementedError("Class {} does not implement attribute 'tuple_len'.".format(self.__class__.__name__))
[ "Length", "of", "tuples", "produced", "by", "this", "generator", "." ]
maxalbert/tohu
python
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/generators.py#L48-L55
[ "def", "tuple_len", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_tuple_len", "except", "AttributeError", ":", "raise", "NotImplementedError", "(", "\"Class {} does not implement attribute 'tuple_len'.\"", ".", "format", "(", "self", ".", "__class__", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
train
show_faults
Return all valid/active faults ordered by ID to allow the user to pick and choose. :return: List of Tuples where the Tuple elements are: (fault id, fault template)
surrealism.py
def show_faults(): """ Return all valid/active faults ordered by ID to allow the user to pick and choose. :return: List of Tuples where the Tuple elements are: (fault id, fault template) """ cursor = CONN.cursor() query = "select fau_id, fault from surfaults where fau_is_valid = 'y' order by...
def show_faults(): """ Return all valid/active faults ordered by ID to allow the user to pick and choose. :return: List of Tuples where the Tuple elements are: (fault id, fault template) """ cursor = CONN.cursor() query = "select fau_id, fault from surfaults where fau_is_valid = 'y' order by...
[ "Return", "all", "valid", "/", "active", "faults", "ordered", "by", "ID", "to", "allow", "the", "user", "to", "pick", "and", "choose", "." ]
Morrolan/surrealism
python
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L71-L82
[ "def", "show_faults", "(", ")", ":", "cursor", "=", "CONN", ".", "cursor", "(", ")", "query", "=", "\"select fau_id, fault from surfaults where fau_is_valid = 'y' order by fau_id asc\"", "cursor", ".", "execute", "(", "query", ")", "result", "=", "cursor", ".", "fet...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
train
show_sentences
Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value.
surrealism.py
def show_sentences(): """ Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value. """ cursor = CONN.cursor() query = "select sen_id, sentence from sursentences where sen_...
def show_sentences(): """ Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value. """ cursor = CONN.cursor() query = "select sen_id, sentence from sursentences where sen_...
[ "Return", "all", "valid", "/", "active", "sentences", "ordered", "by", "ID", "to", "allow", "the", "user", "to", "pick", "and", "choose", "." ]
Morrolan/surrealism
python
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L94-L111
[ "def", "show_sentences", "(", ")", ":", "cursor", "=", "CONN", ".", "cursor", "(", ")", "query", "=", "\"select sen_id, sentence from sursentences where sen_is_valid = 'y' order by sen_id asc\"", "cursor", ".", "execute", "(", "query", ")", "result", "=", "cursor", "....
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
train
get_fault
Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit with different keywords.
surrealism.py
def get_fault(fault_id=None): """Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit...
def get_fault(fault_id=None): """Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit...
[ "Retrieve", "a", "randomly", "-", "generated", "error", "message", "as", "a", "unicode", "string", ".", ":", "param", "fault_id", ":", "Allows", "you", "to", "optionally", "specify", "an", "integer", "representing", "the", "fault_id", "from", "the", "database"...
Morrolan/surrealism
python
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L185-L229
[ "def", "get_fault", "(", "fault_id", "=", "None", ")", ":", "counts", "=", "__get_table_limits", "(", ")", "result", "=", "None", "id_", "=", "0", "try", ":", "if", "isinstance", "(", "fault_id", ",", "int", ")", ":", "id_", "=", "fault_id", "elif", ...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
train
get_sentence
Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each time, albeit with different keywords.
surrealism.py
def get_sentence(sentence_id=None): """Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each tim...
def get_sentence(sentence_id=None): """Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each tim...
[ "Retrieve", "a", "randomly", "-", "generated", "sentence", "as", "a", "unicode", "string", ".", ":", "param", "sentence_id", ":", "Allows", "you", "to", "optionally", "specify", "an", "integer", "representing", "the", "sentence_id", "from", "the", "database", ...
Morrolan/surrealism
python
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L237-L282
[ "def", "get_sentence", "(", "sentence_id", "=", "None", ")", ":", "counts", "=", "__get_table_limits", "(", ")", "result", "=", "None", "id_", "=", "0", "try", ":", "if", "isinstance", "(", "sentence_id", ",", "int", ")", ":", "id_", "=", "sentence_id", ...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
train
__get_sentence
Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id:
surrealism.py
def __get_sentence(counts, sentence_id=None): """Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id: """ # First of all we need a cursor and a query to retrieve our ID's cursor = CONN.cursor() check_query = "select sen_id from su...
def __get_sentence(counts, sentence_id=None): """Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id: """ # First of all we need a cursor and a query to retrieve our ID's cursor = CONN.cursor() check_query = "select sen_id from su...
[ "Let", "s", "fetch", "a", "random", "sentence", "that", "we", "then", "need", "to", "substitute", "bits", "of", "..." ]
Morrolan/surrealism
python
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L327-L364
[ "def", "__get_sentence", "(", "counts", ",", "sentence_id", "=", "None", ")", ":", "# First of all we need a cursor and a query to retrieve our ID's", "cursor", "=", "CONN", ".", "cursor", "(", ")", "check_query", "=", "\"select sen_id from sursentences\"", "# Now we fetch ...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
train
__get_verb
Let's fetch a VERB :param counts:
surrealism.py
def __get_verb(counts): """Let's fetch a VERB :param counts: """ cursor = CONN.cursor() check_query = "select verb_id from surverbs" cursor.execute(check_query) check_result = cursor.fetchall() id_list = [] for row in check_result: id_list.append(row[0]) rand = random...
def __get_verb(counts): """Let's fetch a VERB :param counts: """ cursor = CONN.cursor() check_query = "select verb_id from surverbs" cursor.execute(check_query) check_result = cursor.fetchall() id_list = [] for row in check_result: id_list.append(row[0]) rand = random...
[ "Let", "s", "fetch", "a", "VERB", ":", "param", "counts", ":" ]
Morrolan/surrealism
python
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L367-L392
[ "def", "__get_verb", "(", "counts", ")", ":", "cursor", "=", "CONN", ".", "cursor", "(", ")", "check_query", "=", "\"select verb_id from surverbs\"", "cursor", ".", "execute", "(", "check_query", ")", "check_result", "=", "cursor", ".", "fetchall", "(", ")", ...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab