repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
ASMfreaK/habitipy | habitipy/api.py | ApiNode.into | def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']:
"""Get another leaf node with name `val` if possible"""
if val in self.paths:
return self.paths[val]
if self.param:
return self.param
raise IndexError(_("Value {} is missing from api").format(val)) | python | def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']:
"""Get another leaf node with name `val` if possible"""
if val in self.paths:
return self.paths[val]
if self.param:
return self.param
raise IndexError(_("Value {} is missing from api").format(val)) | [
"def",
"into",
"(",
"self",
",",
"val",
":",
"str",
")",
"->",
"Union",
"[",
"'ApiNode'",
",",
"'ApiEndpoint'",
"]",
":",
"if",
"val",
"in",
"self",
".",
"paths",
":",
"return",
"self",
".",
"paths",
"[",
"val",
"]",
"if",
"self",
".",
"param",
"... | Get another leaf node with name `val` if possible | [
"Get",
"another",
"leaf",
"node",
"with",
"name",
"val",
"if",
"possible"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L52-L58 |
ASMfreaK/habitipy | habitipy/api.py | ApiNode.can_into | def can_into(self, val: str) -> bool:
"""Determine if there is a leaf node with name `val`"""
return val in self.paths or (self.param and self.param_name == val) | python | def can_into(self, val: str) -> bool:
"""Determine if there is a leaf node with name `val`"""
return val in self.paths or (self.param and self.param_name == val) | [
"def",
"can_into",
"(",
"self",
",",
"val",
":",
"str",
")",
"->",
"bool",
":",
"return",
"val",
"in",
"self",
".",
"paths",
"or",
"(",
"self",
".",
"param",
"and",
"self",
".",
"param_name",
"==",
"val",
")"
] | Determine if there is a leaf node with name `val` | [
"Determine",
"if",
"there",
"is",
"a",
"leaf",
"node",
"with",
"name",
"val"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L60-L62 |
ASMfreaK/habitipy | habitipy/api.py | ApiNode.place | def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']):
"""place a leaf node"""
if part.startswith(':'):
if self.param and self.param != part:
err = """Cannot place param '{}' as '{self.param_name}' exist on node already!"""
raise ParamAlreadyExist(e... | python | def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']):
"""place a leaf node"""
if part.startswith(':'):
if self.param and self.param != part:
err = """Cannot place param '{}' as '{self.param_name}' exist on node already!"""
raise ParamAlreadyExist(e... | [
"def",
"place",
"(",
"self",
",",
"part",
":",
"str",
",",
"val",
":",
"Union",
"[",
"'ApiNode'",
",",
"'ApiEndpoint'",
"]",
")",
":",
"if",
"part",
".",
"startswith",
"(",
"':'",
")",
":",
"if",
"self",
".",
"param",
"and",
"self",
".",
"param",
... | place a leaf node | [
"place",
"a",
"leaf",
"node"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L64-L74 |
ASMfreaK/habitipy | habitipy/api.py | ApiNode.keys | def keys(self) -> Iterator[str]:
"""return all possible paths one can take from this ApiNode"""
if self.param:
yield self.param_name
yield from self.paths.keys() | python | def keys(self) -> Iterator[str]:
"""return all possible paths one can take from this ApiNode"""
if self.param:
yield self.param_name
yield from self.paths.keys() | [
"def",
"keys",
"(",
"self",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"if",
"self",
".",
"param",
":",
"yield",
"self",
".",
"param_name",
"yield",
"from",
"self",
".",
"paths",
".",
"keys",
"(",
")"
] | return all possible paths one can take from this ApiNode | [
"return",
"all",
"possible",
"paths",
"one",
"can",
"take",
"from",
"this",
"ApiNode"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L76-L80 |
ASMfreaK/habitipy | habitipy/api.py | ApiEndpoint.add_param | def add_param(self, group=None, type_='', field='', description=''):
"""parse and append a param"""
group = group or '(Parameter)'
group = group.lower()[1:-1]
p = Param(type_, field, description)
self.params[group][p.field] = p | python | def add_param(self, group=None, type_='', field='', description=''):
"""parse and append a param"""
group = group or '(Parameter)'
group = group.lower()[1:-1]
p = Param(type_, field, description)
self.params[group][p.field] = p | [
"def",
"add_param",
"(",
"self",
",",
"group",
"=",
"None",
",",
"type_",
"=",
"''",
",",
"field",
"=",
"''",
",",
"description",
"=",
"''",
")",
":",
"group",
"=",
"group",
"or",
"'(Parameter)'",
"group",
"=",
"group",
".",
"lower",
"(",
")",
"[",... | parse and append a param | [
"parse",
"and",
"append",
"a",
"param"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L368-L373 |
ASMfreaK/habitipy | habitipy/api.py | ApiEndpoint.add_success | def add_success(self, group=None, type_='', field='', description=''):
"""parse and append a success data param"""
group = group or '(200)'
group = int(group.lower()[1:-1])
self.retcode = self.retcode or group
if group != self.retcode:
raise ValueError('Two or more re... | python | def add_success(self, group=None, type_='', field='', description=''):
"""parse and append a success data param"""
group = group or '(200)'
group = int(group.lower()[1:-1])
self.retcode = self.retcode or group
if group != self.retcode:
raise ValueError('Two or more re... | [
"def",
"add_success",
"(",
"self",
",",
"group",
"=",
"None",
",",
"type_",
"=",
"''",
",",
"field",
"=",
"''",
",",
"description",
"=",
"''",
")",
":",
"group",
"=",
"group",
"or",
"'(200)'",
"group",
"=",
"int",
"(",
"group",
".",
"lower",
"(",
... | parse and append a success data param | [
"parse",
"and",
"append",
"a",
"success",
"data",
"param"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L375-L384 |
ASMfreaK/habitipy | habitipy/api.py | ApiEndpoint.render_docstring | def render_docstring(self):
"""make a nice docstring for ipython"""
res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self)
if self.params:
for group, params in self.params.items():
res += '\n' + group + ' params:\n'
for param in params.v... | python | def render_docstring(self):
"""make a nice docstring for ipython"""
res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self)
if self.params:
for group, params in self.params.items():
res += '\n' + group + ' params:\n'
for param in params.v... | [
"def",
"render_docstring",
"(",
"self",
")",
":",
"res",
"=",
"'{{{self.method}}} {self.uri} {self.title}\\n'",
".",
"format",
"(",
"self",
"=",
"self",
")",
"if",
"self",
".",
"params",
":",
"for",
"group",
",",
"params",
"in",
"self",
".",
"params",
".",
... | make a nice docstring for ipython | [
"make",
"a",
"nice",
"docstring",
"for",
"ipython"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L389-L397 |
ASMfreaK/habitipy | habitipy/api.py | Param.validate | def validate(self, obj):
"""check if obj has this api param"""
if self.path:
for i in self.path:
obj = obj[i]
obj = obj[self.field]
raise NotImplementedError('Validation is not implemented yet') | python | def validate(self, obj):
"""check if obj has this api param"""
if self.path:
for i in self.path:
obj = obj[i]
obj = obj[self.field]
raise NotImplementedError('Validation is not implemented yet') | [
"def",
"validate",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"path",
":",
"for",
"i",
"in",
"self",
".",
"path",
":",
"obj",
"=",
"obj",
"[",
"i",
"]",
"obj",
"=",
"obj",
"[",
"self",
".",
"field",
"]",
"raise",
"NotImplementedError",... | check if obj has this api param | [
"check",
"if",
"obj",
"has",
"this",
"api",
"param"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L439-L446 |
ASMfreaK/habitipy | habitipy/api.py | Param.render_docstring | def render_docstring(self):
"""make a nice docstring for ipython"""
default = (' = ' + str(self.default)) if self.default else ''
opt = 'optional' if self.is_optional else ''
can_be = ' '.join(self.possible_values) if self.possible_values else ''
can_be = 'one of [{}]'.format(can... | python | def render_docstring(self):
"""make a nice docstring for ipython"""
default = (' = ' + str(self.default)) if self.default else ''
opt = 'optional' if self.is_optional else ''
can_be = ' '.join(self.possible_values) if self.possible_values else ''
can_be = 'one of [{}]'.format(can... | [
"def",
"render_docstring",
"(",
"self",
")",
":",
"default",
"=",
"(",
"' = '",
"+",
"str",
"(",
"self",
".",
"default",
")",
")",
"if",
"self",
".",
"default",
"else",
"''",
"opt",
"=",
"'optional'",
"if",
"self",
".",
"is_optional",
"else",
"''",
"... | make a nice docstring for ipython | [
"make",
"a",
"nice",
"docstring",
"for",
"ipython"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L448-L456 |
ASMfreaK/habitipy | habitipy/cli.py | is_uuid | def is_uuid(u):
"""validator for plumbum prompt"""
if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex:
return u
return False | python | def is_uuid(u):
"""validator for plumbum prompt"""
if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex:
return u
return False | [
"def",
"is_uuid",
"(",
"u",
")",
":",
"if",
"isinstance",
"(",
"u",
",",
"str",
")",
"and",
"u",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"==",
"uuid",
".",
"UUID",
"(",
"u",
")",
".",
"hex",
":",
"return",
"u",
"return",
"False"
] | validator for plumbum prompt | [
"validator",
"for",
"plumbum",
"prompt"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L48-L52 |
ASMfreaK/habitipy | habitipy/cli.py | load_conf | def load_conf(configfile, config=None):
"""Get authentication data from the AUTH_CONF file."""
default_login = 'your-login-for-api-here'
default_password = 'your-password-for-api-here'
config = config or {}
configfile = local.path(configfile)
if not configfile.exists():
configfile.dirnam... | python | def load_conf(configfile, config=None):
"""Get authentication data from the AUTH_CONF file."""
default_login = 'your-login-for-api-here'
default_password = 'your-password-for-api-here'
config = config or {}
configfile = local.path(configfile)
if not configfile.exists():
configfile.dirnam... | [
"def",
"load_conf",
"(",
"configfile",
",",
"config",
"=",
"None",
")",
":",
"default_login",
"=",
"'your-login-for-api-here'",
"default_password",
"=",
"'your-password-for-api-here'",
"config",
"=",
"config",
"or",
"{",
"}",
"configfile",
"=",
"local",
".",
"path... | Get authentication data from the AUTH_CONF file. | [
"Get",
"authentication",
"data",
"from",
"the",
"AUTH_CONF",
"file",
"."
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L55-L97 |
ASMfreaK/habitipy | habitipy/cli.py | get_content | def get_content(api, rebuild_cache=False):
"""get content from server or cache"""
if hasattr(get_content, 'cache') and not rebuild_cache:
return get_content.cache
if not os.path.exists(CONTENT_JSON) or rebuild_cache:
import locale
content_endpoint = api.content.get
# pylint: ... | python | def get_content(api, rebuild_cache=False):
"""get content from server or cache"""
if hasattr(get_content, 'cache') and not rebuild_cache:
return get_content.cache
if not os.path.exists(CONTENT_JSON) or rebuild_cache:
import locale
content_endpoint = api.content.get
# pylint: ... | [
"def",
"get_content",
"(",
"api",
",",
"rebuild_cache",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"get_content",
",",
"'cache'",
")",
"and",
"not",
"rebuild_cache",
":",
"return",
"get_content",
".",
"cache",
"if",
"not",
"os",
".",
"path",
".",
"exi... | get content from server or cache | [
"get",
"content",
"from",
"server",
"or",
"cache"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L126-L164 |
ASMfreaK/habitipy | habitipy/cli.py | get_additional_rewards | def get_additional_rewards(api):
"""returns list of non-user rewards (potion, armoire, gear)"""
c = get_content(api)
tasks = [c[i] for i in ['potion', 'armoire']]
tasks.extend(api.user.inventory.buy.get())
for task in tasks:
task['id'] = task['alias'] = task['key']
return tasks | python | def get_additional_rewards(api):
"""returns list of non-user rewards (potion, armoire, gear)"""
c = get_content(api)
tasks = [c[i] for i in ['potion', 'armoire']]
tasks.extend(api.user.inventory.buy.get())
for task in tasks:
task['id'] = task['alias'] = task['key']
return tasks | [
"def",
"get_additional_rewards",
"(",
"api",
")",
":",
"c",
"=",
"get_content",
"(",
"api",
")",
"tasks",
"=",
"[",
"c",
"[",
"i",
"]",
"for",
"i",
"in",
"[",
"'potion'",
",",
"'armoire'",
"]",
"]",
"tasks",
".",
"extend",
"(",
"api",
".",
"user",
... | returns list of non-user rewards (potion, armoire, gear) | [
"returns",
"list",
"of",
"non",
"-",
"user",
"rewards",
"(",
"potion",
"armoire",
"gear",
")"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L365-L372 |
ASMfreaK/habitipy | habitipy/cli.py | ScoreInfo.color | def color(cls, value):
"""task value/score color"""
index = bisect(cls.breakpoints, value)
return colors.fg(cls.colors_[index]) | python | def color(cls, value):
"""task value/score color"""
index = bisect(cls.breakpoints, value)
return colors.fg(cls.colors_[index]) | [
"def",
"color",
"(",
"cls",
",",
"value",
")",
":",
"index",
"=",
"bisect",
"(",
"cls",
".",
"breakpoints",
",",
"value",
")",
"return",
"colors",
".",
"fg",
"(",
"cls",
".",
"colors_",
"[",
"index",
"]",
")"
] | task value/score color | [
"task",
"value",
"/",
"score",
"color"
] | train | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L289-L292 |
maxalbert/tohu | tohu/v6/custom_generator/custom_generator.py | augment_init_method | def augment_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the field generators and similar bookkeeping.
"""
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
super(CustomGenerator, self).__init__() # TODO: does this ... | python | def augment_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the field generators and similar bookkeeping.
"""
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
super(CustomGenerator, self).__init__() # TODO: does this ... | [
"def",
"augment_init_method",
"(",
"cls",
")",
":",
"orig_init",
"=",
"cls",
".",
"__init__",
"def",
"new_init",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"CustomGenerator",
",",
"self",
")",
".",
"__init__",
"(",
... | Replace the existing cls.__init__() method with a new one which
also initialises the field generators and similar bookkeeping. | [
"Replace",
"the",
"existing",
"cls",
".",
"__init__",
"()",
"method",
"with",
"a",
"new",
"one",
"which",
"also",
"initialises",
"the",
"field",
"generators",
"and",
"similar",
"bookkeeping",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/custom_generator.py#L9-L39 |
maxalbert/tohu | tohu/v2/custom_generator.py | find_field_generators | def find_field_generators(obj):
"""
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces.
"""
cls_dict = obj.__class__.__dict__
obj_dict = obj.__dict__
#debug_print_dict(cls_dict, 'cls_dict')
#debug_prin... | python | def find_field_generators(obj):
"""
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces.
"""
cls_dict = obj.__class__.__dict__
obj_dict = obj.__dict__
#debug_print_dict(cls_dict, 'cls_dict')
#debug_prin... | [
"def",
"find_field_generators",
"(",
"obj",
")",
":",
"cls_dict",
"=",
"obj",
".",
"__class__",
".",
"__dict__",
"obj_dict",
"=",
"obj",
".",
"__dict__",
"#debug_print_dict(cls_dict, 'cls_dict')",
"#debug_print_dict(obj_dict, 'obj_dict')",
"field_gens",
"=",
"{",
"}",
... | Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces. | [
"Return",
"dictionary",
"with",
"the",
"names",
"and",
"instances",
"of",
"all",
"tohu",
".",
"BaseGenerator",
"occurring",
"in",
"the",
"given",
"object",
"s",
"class",
"&",
"instance",
"namespaces",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L20-L36 |
maxalbert/tohu | tohu/v2/custom_generator.py | set_item_class_name | def set_item_class_name(cls_obj):
"""
Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux
"""
if '__tohu__items__name__' in... | python | def set_item_class_name(cls_obj):
"""
Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux
"""
if '__tohu__items__name__' in... | [
"def",
"set_item_class_name",
"(",
"cls_obj",
")",
":",
"if",
"'__tohu__items__name__'",
"in",
"cls_obj",
".",
"__dict__",
":",
"logger",
".",
"debug",
"(",
"f\"Using item class name '{cls_obj.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')\"",
")",
"else",... | Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux | [
"Return",
"the",
"first",
"part",
"of",
"the",
"class",
"name",
"of",
"this",
"custom",
"generator",
".",
"This",
"will",
"be",
"used",
"for",
"the",
"class",
"name",
"of",
"the",
"items",
"produced",
"by",
"this",
"generator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L39-L59 |
maxalbert/tohu | tohu/v2/custom_generator.py | make_item_class_for_custom_generator | def make_item_class_for_custom_generator(obj):
"""
obj:
The custom generator instance for which to create an item class
"""
clsname = obj.__tohu_items_name__
attr_names = obj.field_gens.keys()
return make_item_class(clsname, attr_names) | python | def make_item_class_for_custom_generator(obj):
"""
obj:
The custom generator instance for which to create an item class
"""
clsname = obj.__tohu_items_name__
attr_names = obj.field_gens.keys()
return make_item_class(clsname, attr_names) | [
"def",
"make_item_class_for_custom_generator",
"(",
"obj",
")",
":",
"clsname",
"=",
"obj",
".",
"__tohu_items_name__",
"attr_names",
"=",
"obj",
".",
"field_gens",
".",
"keys",
"(",
")",
"return",
"make_item_class",
"(",
"clsname",
",",
"attr_names",
")"
] | obj:
The custom generator instance for which to create an item class | [
"obj",
":",
"The",
"custom",
"generator",
"instance",
"for",
"which",
"to",
"create",
"an",
"item",
"class"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L108-L115 |
maxalbert/tohu | tohu/v2/custom_generator.py | add_new_init_method | def add_new_init_method(obj):
"""
Replace the existing obj.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
... | python | def add_new_init_method(obj):
"""
Replace the existing obj.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
... | [
"def",
"add_new_init_method",
"(",
"obj",
")",
":",
"orig_init",
"=",
"obj",
".",
"__init__",
"def",
"new_init",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Initialising new {self}\"",
")",
"# Call ori... | Replace the existing obj.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
(2) ..to do.. | [
"Replace",
"the",
"existing",
"obj",
".",
"__init__",
"()",
"method",
"with",
"a",
"new",
"one",
"which",
"calls",
"the",
"original",
"one",
"and",
"in",
"addition",
"performs",
"the",
"following",
"actions",
":"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L118-L192 |
maxalbert/tohu | tohu/v2/custom_generator.py | add_new_reset_method | def add_new_reset_method(obj):
"""
Attach a new `reset()` method to `obj` which resets the internal
seed generator of `obj` and then resets each of its constituent
field generators found in `obj.field_gens`.
"""
#
# Create and assign automatically generated reset() method
#
def ne... | python | def add_new_reset_method(obj):
"""
Attach a new `reset()` method to `obj` which resets the internal
seed generator of `obj` and then resets each of its constituent
field generators found in `obj.field_gens`.
"""
#
# Create and assign automatically generated reset() method
#
def ne... | [
"def",
"add_new_reset_method",
"(",
"obj",
")",
":",
"#",
"# Create and assign automatically generated reset() method",
"#",
"def",
"new_reset",
"(",
"self",
",",
"seed",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"f'[EEE] Inside automatically generated reset()... | Attach a new `reset()` method to `obj` which resets the internal
seed generator of `obj` and then resets each of its constituent
field generators found in `obj.field_gens`. | [
"Attach",
"a",
"new",
"reset",
"()",
"method",
"to",
"obj",
"which",
"resets",
"the",
"internal",
"seed",
"generator",
"of",
"obj",
"and",
"then",
"resets",
"each",
"of",
"its",
"constituent",
"field",
"generators",
"found",
"in",
"obj",
".",
"field_gens",
... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L195-L225 |
maxalbert/tohu | tohu/v2/custom_generator.py | add_new_next_method | def add_new_next_method(obj):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
obj.__next__ = new_next | python | def add_new_next_method(obj):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
obj.__next__ = new_next | [
"def",
"add_new_next_method",
"(",
"obj",
")",
":",
"def",
"new_next",
"(",
"self",
")",
":",
"field_values",
"=",
"[",
"next",
"(",
"g",
")",
"for",
"g",
"in",
"self",
".",
"field_gens",
".",
"values",
"(",
")",
"]",
"return",
"self",
".",
"item_cls... | TODO | [
"TODO"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L228-L237 |
maxalbert/tohu | tohu/v2/custom_generator.py | add_new_spawn_method | def add_new_spawn_method(obj):
"""
TODO
"""
def new_spawn(self):
# TODO/FIXME: Check that this does the right thing:
# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour)
# (ii) ensure that it... | python | def add_new_spawn_method(obj):
"""
TODO
"""
def new_spawn(self):
# TODO/FIXME: Check that this does the right thing:
# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour)
# (ii) ensure that it... | [
"def",
"add_new_spawn_method",
"(",
"obj",
")",
":",
"def",
"new_spawn",
"(",
"self",
")",
":",
"# TODO/FIXME: Check that this does the right thing:",
"# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviou... | TODO | [
"TODO"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L240-L252 |
maxalbert/tohu | tohu/v6/set_special_methods.py | check_that_operator_can_be_applied_to_produces_items | 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)
... | python | 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",
")",
":",
"g1_tmp_copy",
"=",
"g1",
".",
"spawn",
"(",
")",
"g2_tmp_copy",
"=",
"g2",
".",
"spawn",
"(",
")",
"sample_item_1",
"=",
"next",
"(",
"g1_tmp_copy",
")... | Helper function to check that the operator `op` can be applied to items produced by g1 and g2. | [
"Helper",
"function",
"to",
"check",
"that",
"the",
"operator",
"op",
"can",
"be",
"applied",
"to",
"items",
"produced",
"by",
"g1",
"and",
"g2",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/set_special_methods.py#L16-L28 |
maxalbert/tohu | tohu/v2/base.py | add_new_init_method | 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... | python | 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",
")",
":",
"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. | [
"Replace",
"the",
"existing",
"cls",
".",
"__init__",
"()",
"method",
"with",
"a",
"new",
"one",
"which",
"also",
"initialises",
"the",
"_dependent_generators",
"attribute",
"to",
"an",
"empty",
"list",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L113-L125 |
maxalbert/tohu | tohu/v2/base.py | add_new_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
... | python | 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",
")",
":",
"if",
"isinstance",
"(",
"cls",
".",
"__repr__",
",",
"WrapperDescriptorType",
")",
":",
"cls",
".",
"__repr__",
"=",
"lambda",
"self",
":",
"f\"<{self.__class__.__name__}, id={hex(id(self))}>\"",
"else",
":",
"#... | Add default __repr__ method in case no user-defined one is present. | [
"Add",
"default",
"__repr__",
"method",
"in",
"case",
"no",
"user",
"-",
"defined",
"one",
"is",
"present",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L128-L137 |
maxalbert/tohu | tohu/v2/base.py | add_new_reset_method | 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 ... | python | 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",
")",
":",
"orig_reset",
"=",
"cls",
".",
"reset",
"def",
"new_reset",
"(",
"self",
",",
"seed",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Calling reset() on {self} (seed={seed})\"",
")",
"orig_reset",
"(... | Replace existing cls.reset() method with a new one which also
calls reset() on any clones. | [
"Replace",
"existing",
"cls",
".",
"reset",
"()",
"method",
"with",
"a",
"new",
"one",
"which",
"also",
"calls",
"reset",
"()",
"on",
"any",
"clones",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L141-L155 |
maxalbert/tohu | tohu/v2/base.py | UltraBaseGenerator.generate | 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... | python | 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",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"self",
".",
"reset",
"(",
"seed",
")",
"items",
"=",
"islice",
"(",
"self",
",",
... | Return sequence of `N` elements.
If `seed` is not None, the generator is reset
using this seed before generating the elements. | [
"Return",
"sequence",
"of",
"N",
"elements",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L34-L50 |
maxalbert/tohu | tohu/v2/base_NEW.py | TohuUltraBaseGenerator.tohu_id | 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))... | python | 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",
")",
":",
"myhash",
"=",
"hashlib",
".",
"md5",
"(",
"str",
"(",
"id",
"(",
"self",
")",
")",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"return",
"myhash",
"[",
":",
"12",
"]"
] | 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. | [
"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",
"... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base_NEW.py#L122-L130 |
maxalbert/tohu | tohu/v4/custom_generator.py | CustomGenerator._set_item_class | 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) | python | 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",
")",
":",
"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 | [
"cls",
":",
"The",
"custom",
"generator",
"class",
"for",
"which",
"to",
"create",
"an",
"item",
"-",
"class"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/custom_generator.py#L130-L136 |
maxalbert/tohu | tohu/v4/custom_generator.py | CustomGenerator._find_field_generator_templates | 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... | python | 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",
")",
":",
"field_gen_templates",
"=",
"{",
"}",
"# Extract field generators from class dict",
"for",
"name",
",",
"g",
"in",
"self",
".",
"__class__",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isi... | Return a dictionary of the form {name: field_generator} containing
all tohu generators defined in the class and instance namespace
of this custom generator. | [
"Return",
"a",
"dictionary",
"of",
"the",
"form",
"{",
"name",
":",
"field_generator",
"}",
"containing",
"all",
"tohu",
"generators",
"defined",
"in",
"the",
"class",
"and",
"instance",
"namespace",
"of",
"this",
"custom",
"generator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/custom_generator.py#L142-L160 |
maxalbert/tohu | tohu/v4/item_list.py | _generate_csv_header_line | 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... | python | 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'",
")",
":",
"if",
"isinstance",
"(",
"header",
",",
"str",
")",
":",
"# ... | Helper function to generate a CSV header line depending on
the combination of arguments provided. | [
"Helper",
"function",
"to",
"generate",
"a",
"CSV",
"header",
"line",
"depending",
"on",
"the",
"combination",
"of",
"arguments",
"provided",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L14-L29 |
maxalbert/tohu | tohu/v4/item_list.py | _extract_schema_if_given | 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')
(... | python | 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",
")",
":",
"pattern",
"=",
"'^(([^.]+)\\.)?(.+)$'",
"m",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"table_name",
")",
"schema",
",",
"table_name",
"=",
"m",
".",
"group",
"(",
"2",
")",
",",
"m",
"... | 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... | [
"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",
... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L32-L49 |
maxalbert/tohu | tohu/v4/item_list.py | ItemList.to_df | 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... | python | 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",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"fields",
"=",
"{",
"name",
":",
"name",
"for",
"name",
"in",
"fields",
"}",
"if",
"fields",
"is"... | 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... | [
"Export",
"items",
"as",
"rows",
"in",
"a",
"pandas",
"dataframe",
"table",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L101-L130 |
maxalbert/tohu | tohu/v4/item_list.py | ItemList.to_csv | 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... | python | 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 `append=True` to open the file in append mode instead.
If filename is None, the generated CSV output is returned instead of writt... | [
"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... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L132-L206 |
maxalbert/tohu | tohu/v5/base.py | SpawnMapping.spawn_generator | 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) | python | 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",
")",
":",
"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. | [
"Return",
"a",
"fresh",
"spawn",
"of",
"g",
"unless",
"g",
"is",
"already",
"contained",
"in",
"this",
"SpawnMapping",
"in",
"which",
"case",
"return",
"the",
"previously",
"spawned",
"generator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L30-L39 |
maxalbert/tohu | tohu/v5/base.py | TohuBaseGenerator.spawn | 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 ... | python | 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",
")",
":",
"spawn_mapping",
"=",
"spawn_mapping",
"or",
"SpawnMapping",
"(",
")",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"if",
"self",
".",
"parent",
"in",
"spawn_mapping",
":... | 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... | [
"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",
".",
... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L171-L189 |
maxalbert/tohu | tohu/v5/base.py | TohuBaseGenerator.clone | 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)
... | python | 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",
")",
":",
"c",
"=",
"self",
".",
"spawn",
"(",
"spawn_mapping",
")",
"self",
".",
"register_clone",
"(",
"c",
")",
"c",
".",
"register_parent",
"(",
"self",
")",
"return",
"c"
] | 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. | [
"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... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L195-L204 |
maxalbert/tohu | tohu/v4/derived_generators.py | FuncArgGens.all_generators | 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 | python | 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",
")",
":",
"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. | [
"Convenience",
"property",
"to",
"iterate",
"over",
"all",
"generators",
"in",
"arg_gens",
"and",
"kwarg_gens",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/derived_generators.py#L40-L48 |
maxalbert/tohu | tohu/v2/generators.py | Split | 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... | python | 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",
")",
":",
"if",
"tuple_len",
"is",
"None",
":",
"try",
":",
"tuple_len",
"=",
"g",
".",
"tuple_len",
"except",
"AttributeError",
":",
"raise",
"ValueError",... | 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. | [
"Split",
"a",
"tuple",
"generator",
"into",
"individual",
"generators",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/generators.py#L956-L975 |
maxalbert/tohu | tohu/v2/generators.py | TupleGenerator.tuple_len | 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__)) | python | 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",
")",
":",
"try",
":",
"return",
"self",
".",
"_tuple_len",
"except",
"AttributeError",
":",
"raise",
"NotImplementedError",
"(",
"\"Class {} does not implement attribute 'tuple_len'.\"",
".",
"format",
"(",
"self",
".",
"__class__",
... | Length of tuples produced by this generator. | [
"Length",
"of",
"tuples",
"produced",
"by",
"this",
"generator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/generators.py#L48-L55 |
Morrolan/surrealism | surrealism.py | show_faults | 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... | python | 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",
"(",
")",
":",
"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... | 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) | [
"Return",
"all",
"valid",
"/",
"active",
"faults",
"ordered",
"by",
"ID",
"to",
"allow",
"the",
"user",
"to",
"pick",
"and",
"choose",
"."
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L71-L82 |
Morrolan/surrealism | surrealism.py | show_sentences | 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_... | python | 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",
"(",
")",
":",
"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",
".... | 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. | [
"Return",
"all",
"valid",
"/",
"active",
"sentences",
"ordered",
"by",
"ID",
"to",
"allow",
"the",
"user",
"to",
"pick",
"and",
"choose",
"."
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L94-L111 |
Morrolan/surrealism | surrealism.py | get_fault | 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... | python | 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",
")",
":",
"counts",
"=",
"__get_table_limits",
"(",
")",
"result",
"=",
"None",
"id_",
"=",
"0",
"try",
":",
"if",
"isinstance",
"(",
"fault_id",
",",
"int",
")",
":",
"id_",
"=",
"fault_id",
"elif",
... | 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. | [
"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"... | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L185-L229 |
Morrolan/surrealism | surrealism.py | get_sentence | 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... | python | 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",
")",
":",
"counts",
"=",
"__get_table_limits",
"(",
")",
"result",
"=",
"None",
"id_",
"=",
"0",
"try",
":",
"if",
"isinstance",
"(",
"sentence_id",
",",
"int",
")",
":",
"id_",
"=",
"sentence_id",
... | 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. | [
"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",
... | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L237-L282 |
Morrolan/surrealism | surrealism.py | __get_sentence | 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... | python | 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",
")",
":",
"# 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 ... | Let's fetch a random sentence that we then need to substitute bits of...
@
:param counts:
:param sentence_id: | [
"Let",
"s",
"fetch",
"a",
"random",
"sentence",
"that",
"we",
"then",
"need",
"to",
"substitute",
"bits",
"of",
"..."
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L327-L364 |
Morrolan/surrealism | surrealism.py | __get_verb | 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... | python | 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",
")",
":",
"cursor",
"=",
"CONN",
".",
"cursor",
"(",
")",
"check_query",
"=",
"\"select verb_id from surverbs\"",
"cursor",
".",
"execute",
"(",
"check_query",
")",
"check_result",
"=",
"cursor",
".",
"fetchall",
"(",
")",
... | Let's fetch a VERB
:param counts: | [
"Let",
"s",
"fetch",
"a",
"VERB",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L367-L392 |
Morrolan/surrealism | surrealism.py | __get_table_limits | def __get_table_limits():
"""Here we simply take a count of each of the database tables so we know our
upper limits for our random number calls then return a dictionary of them
to the calling function..."""
table_counts = {
'max_adjectives': None,
'max_names': None,
'max_nouns'... | python | def __get_table_limits():
"""Here we simply take a count of each of the database tables so we know our
upper limits for our random number calls then return a dictionary of them
to the calling function..."""
table_counts = {
'max_adjectives': None,
'max_names': None,
'max_nouns'... | [
"def",
"__get_table_limits",
"(",
")",
":",
"table_counts",
"=",
"{",
"'max_adjectives'",
":",
"None",
",",
"'max_names'",
":",
"None",
",",
"'max_nouns'",
":",
"None",
",",
"'max_sentences'",
":",
"None",
",",
"'max_faults'",
":",
"None",
",",
"'max_verbs'",
... | Here we simply take a count of each of the database tables so we know our
upper limits for our random number calls then return a dictionary of them
to the calling function... | [
"Here",
"we",
"simply",
"take",
"a",
"count",
"of",
"each",
"of",
"the",
"database",
"tables",
"so",
"we",
"know",
"our",
"upper",
"limits",
"for",
"our",
"random",
"number",
"calls",
"then",
"return",
"a",
"dictionary",
"of",
"them",
"to",
"the",
"calli... | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L478-L518 |
Morrolan/surrealism | surrealism.py | __process_sentence | def __process_sentence(sentence_tuple, counts):
"""pull the actual sentence from the tuple (tuple contains additional data such as ID)
:param _sentence_tuple:
:param counts:
"""
sentence = sentence_tuple[2]
# now we start replacing words one type at a time...
sentence = __replace_verbs(sen... | python | def __process_sentence(sentence_tuple, counts):
"""pull the actual sentence from the tuple (tuple contains additional data such as ID)
:param _sentence_tuple:
:param counts:
"""
sentence = sentence_tuple[2]
# now we start replacing words one type at a time...
sentence = __replace_verbs(sen... | [
"def",
"__process_sentence",
"(",
"sentence_tuple",
",",
"counts",
")",
":",
"sentence",
"=",
"sentence_tuple",
"[",
"2",
"]",
"# now we start replacing words one type at a time...",
"sentence",
"=",
"__replace_verbs",
"(",
"sentence",
",",
"counts",
")",
"sentence",
... | pull the actual sentence from the tuple (tuple contains additional data such as ID)
:param _sentence_tuple:
:param counts: | [
"pull",
"the",
"actual",
"sentence",
"from",
"the",
"tuple",
"(",
"tuple",
"contains",
"additional",
"data",
"such",
"as",
"ID",
")",
":",
"param",
"_sentence_tuple",
":",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L521-L559 |
Morrolan/surrealism | surrealism.py | __replace_verbs | def __replace_verbs(sentence, counts):
"""Lets find and replace all instances of #VERB
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#VERB') != -1:
sentence = sentence.replace('#VERB', str(__get_verb(counts)), 1)
if sentence.find... | python | def __replace_verbs(sentence, counts):
"""Lets find and replace all instances of #VERB
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#VERB') != -1:
sentence = sentence.replace('#VERB', str(__get_verb(counts)), 1)
if sentence.find... | [
"def",
"__replace_verbs",
"(",
"sentence",
",",
"counts",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#VERB'",
")",
"!=",
"-",
"1",
":",
"sentence",
"=",
"sentence",
".",
"replace",
"(",
"'#VERB'",
","... | Lets find and replace all instances of #VERB
:param _sentence:
:param counts: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#VERB",
":",
"param",
"_sentence",
":",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L562-L576 |
Morrolan/surrealism | surrealism.py | __replace_nouns | def __replace_nouns(sentence, counts):
"""Lets find and replace all instances of #NOUN
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NOUN') != -1:
sentence = sentence.replace('#NOUN', str(__get_noun(counts)), 1)
if sentence.find... | python | def __replace_nouns(sentence, counts):
"""Lets find and replace all instances of #NOUN
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NOUN') != -1:
sentence = sentence.replace('#NOUN', str(__get_noun(counts)), 1)
if sentence.find... | [
"def",
"__replace_nouns",
"(",
"sentence",
",",
"counts",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#NOUN'",
")",
"!=",
"-",
"1",
":",
"sentence",
"=",
"sentence",
".",
"replace",
"(",
"'#NOUN'",
","... | Lets find and replace all instances of #NOUN
:param _sentence:
:param counts: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#NOUN",
":",
"param",
"_sentence",
":",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L579-L594 |
Morrolan/surrealism | surrealism.py | ___replace_adjective_maybe | def ___replace_adjective_maybe(sentence, counts):
"""Lets find and replace all instances of #ADJECTIVE_MAYBE
:param _sentence:
:param counts:
"""
random_decision = random.randint(0, 1)
if sentence is not None:
while sentence.find('#ADJECTIVE_MAYBE') != -1:
if random_decis... | python | def ___replace_adjective_maybe(sentence, counts):
"""Lets find and replace all instances of #ADJECTIVE_MAYBE
:param _sentence:
:param counts:
"""
random_decision = random.randint(0, 1)
if sentence is not None:
while sentence.find('#ADJECTIVE_MAYBE') != -1:
if random_decis... | [
"def",
"___replace_adjective_maybe",
"(",
"sentence",
",",
"counts",
")",
":",
"random_decision",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"1",
")",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#ADJECTIVE_MAYBE'",... | Lets find and replace all instances of #ADJECTIVE_MAYBE
:param _sentence:
:param counts: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#ADJECTIVE_MAYBE",
":",
"param",
"_sentence",
":",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L597-L619 |
Morrolan/surrealism | surrealism.py | __replace_adjective | def __replace_adjective(sentence, counts):
"""Lets find and replace all instances of #ADJECTIVE
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#ADJECTIVE') != -1:
sentence = sentence.replace('#ADJECTIVE',
... | python | def __replace_adjective(sentence, counts):
"""Lets find and replace all instances of #ADJECTIVE
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#ADJECTIVE') != -1:
sentence = sentence.replace('#ADJECTIVE',
... | [
"def",
"__replace_adjective",
"(",
"sentence",
",",
"counts",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#ADJECTIVE'",
")",
"!=",
"-",
"1",
":",
"sentence",
"=",
"sentence",
".",
"replace",
"(",
"'#ADJE... | Lets find and replace all instances of #ADJECTIVE
:param _sentence:
:param counts: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#ADJECTIVE",
":",
"param",
"_sentence",
":",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L622-L638 |
Morrolan/surrealism | surrealism.py | __replace_names | def __replace_names(sentence, counts):
"""Lets find and replace all instances of #NAME
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NAME') != -1:
sentence = sentence.replace('#NAME', str(__get_name(counts)), 1)
if sentence.fin... | python | def __replace_names(sentence, counts):
"""Lets find and replace all instances of #NAME
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NAME') != -1:
sentence = sentence.replace('#NAME', str(__get_name(counts)), 1)
if sentence.fin... | [
"def",
"__replace_names",
"(",
"sentence",
",",
"counts",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#NAME'",
")",
"!=",
"-",
"1",
":",
"sentence",
"=",
"sentence",
".",
"replace",
"(",
"'#NAME'",
","... | Lets find and replace all instances of #NAME
:param _sentence:
:param counts: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#NAME",
":",
"param",
"_sentence",
":",
":",
"param",
"counts",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L641-L656 |
Morrolan/surrealism | surrealism.py | __replace_an | def __replace_an(sentence):
"""Lets find and replace all instances of #AN
This is a little different, as this depends on whether the next
word starts with a vowel or a consonant.
:param _sentence:
"""
if sentence is not None:
while sentence.find('#AN') != -1:
an_index = sen... | python | def __replace_an(sentence):
"""Lets find and replace all instances of #AN
This is a little different, as this depends on whether the next
word starts with a vowel or a consonant.
:param _sentence:
"""
if sentence is not None:
while sentence.find('#AN') != -1:
an_index = sen... | [
"def",
"__replace_an",
"(",
"sentence",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#AN'",
")",
"!=",
"-",
"1",
":",
"an_index",
"=",
"sentence",
".",
"find",
"(",
"'#AN'",
")",
"if",
"an_index",
">"... | Lets find and replace all instances of #AN
This is a little different, as this depends on whether the next
word starts with a vowel or a consonant.
:param _sentence: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#AN",
"This",
"is",
"a",
"little",
"different",
"as",
"this",
"depends",
"on",
"whether",
"the",
"next",
"word",
"starts",
"with",
"a",
"vowel",
"or",
"a",
"consonant",
"."
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L659-L683 |
Morrolan/surrealism | surrealism.py | __replace_random | def __replace_random(sentence):
"""Lets find and replace all instances of #RANDOM
:param _sentence:
"""
sub_list = None
choice = None
if sentence is not None:
while sentence.find('#RANDOM') != -1:
random_index = sentence.find('#RANDOM')
start_index = sentence.... | python | def __replace_random(sentence):
"""Lets find and replace all instances of #RANDOM
:param _sentence:
"""
sub_list = None
choice = None
if sentence is not None:
while sentence.find('#RANDOM') != -1:
random_index = sentence.find('#RANDOM')
start_index = sentence.... | [
"def",
"__replace_random",
"(",
"sentence",
")",
":",
"sub_list",
"=",
"None",
"choice",
"=",
"None",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#RANDOM'",
")",
"!=",
"-",
"1",
":",
"random_index",
"=",
"sentence... | Lets find and replace all instances of #RANDOM
:param _sentence: | [
"Lets",
"find",
"and",
"replace",
"all",
"instances",
"of",
"#RANDOM",
":",
"param",
"_sentence",
":"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L686-L716 |
Morrolan/surrealism | surrealism.py | __replace_repeat | def __replace_repeat(sentence):
"""
Allows the use of repeating random-elements such as in the 'Ten green bottles' type sentences.
:param sentence:
"""
######### USE SENTENCE_ID 47 for testing!
repeat_dict = {}
if sentence is not None:
while sentence.find('#DEFINE_REPEAT') != -1... | python | def __replace_repeat(sentence):
"""
Allows the use of repeating random-elements such as in the 'Ten green bottles' type sentences.
:param sentence:
"""
######### USE SENTENCE_ID 47 for testing!
repeat_dict = {}
if sentence is not None:
while sentence.find('#DEFINE_REPEAT') != -1... | [
"def",
"__replace_repeat",
"(",
"sentence",
")",
":",
"######### USE SENTENCE_ID 47 for testing!",
"repeat_dict",
"=",
"{",
"}",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#DEFINE_REPEAT'",
")",
"!=",
"-",
"1",
":",
"b... | Allows the use of repeating random-elements such as in the 'Ten green bottles' type sentences.
:param sentence: | [
"Allows",
"the",
"use",
"of",
"repeating",
"random",
"-",
"elements",
"such",
"as",
"in",
"the",
"Ten",
"green",
"bottles",
"type",
"sentences",
"."
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L719-L760 |
Morrolan/surrealism | surrealism.py | __replace_capitalise | def __replace_capitalise(sentence):
"""here we replace all instances of #CAPITALISE and cap the next word.
############
#NOTE: Buggy as hell, as it doesn't account for words that are already
#capitalized
############
:param _sentence:
"""
if sentence is not None:
while senten... | python | def __replace_capitalise(sentence):
"""here we replace all instances of #CAPITALISE and cap the next word.
############
#NOTE: Buggy as hell, as it doesn't account for words that are already
#capitalized
############
:param _sentence:
"""
if sentence is not None:
while senten... | [
"def",
"__replace_capitalise",
"(",
"sentence",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#CAPITALISE'",
")",
"!=",
"-",
"1",
":",
"cap_index",
"=",
"_sentence",
".",
"find",
"(",
"'#CAPITALISE'",
")",
... | here we replace all instances of #CAPITALISE and cap the next word.
############
#NOTE: Buggy as hell, as it doesn't account for words that are already
#capitalized
############
:param _sentence: | [
"here",
"we",
"replace",
"all",
"instances",
"of",
"#CAPITALISE",
"and",
"cap",
"the",
"next",
"word",
".",
"############"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L763-L790 |
Morrolan/surrealism | surrealism.py | __replace_capall | def __replace_capall(sentence):
"""here we replace all instances of #CAPALL and cap the entire sentence.
Don't believe that CAPALL is buggy anymore as it forces all uppercase OK?
:param _sentence:
"""
# print "\nReplacing CAPITALISE: "
if sentence is not None:
while sentence.find... | python | def __replace_capall(sentence):
"""here we replace all instances of #CAPALL and cap the entire sentence.
Don't believe that CAPALL is buggy anymore as it forces all uppercase OK?
:param _sentence:
"""
# print "\nReplacing CAPITALISE: "
if sentence is not None:
while sentence.find... | [
"def",
"__replace_capall",
"(",
"sentence",
")",
":",
"# print \"\\nReplacing CAPITALISE: \"",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#CAPALL'",
")",
"!=",
"-",
"1",
":",
"# _cap_index = _sentence.find('#CAPALL')",
"sen... | here we replace all instances of #CAPALL and cap the entire sentence.
Don't believe that CAPALL is buggy anymore as it forces all uppercase OK?
:param _sentence: | [
"here",
"we",
"replace",
"all",
"instances",
"of",
"#CAPALL",
"and",
"cap",
"the",
"entire",
"sentence",
".",
"Don",
"t",
"believe",
"that",
"CAPALL",
"is",
"buggy",
"anymore",
"as",
"it",
"forces",
"all",
"uppercase",
"OK?"
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L793-L811 |
Morrolan/surrealism | surrealism.py | __check_spaces | def __check_spaces(sentence):
"""
Here we check to see that we have the correct number of spaces in the correct locations.
:param _sentence:
:return:
"""
# We have to run the process multiple times:
# Once to search for all spaces, and check if there are adjoining spaces;
# The seco... | python | def __check_spaces(sentence):
"""
Here we check to see that we have the correct number of spaces in the correct locations.
:param _sentence:
:return:
"""
# We have to run the process multiple times:
# Once to search for all spaces, and check if there are adjoining spaces;
# The seco... | [
"def",
"__check_spaces",
"(",
"sentence",
")",
":",
"# We have to run the process multiple times:",
"# Once to search for all spaces, and check if there are adjoining spaces;",
"# The second time to check for 2 spaces after sentence-ending characters such as . and ! and ?",
"if",
"sentence",... | Here we check to see that we have the correct number of spaces in the correct locations.
:param _sentence:
:return: | [
"Here",
"we",
"check",
"to",
"see",
"that",
"we",
"have",
"the",
"correct",
"number",
"of",
"spaces",
"in",
"the",
"correct",
"locations",
"."
] | train | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L814-L841 |
maxalbert/tohu | tohu/v6/utils.py | make_exploded_column | def make_exploded_column(df, colname_new, colname_old):
"""
Internal helper function used by `explode_columns()`.
"""
s = df[colname_old].apply(pd.Series).stack()
s.name = colname_new
return s | python | def make_exploded_column(df, colname_new, colname_old):
"""
Internal helper function used by `explode_columns()`.
"""
s = df[colname_old].apply(pd.Series).stack()
s.name = colname_new
return s | [
"def",
"make_exploded_column",
"(",
"df",
",",
"colname_new",
",",
"colname_old",
")",
":",
"s",
"=",
"df",
"[",
"colname_old",
"]",
".",
"apply",
"(",
"pd",
".",
"Series",
")",
".",
"stack",
"(",
")",
"s",
".",
"name",
"=",
"colname_new",
"return",
... | Internal helper function used by `explode_columns()`. | [
"Internal",
"helper",
"function",
"used",
"by",
"explode_columns",
"()",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L48-L54 |
maxalbert/tohu | tohu/v6/utils.py | explode_columns | def explode_columns(df, colnames):
"""
Given a dataframe with certain columns that contain lists,
return another dataframe where the elements in each list
are "exploded" into individual rows.
Example:
>>> df
col1 col2 col3 col4
0 foo 11 [DDD, AAA, CCC] [dd... | python | def explode_columns(df, colnames):
"""
Given a dataframe with certain columns that contain lists,
return another dataframe where the elements in each list
are "exploded" into individual rows.
Example:
>>> df
col1 col2 col3 col4
0 foo 11 [DDD, AAA, CCC] [dd... | [
"def",
"explode_columns",
"(",
"df",
",",
"colnames",
")",
":",
"if",
"isinstance",
"(",
"colnames",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"colnames",
"=",
"{",
"name",
":",
"name",
"for",
"name",
"in",
"colnames",
"}",
"remaining_columns",
"=... | Given a dataframe with certain columns that contain lists,
return another dataframe where the elements in each list
are "exploded" into individual rows.
Example:
>>> df
col1 col2 col3 col4
0 foo 11 [DDD, AAA, CCC] [dd, aa, cc]
1 bar 22 [FFF] ... | [
"Given",
"a",
"dataframe",
"with",
"certain",
"columns",
"that",
"contain",
"lists",
"return",
"another",
"dataframe",
"where",
"the",
"elements",
"in",
"each",
"list",
"are",
"exploded",
"into",
"individual",
"rows",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L57-L97 |
maxalbert/tohu | tohu/v6/utils.py | print_generated_sequence | def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `gen`.
"""
if seed:
gen.reset(seed)
elems = [format(next(gen), fmt) for _ in range(num)]
sep_initial = "\n\n" if '\n' in... | python | def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=None):
"""
Helper function which prints a sequence of `num` items
produced by the random generator `gen`.
"""
if seed:
gen.reset(seed)
elems = [format(next(gen), fmt) for _ in range(num)]
sep_initial = "\n\n" if '\n' in... | [
"def",
"print_generated_sequence",
"(",
"gen",
",",
"num",
",",
"*",
",",
"sep",
"=",
"\", \"",
",",
"fmt",
"=",
"''",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
":",
"gen",
".",
"reset",
"(",
"seed",
")",
"elems",
"=",
"[",
"format",
"(",... | Helper function which prints a sequence of `num` items
produced by the random generator `gen`. | [
"Helper",
"function",
"which",
"prints",
"a",
"sequence",
"of",
"num",
"items",
"produced",
"by",
"the",
"random",
"generator",
"gen",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L100-L110 |
maxalbert/tohu | tohu/v6/utils.py | make_dummy_tuples | def make_dummy_tuples(chars='abcde'):
"""
Helper function to create a list of namedtuples which are useful
for testing and debugging (especially of custom generators).
Example
-------
>>> make_dummy_tuples(chars='abcd')
[Quux(x='AA', y='aa'),
Quux(x='BB', y='bb'),
Quux(x='CC', y='... | python | def make_dummy_tuples(chars='abcde'):
"""
Helper function to create a list of namedtuples which are useful
for testing and debugging (especially of custom generators).
Example
-------
>>> make_dummy_tuples(chars='abcd')
[Quux(x='AA', y='aa'),
Quux(x='BB', y='bb'),
Quux(x='CC', y='... | [
"def",
"make_dummy_tuples",
"(",
"chars",
"=",
"'abcde'",
")",
":",
"Quux",
"=",
"namedtuple",
"(",
"'Quux'",
",",
"[",
"'x'",
",",
"'y'",
"]",
")",
"some_tuples",
"=",
"[",
"Quux",
"(",
"(",
"c",
"*",
"2",
")",
".",
"upper",
"(",
")",
",",
"c",
... | Helper function to create a list of namedtuples which are useful
for testing and debugging (especially of custom generators).
Example
-------
>>> make_dummy_tuples(chars='abcd')
[Quux(x='AA', y='aa'),
Quux(x='BB', y='bb'),
Quux(x='CC', y='cc'),
Quux(x='DD', y='dd')] | [
"Helper",
"function",
"to",
"create",
"a",
"list",
"of",
"namedtuples",
"which",
"are",
"useful",
"for",
"testing",
"and",
"debugging",
"(",
"especially",
"of",
"custom",
"generators",
")",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L113-L128 |
maxalbert/tohu | tohu/v6/utils.py | ensure_is_date_object | def ensure_is_date_object(x):
"""
Ensure input represents a valid date and return the corresponding `datetime.date` object.
Valid inputs:
- string of the form "YYYY-MM-DD"
- dt.date object
- pd.Timestamp of the form "YYYY-MM-DD 00:00:00" with freq='D' (as is generated by pd.date_range())... | python | def ensure_is_date_object(x):
"""
Ensure input represents a valid date and return the corresponding `datetime.date` object.
Valid inputs:
- string of the form "YYYY-MM-DD"
- dt.date object
- pd.Timestamp of the form "YYYY-MM-DD 00:00:00" with freq='D' (as is generated by pd.date_range())... | [
"def",
"ensure_is_date_object",
"(",
"x",
")",
":",
"error_msg",
"=",
"f\"Cannot convert input to date object: {x} (type: {type(x)})\"",
"if",
"isinstance",
"(",
"x",
",",
"dt",
".",
"date",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Timestamp",
")... | Ensure input represents a valid date and return the corresponding `datetime.date` object.
Valid inputs:
- string of the form "YYYY-MM-DD"
- dt.date object
- pd.Timestamp of the form "YYYY-MM-DD 00:00:00" with freq='D' (as is generated by pd.date_range()) | [
"Ensure",
"input",
"represents",
"a",
"valid",
"date",
"and",
"return",
"the",
"corresponding",
"datetime",
".",
"date",
"object",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L148-L175 |
maxalbert/tohu | tohu/v6/tohu_namespace.py | TohuNamespace.all_independent_generators | def all_independent_generators(self):
"""
Return all generators in this namespace which are not clones.
"""
return {g: name for g, name in self._ns.items() if not is_clone(g)} | python | def all_independent_generators(self):
"""
Return all generators in this namespace which are not clones.
"""
return {g: name for g, name in self._ns.items() if not is_clone(g)} | [
"def",
"all_independent_generators",
"(",
"self",
")",
":",
"return",
"{",
"g",
":",
"name",
"for",
"g",
",",
"name",
"in",
"self",
".",
"_ns",
".",
"items",
"(",
")",
"if",
"not",
"is_clone",
"(",
"g",
")",
"}"
] | Return all generators in this namespace which are not clones. | [
"Return",
"all",
"generators",
"in",
"this",
"namespace",
"which",
"are",
"not",
"clones",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/tohu_namespace.py#L60-L64 |
maxalbert/tohu | tohu/v6/custom_generator/utils.py | make_tohu_items_class | def make_tohu_items_class(clsname, attr_names):
"""
Parameters
----------
clsname: string
Name of the class to be created
attr_names: list of strings
Names of the attributes of the class to be created
"""
item_cls = attr.make_class(clsname, {name: attr.ib() for name in attr... | python | def make_tohu_items_class(clsname, attr_names):
"""
Parameters
----------
clsname: string
Name of the class to be created
attr_names: list of strings
Names of the attributes of the class to be created
"""
item_cls = attr.make_class(clsname, {name: attr.ib() for name in attr... | [
"def",
"make_tohu_items_class",
"(",
"clsname",
",",
"attr_names",
")",
":",
"item_cls",
"=",
"attr",
".",
"make_class",
"(",
"clsname",
",",
"{",
"name",
":",
"attr",
".",
"ib",
"(",
")",
"for",
"name",
"in",
"attr_names",
"}",
",",
"repr",
"=",
"Fals... | Parameters
----------
clsname: string
Name of the class to be created
attr_names: list of strings
Names of the attributes of the class to be created | [
"Parameters",
"----------",
"clsname",
":",
"string",
"Name",
"of",
"the",
"class",
"to",
"be",
"created"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/utils.py#L11-L54 |
maxalbert/tohu | tohu/v6/custom_generator/utils.py | get_tohu_items_name | def get_tohu_items_name(cls):
"""
Return a string which defines the name of the namedtuple class which will be used
to produce items for the custom generator.
By default this will be the first part of the class name (before '...Generator'),
for example:
FoobarGenerator -> Foobar
Qu... | python | def get_tohu_items_name(cls):
"""
Return a string which defines the name of the namedtuple class which will be used
to produce items for the custom generator.
By default this will be the first part of the class name (before '...Generator'),
for example:
FoobarGenerator -> Foobar
Qu... | [
"def",
"get_tohu_items_name",
"(",
"cls",
")",
":",
"assert",
"issubclass",
"(",
"cls",
",",
"TohuBaseGenerator",
")",
"try",
":",
"tohu_items_name",
"=",
"cls",
".",
"__dict__",
"[",
"'__tohu_items_name__'",
"]",
"logger",
".",
"debug",
"(",
"f\"Using item clas... | Return a string which defines the name of the namedtuple class which will be used
to produce items for the custom generator.
By default this will be the first part of the class name (before '...Generator'),
for example:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux
However, it can... | [
"Return",
"a",
"string",
"which",
"defines",
"the",
"name",
"of",
"the",
"namedtuple",
"class",
"which",
"will",
"be",
"used",
"to",
"produce",
"items",
"for",
"the",
"custom",
"generator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/utils.py#L57-L92 |
maxalbert/tohu | tohu/v4/primitive_generators.py | SelectOnePrimitive._init_randgen | def _init_randgen(self):
"""
Initialise random generator to be used for picking elements.
With the current implementation in tohu (where we pick elements
from generators individually instead of in bulk), it is faster
to `use random.Random` than `numpy.random.RandomState` (it is
... | python | def _init_randgen(self):
"""
Initialise random generator to be used for picking elements.
With the current implementation in tohu (where we pick elements
from generators individually instead of in bulk), it is faster
to `use random.Random` than `numpy.random.RandomState` (it is
... | [
"def",
"_init_randgen",
"(",
"self",
")",
":",
"if",
"self",
".",
"p",
"is",
"None",
":",
"self",
".",
"randgen",
"=",
"Random",
"(",
")",
"self",
".",
"func_random_choice",
"=",
"self",
".",
"randgen",
".",
"choice",
"else",
":",
"self",
".",
"randg... | Initialise random generator to be used for picking elements.
With the current implementation in tohu (where we pick elements
from generators individually instead of in bulk), it is faster
to `use random.Random` than `numpy.random.RandomState` (it is
possible that this may change in the f... | [
"Initialise",
"random",
"generator",
"to",
"be",
"used",
"for",
"picking",
"elements",
".",
"With",
"the",
"current",
"implementation",
"in",
"tohu",
"(",
"where",
"we",
"pick",
"elements",
"from",
"generators",
"individually",
"instead",
"of",
"in",
"bulk",
"... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/primitive_generators.py#L511-L532 |
maxalbert/tohu | tohu/v4/primitive_generators.py | SelectOnePrimitive._set_random_state_from | def _set_random_state_from(self, other):
"""
Transfer the internal state from `other` to `self`.
After this call, `self` will produce the same elements
in the same order as `other` (even though they otherwise
remain completely independent).
"""
try:
# ... | python | def _set_random_state_from(self, other):
"""
Transfer the internal state from `other` to `self`.
After this call, `self` will produce the same elements
in the same order as `other` (even though they otherwise
remain completely independent).
"""
try:
# ... | [
"def",
"_set_random_state_from",
"(",
"self",
",",
"other",
")",
":",
"try",
":",
"# this works if randgen is an instance of random.Random()",
"self",
".",
"randgen",
".",
"setstate",
"(",
"other",
".",
"randgen",
".",
"getstate",
"(",
")",
")",
"except",
"Attribu... | Transfer the internal state from `other` to `self`.
After this call, `self` will produce the same elements
in the same order as `other` (even though they otherwise
remain completely independent). | [
"Transfer",
"the",
"internal",
"state",
"from",
"other",
"to",
"self",
".",
"After",
"this",
"call",
"self",
"will",
"produce",
"the",
"same",
"elements",
"in",
"the",
"same",
"order",
"as",
"other",
"(",
"even",
"though",
"they",
"otherwise",
"remain",
"c... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/primitive_generators.py#L534-L548 |
maxalbert/tohu | tohu/v4/primitive_generators.py | SelectMultiplePrimitive._init_randgen | def _init_randgen(self):
"""
Initialise random generator to be used for picking elements.
With the current implementation in tohu (where we pick elements
from generators individually instead of in bulk), it is faster
to `use random.Random` than `numpy.random.RandomState` (it is
... | python | def _init_randgen(self):
"""
Initialise random generator to be used for picking elements.
With the current implementation in tohu (where we pick elements
from generators individually instead of in bulk), it is faster
to `use random.Random` than `numpy.random.RandomState` (it is
... | [
"def",
"_init_randgen",
"(",
"self",
")",
":",
"if",
"self",
".",
"p",
"is",
"None",
":",
"self",
".",
"randgen",
"=",
"Random",
"(",
")",
"self",
".",
"func_random_choice",
"=",
"partial",
"(",
"self",
".",
"randgen",
".",
"choices",
",",
"k",
"=",
... | Initialise random generator to be used for picking elements.
With the current implementation in tohu (where we pick elements
from generators individually instead of in bulk), it is faster
to `use random.Random` than `numpy.random.RandomState` (it is
possible that this may change in the f... | [
"Initialise",
"random",
"generator",
"to",
"be",
"used",
"for",
"picking",
"elements",
".",
"With",
"the",
"current",
"implementation",
"in",
"tohu",
"(",
"where",
"we",
"pick",
"elements",
"from",
"generators",
"individually",
"instead",
"of",
"in",
"bulk",
"... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/primitive_generators.py#L589-L610 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | update_with_tohu_generators | def update_with_tohu_generators(field_gens, adict):
"""
Helper function which updates `field_gens` with any items in the
dictionary `adict` that are instances of `TohuUltraBaseGenerator`.
"""
for name, gen in adict.items():
if isinstance(gen, TohuUltraBaseGenerator):
field_gens[n... | python | def update_with_tohu_generators(field_gens, adict):
"""
Helper function which updates `field_gens` with any items in the
dictionary `adict` that are instances of `TohuUltraBaseGenerator`.
"""
for name, gen in adict.items():
if isinstance(gen, TohuUltraBaseGenerator):
field_gens[n... | [
"def",
"update_with_tohu_generators",
"(",
"field_gens",
",",
"adict",
")",
":",
"for",
"name",
",",
"gen",
"in",
"adict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"gen",
",",
"TohuUltraBaseGenerator",
")",
":",
"field_gens",
"[",
"name",
"]",... | Helper function which updates `field_gens` with any items in the
dictionary `adict` that are instances of `TohuUltraBaseGenerator`. | [
"Helper",
"function",
"which",
"updates",
"field_gens",
"with",
"any",
"items",
"in",
"the",
"dictionary",
"adict",
"that",
"are",
"instances",
"of",
"TohuUltraBaseGenerator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L22-L29 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | find_field_generator_templates | def find_field_generator_templates(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')
#d... | python | def find_field_generator_templates(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')
#d... | [
"def",
"find_field_generator_templates",
"(",
"obj",
")",
":",
"cls_dict",
"=",
"obj",
".",
"__class__",
".",
"__dict__",
"obj_dict",
"=",
"obj",
".",
"__dict__",
"#debug_print_dict(cls_dict, 'cls_dict')",
"#debug_print_dict(obj_dict, 'obj_dict')",
"field_gens",
"=",
"{",... | Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces. | [
"Return",
"dictionary",
"with",
"the",
"names",
"and",
"instances",
"of",
"all",
"tohu",
".",
"BaseGenerator",
"occurring",
"in",
"the",
"given",
"object",
"s",
"class",
"&",
"instance",
"namespaces",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L32-L48 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | set_item_class_name_on_custom_generator_class | def set_item_class_name_on_custom_generator_class(cls):
"""
Set the attribute `cls.__tohu_items_name__` to a string which defines the name
of the namedtuple class which will be used to produce items for the custom
generator.
By default this will be the first part of the class name (before '...Gener... | python | def set_item_class_name_on_custom_generator_class(cls):
"""
Set the attribute `cls.__tohu_items_name__` to a string which defines the name
of the namedtuple class which will be used to produce items for the custom
generator.
By default this will be the first part of the class name (before '...Gener... | [
"def",
"set_item_class_name_on_custom_generator_class",
"(",
"cls",
")",
":",
"if",
"'__tohu__items__name__'",
"in",
"cls",
".",
"__dict__",
":",
"logger",
".",
"debug",
"(",
"f\"Using item class name '{cls.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')\"",
... | Set the attribute `cls.__tohu_items_name__` to a string which defines the name
of the namedtuple class which will be used to produce items for the custom
generator.
By default this will be the first part of the class name (before '...Generator'),
for example:
FoobarGenerator -> Foobar
... | [
"Set",
"the",
"attribute",
"cls",
".",
"__tohu_items_name__",
"to",
"a",
"string",
"which",
"defines",
"the",
"name",
"of",
"the",
"namedtuple",
"class",
"which",
"will",
"be",
"used",
"to",
"produce",
"items",
"for",
"the",
"custom",
"generator",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L51-L80 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | make_item_class_for_custom_generator_class | def make_item_class_for_custom_generator_class(cls):
"""
cls:
The custom generator class for which to create an item-class
"""
clsname = cls.__tohu_items_name__
attr_names = cls.field_gens.keys()
return make_item_class(clsname, attr_names) | python | def make_item_class_for_custom_generator_class(cls):
"""
cls:
The custom generator class for which to create an item-class
"""
clsname = cls.__tohu_items_name__
attr_names = cls.field_gens.keys()
return make_item_class(clsname, attr_names) | [
"def",
"make_item_class_for_custom_generator_class",
"(",
"cls",
")",
":",
"clsname",
"=",
"cls",
".",
"__tohu_items_name__",
"attr_names",
"=",
"cls",
".",
"field_gens",
".",
"keys",
"(",
")",
"return",
"make_item_class",
"(",
"clsname",
",",
"attr_names",
")"
] | cls:
The custom generator class for which to create an item-class | [
"cls",
":",
"The",
"custom",
"generator",
"class",
"for",
"which",
"to",
"create",
"an",
"item",
"-",
"class"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L129-L136 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | _add_new_init_method | def _add_new_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
... | python | def _add_new_init_method(cls):
"""
Replace the existing cls.__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",
"(",
"cls",
")",
":",
"orig_init",
"=",
"cls",
".",
"__init__",
"def",
"new_init_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Initialising new {self} (type: {type(sel... | Replace the existing cls.__init__() method with a new one
which calls the original one and in addition performs the
following actions:
(1) Finds all instances of tohu.BaseGenerator in the namespace
and collects them in the dictionary `self.field_gens`.
(2) ..to do.. | [
"Replace",
"the",
"existing",
"cls",
".",
"__init__",
"()",
"method",
"with",
"a",
"new",
"one",
"which",
"calls",
"the",
"original",
"one",
"and",
"in",
"addition",
"performs",
"the",
"following",
"actions",
":"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L139-L192 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | _add_new_next_method | def _add_new_next_method(cls):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
cls.__next__ = new_next | python | def _add_new_next_method(cls):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
cls.__next__ = new_next | [
"def",
"_add_new_next_method",
"(",
"cls",
")",
":",
"def",
"new_next",
"(",
"self",
")",
":",
"field_values",
"=",
"[",
"next",
"(",
"g",
")",
"for",
"g",
"in",
"self",
".",
"field_gens",
".",
"values",
"(",
")",
"]",
"return",
"self",
".",
"item_cl... | TODO | [
"TODO"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L195-L204 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | _add_new_reset_method | def _add_new_reset_method(cls):
"""
Attach a new `reset()` method to `cls` which resets the internal
seed generator of `cls` and then resets each of its constituent
field generators found in `cls.field_gens`.
"""
#
# Create and assign automatically generated reset() method
#
def n... | python | def _add_new_reset_method(cls):
"""
Attach a new `reset()` method to `cls` which resets the internal
seed generator of `cls` and then resets each of its constituent
field generators found in `cls.field_gens`.
"""
#
# Create and assign automatically generated reset() method
#
def n... | [
"def",
"_add_new_reset_method",
"(",
"cls",
")",
":",
"#",
"# Create and assign automatically generated reset() method",
"#",
"def",
"new_reset_method",
"(",
"self",
",",
"seed",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"f'[EEE] Inside automatically generated... | Attach a new `reset()` method to `cls` which resets the internal
seed generator of `cls` and then resets each of its constituent
field generators found in `cls.field_gens`. | [
"Attach",
"a",
"new",
"reset",
"()",
"method",
"to",
"cls",
"which",
"resets",
"the",
"internal",
"seed",
"generator",
"of",
"cls",
"and",
"then",
"resets",
"each",
"of",
"its",
"constituent",
"field",
"generators",
"found",
"in",
"cls",
".",
"field_gens",
... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L207-L237 |
maxalbert/tohu | tohu/v2/custom_generator_NEW.py | _add_new_spawn_method | def _add_new_spawn_method(cls):
"""
TODO
"""
def new_spawn_method(self, dependency_mapping):
# 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)
... | python | def _add_new_spawn_method(cls):
"""
TODO
"""
def new_spawn_method(self, dependency_mapping):
# 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)
... | [
"def",
"_add_new_spawn_method",
"(",
"cls",
")",
":",
"def",
"new_spawn_method",
"(",
"self",
",",
"dependency_mapping",
")",
":",
"# 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 independentl... | TODO | [
"TODO"
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L240-L259 |
maxalbert/tohu | tohu/v6/derived_generators.py | DerivedGenerator.reset_input_generators | def reset_input_generators(self, seed):
"""
Helper method which explicitly resets all input generators
to the derived generator. This should only ever be called
for testing or debugging.
"""
seed_generator = SeedGenerator().reset(seed=seed)
for gen in self.input_... | python | def reset_input_generators(self, seed):
"""
Helper method which explicitly resets all input generators
to the derived generator. This should only ever be called
for testing or debugging.
"""
seed_generator = SeedGenerator().reset(seed=seed)
for gen in self.input_... | [
"def",
"reset_input_generators",
"(",
"self",
",",
"seed",
")",
":",
"seed_generator",
"=",
"SeedGenerator",
"(",
")",
".",
"reset",
"(",
"seed",
"=",
"seed",
")",
"for",
"gen",
"in",
"self",
".",
"input_generators",
":",
"gen",
".",
"reset",
"(",
"next"... | Helper method which explicitly resets all input generators
to the derived generator. This should only ever be called
for testing or debugging. | [
"Helper",
"method",
"which",
"explicitly",
"resets",
"all",
"input",
"generators",
"to",
"the",
"derived",
"generator",
".",
"This",
"should",
"only",
"ever",
"be",
"called",
"for",
"testing",
"or",
"debugging",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/derived_generators.py#L20-L35 |
maxalbert/tohu | tohu/v6/derived_generators.py | SelectOne._spot_check_that_elements_produced_by_this_generator_have_attribute | def _spot_check_that_elements_produced_by_this_generator_have_attribute(self, name):
"""
Helper function to spot-check that the items produces by this generator have the attribute `name`.
"""
g_tmp = self.values_gen.spawn()
sample_element = next(g_tmp)[0]
try:
... | python | def _spot_check_that_elements_produced_by_this_generator_have_attribute(self, name):
"""
Helper function to spot-check that the items produces by this generator have the attribute `name`.
"""
g_tmp = self.values_gen.spawn()
sample_element = next(g_tmp)[0]
try:
... | [
"def",
"_spot_check_that_elements_produced_by_this_generator_have_attribute",
"(",
"self",
",",
"name",
")",
":",
"g_tmp",
"=",
"self",
".",
"values_gen",
".",
"spawn",
"(",
")",
"sample_element",
"=",
"next",
"(",
"g_tmp",
")",
"[",
"0",
"]",
"try",
":",
"get... | Helper function to spot-check that the items produces by this generator have the attribute `name`. | [
"Helper",
"function",
"to",
"spot",
"-",
"check",
"that",
"the",
"items",
"produces",
"by",
"this",
"generator",
"have",
"the",
"attribute",
"name",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/derived_generators.py#L201-L210 |
maxalbert/tohu | tohu/v6/item_list.py | ItemList.to_df | def to_df(self, fields=None, fields_to_explode=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 gene... | python | def to_df(self, fields=None, fields_to_explode=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 gene... | [
"def",
"to_df",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"fields_to_explode",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"fields",
"=",
"{",
"name",
":",
"name",
"for",
"name",
"in"... | 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... | [
"Export",
"items",
"as",
"rows",
"in",
"a",
"pandas",
"dataframe",
"table",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L104-L180 |
maxalbert/tohu | tohu/v6/item_list.py | ItemList.to_csv | def to_csv(self, output_file=None, *, fields=None, fields_to_explode=None, append=False, header=True, header_prefix='', sep=',', newline='\n'):
"""
Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing... | python | def to_csv(self, output_file=None, *, fields=None, fields_to_explode=None, append=False, header=True, header_prefix='', sep=',', newline='\n'):
"""
Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing... | [
"def",
"to_csv",
"(",
"self",
",",
"output_file",
"=",
"None",
",",
"*",
",",
"fields",
"=",
"None",
",",
"fields_to_explode",
"=",
"None",
",",
"append",
"=",
"False",
",",
"header",
"=",
"True",
",",
"header_prefix",
"=",
"''",
",",
"sep",
"=",
"',... | Parameters
----------
output_file: str or file object 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 `output_file` is None, the generated CSV output is re... | [
"Parameters",
"----------",
"output_file",
":",
"str",
"or",
"file",
"object",
"or",
"None",
"The",
"file",
"to",
"which",
"output",
"will",
"be",
"written",
".",
"By",
"default",
"any",
"existing",
"content",
"is",
"overwritten",
".",
"Use",
"append",
"=",
... | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L182-L280 |
maxalbert/tohu | tohu/v6/item_list.py | ItemList.to_sql | def to_sql(self, url, table_name, *, schema=None, fields=None, fields_to_explode=None, if_exists="fail", dtype=None):
"""
Export items as rows in a PostgreSQL table.
Parameters
----------
url: string
Connection string to connect to the database.
Example:... | python | def to_sql(self, url, table_name, *, schema=None, fields=None, fields_to_explode=None, if_exists="fail", dtype=None):
"""
Export items as rows in a PostgreSQL table.
Parameters
----------
url: string
Connection string to connect to the database.
Example:... | [
"def",
"to_sql",
"(",
"self",
",",
"url",
",",
"table_name",
",",
"*",
",",
"schema",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"fields_to_explode",
"=",
"None",
",",
"if_exists",
"=",
"\"fail\"",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"schem... | Export items as rows in a PostgreSQL table.
Parameters
----------
url: string
Connection string to connect to the database.
Example: "postgresql://postgres@127.0.0.1:5432/testdb"
table_name: string
Name of the database table. Note that if this name ... | [
"Export",
"items",
"as",
"rows",
"in",
"a",
"PostgreSQL",
"table",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L282-L345 |
maxalbert/tohu | tohu/v6/base.py | TohuBaseGenerator.reset | def reset(self, seed):
"""
Reset this generator's seed generator and any clones.
"""
logger.debug(f'Resetting {self} (seed={seed})')
self.seed_generator.reset(seed)
for c in self.clones:
c.reset(seed) | python | def reset(self, seed):
"""
Reset this generator's seed generator and any clones.
"""
logger.debug(f'Resetting {self} (seed={seed})')
self.seed_generator.reset(seed)
for c in self.clones:
c.reset(seed) | [
"def",
"reset",
"(",
"self",
",",
"seed",
")",
":",
"logger",
".",
"debug",
"(",
"f'Resetting {self} (seed={seed})'",
")",
"self",
".",
"seed_generator",
".",
"reset",
"(",
"seed",
")",
"for",
"c",
"in",
"self",
".",
"clones",
":",
"c",
".",
"reset",
"... | Reset this generator's seed generator and any clones. | [
"Reset",
"this",
"generator",
"s",
"seed",
"generator",
"and",
"any",
"clones",
"."
] | train | https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/base.py#L121-L129 |
depop/python-flexisettings | flexisettings/__init__.py | _load_config | def _load_config(initial_namespace=None, defaults=None):
# type: (Optional[str], Optional[str]) -> ConfigLoader
"""
Kwargs:
initial_namespace:
defaults:
"""
# load defaults
if defaults:
config = ConfigLoader()
config.update_from_object(defaults)
namespace = g... | python | def _load_config(initial_namespace=None, defaults=None):
# type: (Optional[str], Optional[str]) -> ConfigLoader
"""
Kwargs:
initial_namespace:
defaults:
"""
# load defaults
if defaults:
config = ConfigLoader()
config.update_from_object(defaults)
namespace = g... | [
"def",
"_load_config",
"(",
"initial_namespace",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"# type: (Optional[str], Optional[str]) -> ConfigLoader",
"# load defaults",
"if",
"defaults",
":",
"config",
"=",
"ConfigLoader",
"(",
")",
"config",
".",
"update_fr... | Kwargs:
initial_namespace:
defaults: | [
"Kwargs",
":",
"initial_namespace",
":",
"defaults",
":"
] | train | https://github.com/depop/python-flexisettings/blob/36d08280ab7c45568fdf206fcdb4cf771d240c6b/flexisettings/__init__.py#L90-L114 |
depop/python-flexisettings | flexisettings/utils.py | override_environment | def override_environment(settings, **kwargs):
# type: (Settings, **str) -> Generator
"""
Override env vars and reload the Settings object
NOTE:
Obviously this context has to be in place before you import any
module which reads env values at import time.
NOTE:
The values in `kwargs` mus... | python | def override_environment(settings, **kwargs):
# type: (Settings, **str) -> Generator
"""
Override env vars and reload the Settings object
NOTE:
Obviously this context has to be in place before you import any
module which reads env values at import time.
NOTE:
The values in `kwargs` mus... | [
"def",
"override_environment",
"(",
"settings",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Settings, **str) -> Generator",
"old_env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"os",
".",
"environ",
".",
"update",
"(",
"kwargs",
")",
"settings",
"."... | Override env vars and reload the Settings object
NOTE:
Obviously this context has to be in place before you import any
module which reads env values at import time.
NOTE:
The values in `kwargs` must be strings else you will get a cryptic:
TypeError: execve() arg 3 contains a non-string va... | [
"Override",
"env",
"vars",
"and",
"reload",
"the",
"Settings",
"object"
] | train | https://github.com/depop/python-flexisettings/blob/36d08280ab7c45568fdf206fcdb4cf771d240c6b/flexisettings/utils.py#L47-L75 |
cloudify-cosmo/repex | repex.py | _import_yaml | def _import_yaml(config_file_path):
"""Return a configuration object
"""
try:
logger.info('Importing config %s...', config_file_path)
with open(config_file_path) as config_file:
return yaml.safe_load(config_file.read())
except IOError as ex:
raise RepexError('{0}: {1}... | python | def _import_yaml(config_file_path):
"""Return a configuration object
"""
try:
logger.info('Importing config %s...', config_file_path)
with open(config_file_path) as config_file:
return yaml.safe_load(config_file.read())
except IOError as ex:
raise RepexError('{0}: {1}... | [
"def",
"_import_yaml",
"(",
"config_file_path",
")",
":",
"try",
":",
"logger",
".",
"info",
"(",
"'Importing config %s...'",
",",
"config_file_path",
")",
"with",
"open",
"(",
"config_file_path",
")",
"as",
"config_file",
":",
"return",
"yaml",
".",
"safe_load"... | Return a configuration object | [
"Return",
"a",
"configuration",
"object"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L72-L83 |
cloudify-cosmo/repex | repex.py | _get_all_files | def _get_all_files(filename_regex,
path,
base_dir,
excluded_paths=None,
excluded_filename_regex=None):
"""Get all files for processing.
This starts iterating from `base_dir` and checks for all files
that look like `filename_regex` ... | python | def _get_all_files(filename_regex,
path,
base_dir,
excluded_paths=None,
excluded_filename_regex=None):
"""Get all files for processing.
This starts iterating from `base_dir` and checks for all files
that look like `filename_regex` ... | [
"def",
"_get_all_files",
"(",
"filename_regex",
",",
"path",
",",
"base_dir",
",",
"excluded_paths",
"=",
"None",
",",
"excluded_filename_regex",
"=",
"None",
")",
":",
"# For windows",
"def",
"replace_backslashes",
"(",
"string",
")",
":",
"return",
"string",
"... | Get all files for processing.
This starts iterating from `base_dir` and checks for all files
that look like `filename_regex` under `path` regex excluding
all paths under the `excluded_paths` list, whether they are files
or folders. `excluded_paths` are explicit paths, not regex.
`excluded_filename_... | [
"Get",
"all",
"files",
"for",
"processing",
"."
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L120-L167 |
cloudify-cosmo/repex | repex.py | _match_tags | def _match_tags(repex_tags, path_tags):
"""Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match.
"""
if 'any' ... | python | def _match_tags(repex_tags, path_tags):
"""Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match.
"""
if 'any' ... | [
"def",
"_match_tags",
"(",
"repex_tags",
",",
"path_tags",
")",
":",
"if",
"'any'",
"in",
"repex_tags",
"or",
"(",
"not",
"repex_tags",
"and",
"not",
"path_tags",
")",
":",
"return",
"True",
"elif",
"set",
"(",
"repex_tags",
")",
"&",
"set",
"(",
"path_t... | Check for matching tags between what the user provided
and the tags set in the config.
If `any` is chosen, match.
If no tags are chosen and none are configured, match.
If the user provided tags match any of the configured tags, match. | [
"Check",
"for",
"matching",
"tags",
"between",
"what",
"the",
"user",
"provided",
"and",
"the",
"tags",
"set",
"in",
"the",
"config",
"."
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L328-L340 |
cloudify-cosmo/repex | repex.py | iterate | def iterate(config_file_path=None,
config=None,
variables=None,
tags=None,
validate=True,
validate_only=False,
with_diff=False):
"""Iterate over all paths in `config_file_path`
:param string config_file_path: a path to a repex config file
... | python | def iterate(config_file_path=None,
config=None,
variables=None,
tags=None,
validate=True,
validate_only=False,
with_diff=False):
"""Iterate over all paths in `config_file_path`
:param string config_file_path: a path to a repex config file
... | [
"def",
"iterate",
"(",
"config_file_path",
"=",
"None",
",",
"config",
"=",
"None",
",",
"variables",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"validate",
"=",
"True",
",",
"validate_only",
"=",
"False",
",",
"with_diff",
"=",
"False",
")",
":",
"# ... | Iterate over all paths in `config_file_path`
:param string config_file_path: a path to a repex config file
:param dict config: a dictionary representing a repex config
:param dict variables: a dict of variables (can be None)
:param list tags: a list of tags to check for
:param bool validate: whethe... | [
"Iterate",
"over",
"all",
"paths",
"in",
"config_file_path"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L343-L378 |
cloudify-cosmo/repex | repex.py | handle_path | def handle_path(pathobj, variables=None, diff=False):
"""Iterate over all chosen files in a path
:param dict pathobj: a dict of a specific path in the config
:param dict variables: a dict of variables (can be None)
"""
logger.info('Handling path with description: %s',
pathobj.get('d... | python | def handle_path(pathobj, variables=None, diff=False):
"""Iterate over all chosen files in a path
:param dict pathobj: a dict of a specific path in the config
:param dict variables: a dict of variables (can be None)
"""
logger.info('Handling path with description: %s',
pathobj.get('d... | [
"def",
"handle_path",
"(",
"pathobj",
",",
"variables",
"=",
"None",
",",
"diff",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'Handling path with description: %s'",
",",
"pathobj",
".",
"get",
"(",
"'description'",
")",
")",
"variables",
"=",
"varia... | Iterate over all chosen files in a path
:param dict pathobj: a dict of a specific path in the config
:param dict variables: a dict of variables (can be None) | [
"Iterate",
"over",
"all",
"chosen",
"files",
"in",
"a",
"path"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L503-L545 |
cloudify-cosmo/repex | repex.py | _build_vars_dict | def _build_vars_dict(vars_file='', variables=None):
"""Merge variables into a single dictionary
Applies to CLI provided variables only
"""
repex_vars = {}
if vars_file:
with open(vars_file) as varsfile:
repex_vars = yaml.safe_load(varsfile.read())
for var in variables:
... | python | def _build_vars_dict(vars_file='', variables=None):
"""Merge variables into a single dictionary
Applies to CLI provided variables only
"""
repex_vars = {}
if vars_file:
with open(vars_file) as varsfile:
repex_vars = yaml.safe_load(varsfile.read())
for var in variables:
... | [
"def",
"_build_vars_dict",
"(",
"vars_file",
"=",
"''",
",",
"variables",
"=",
"None",
")",
":",
"repex_vars",
"=",
"{",
"}",
"if",
"vars_file",
":",
"with",
"open",
"(",
"vars_file",
")",
"as",
"varsfile",
":",
"repex_vars",
"=",
"yaml",
".",
"safe_load... | Merge variables into a single dictionary
Applies to CLI provided variables only | [
"Merge",
"variables",
"into",
"a",
"single",
"dictionary"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L705-L717 |
cloudify-cosmo/repex | repex.py | main | def main(verbose, **kwargs):
"""Replace strings in one or multiple files.
You must either provide `REGEX_PATH` or use the `-c` flag
to provide a valid repex configuration.
`REGEX_PATH` can be: a regex of paths under `basedir`,
a path to a single directory under `basedir`,
or a path to a single... | python | def main(verbose, **kwargs):
"""Replace strings in one or multiple files.
You must either provide `REGEX_PATH` or use the `-c` flag
to provide a valid repex configuration.
`REGEX_PATH` can be: a regex of paths under `basedir`,
a path to a single directory under `basedir`,
or a path to a single... | [
"def",
"main",
"(",
"verbose",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"kwargs",
"[",
"'config'",
"]",
"if",
"not",
"config",
"and",
"not",
"kwargs",
"[",
"'regex_path'",
"]",
":",
"click",
".",
"echo",
"(",
"'Must either provide a path or a viab... | Replace strings in one or multiple files.
You must either provide `REGEX_PATH` or use the `-c` flag
to provide a valid repex configuration.
`REGEX_PATH` can be: a regex of paths under `basedir`,
a path to a single directory under `basedir`,
or a path to a single file.
It's important to note t... | [
"Replace",
"strings",
"in",
"one",
"or",
"multiple",
"files",
"."
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L859-L898 |
cloudify-cosmo/repex | repex.py | _VariablesHandler.expand | def expand(self, repex_vars, fields):
r"""Receive a dict of variables and a dict of fields
and iterates through them to expand a variable in an field, then
returns the fields dict with its variables expanded.
This will fail if not all variables expand (due to not providing
all n... | python | def expand(self, repex_vars, fields):
r"""Receive a dict of variables and a dict of fields
and iterates through them to expand a variable in an field, then
returns the fields dict with its variables expanded.
This will fail if not all variables expand (due to not providing
all n... | [
"def",
"expand",
"(",
"self",
",",
"repex_vars",
",",
"fields",
")",
":",
"logger",
".",
"debug",
"(",
"'Expanding variables...'",
")",
"unexpanded_instances",
"=",
"set",
"(",
")",
"# Expand variables in variables",
"# TODO: This should be done in the global scope.",
"... | r"""Receive a dict of variables and a dict of fields
and iterates through them to expand a variable in an field, then
returns the fields dict with its variables expanded.
This will fail if not all variables expand (due to not providing
all necessary ones).
fields:
type... | [
"r",
"Receive",
"a",
"dict",
"of",
"variables",
"and",
"a",
"dict",
"of",
"fields",
"and",
"iterates",
"through",
"them",
"to",
"expand",
"a",
"variable",
"in",
"an",
"field",
"then",
"returns",
"the",
"fields",
"dict",
"with",
"its",
"variables",
"expande... | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L217-L293 |
cloudify-cosmo/repex | repex.py | _VariablesHandler._expand_var | def _expand_var(self, in_string, available_variables):
"""Expand variable to its corresponding value in_string
:param string variable: variable name
:param value: value to replace with
:param string in_string: the string to replace in
"""
instances = self._get_instances(... | python | def _expand_var(self, in_string, available_variables):
"""Expand variable to its corresponding value in_string
:param string variable: variable name
:param value: value to replace with
:param string in_string: the string to replace in
"""
instances = self._get_instances(... | [
"def",
"_expand_var",
"(",
"self",
",",
"in_string",
",",
"available_variables",
")",
":",
"instances",
"=",
"self",
".",
"_get_instances",
"(",
"in_string",
")",
"for",
"instance",
"in",
"instances",
":",
"for",
"name",
",",
"value",
"in",
"available_variable... | Expand variable to its corresponding value in_string
:param string variable: variable name
:param value: value to replace with
:param string in_string: the string to replace in | [
"Expand",
"variable",
"to",
"its",
"corresponding",
"value",
"in_string"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L302-L315 |
cloudify-cosmo/repex | repex.py | Repex.validate_before | def validate_before(self, content, file_to_handle):
"""Verify that all required strings are in the file
"""
logger.debug('Looking for required strings: %s', self.must_include)
included = True
for string in self.must_include:
if not re.search(r'{0}'.format(string), con... | python | def validate_before(self, content, file_to_handle):
"""Verify that all required strings are in the file
"""
logger.debug('Looking for required strings: %s', self.must_include)
included = True
for string in self.must_include:
if not re.search(r'{0}'.format(string), con... | [
"def",
"validate_before",
"(",
"self",
",",
"content",
",",
"file_to_handle",
")",
":",
"logger",
".",
"debug",
"(",
"'Looking for required strings: %s'",
",",
"self",
".",
"must_include",
")",
"included",
"=",
"True",
"for",
"string",
"in",
"self",
".",
"must... | Verify that all required strings are in the file | [
"Verify",
"that",
"all",
"required",
"strings",
"are",
"in",
"the",
"file"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L589-L603 |
cloudify-cosmo/repex | repex.py | Repex.find_matches | def find_matches(self, content, file_to_handle):
"""Find all matches of an expression in a file
"""
# look for all match groups in the content
groups = [match.groupdict() for match in
self.match_expression.finditer(content)]
# filter out content not in the match... | python | def find_matches(self, content, file_to_handle):
"""Find all matches of an expression in a file
"""
# look for all match groups in the content
groups = [match.groupdict() for match in
self.match_expression.finditer(content)]
# filter out content not in the match... | [
"def",
"find_matches",
"(",
"self",
",",
"content",
",",
"file_to_handle",
")",
":",
"# look for all match groups in the content",
"groups",
"=",
"[",
"match",
".",
"groupdict",
"(",
")",
"for",
"match",
"in",
"self",
".",
"match_expression",
".",
"finditer",
"(... | Find all matches of an expression in a file | [
"Find",
"all",
"matches",
"of",
"an",
"expression",
"in",
"a",
"file"
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L605-L618 |
cloudify-cosmo/repex | repex.py | Repex.replace | def replace(self, match, content):
"""Replace all occurences of the regex in all matches
from a file with a specific value.
"""
new_string = self.replace_expression.sub(self.replace_with, match)
logger.info('Replacing: [ %s ] --> [ %s ]', match, new_string)
new_content = ... | python | def replace(self, match, content):
"""Replace all occurences of the regex in all matches
from a file with a specific value.
"""
new_string = self.replace_expression.sub(self.replace_with, match)
logger.info('Replacing: [ %s ] --> [ %s ]', match, new_string)
new_content = ... | [
"def",
"replace",
"(",
"self",
",",
"match",
",",
"content",
")",
":",
"new_string",
"=",
"self",
".",
"replace_expression",
".",
"sub",
"(",
"self",
".",
"replace_with",
",",
"match",
")",
"logger",
".",
"info",
"(",
"'Replacing: [ %s ] --> [ %s ]'",
",",
... | Replace all occurences of the regex in all matches
from a file with a specific value. | [
"Replace",
"all",
"occurences",
"of",
"the",
"regex",
"in",
"all",
"matches",
"from",
"a",
"file",
"with",
"a",
"specific",
"value",
"."
] | train | https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L623-L630 |
idlesign/uwsgiconf | uwsgiconf/options/master_process.py | MasterProcess.set_exit_events | def set_exit_events(self, no_workers=None, idle=None, reload=None, sig_term=None):
"""Do exit on certain events
:param bool no_workers: Shutdown uWSGI when no workers are running.
:param bool idle: Shutdown uWSGI when idle.
:param bool reload: Force exit even if a reload is requested.... | python | def set_exit_events(self, no_workers=None, idle=None, reload=None, sig_term=None):
"""Do exit on certain events
:param bool no_workers: Shutdown uWSGI when no workers are running.
:param bool idle: Shutdown uWSGI when idle.
:param bool reload: Force exit even if a reload is requested.... | [
"def",
"set_exit_events",
"(",
"self",
",",
"no_workers",
"=",
"None",
",",
"idle",
"=",
"None",
",",
"reload",
"=",
"None",
",",
"sig_term",
"=",
"None",
")",
":",
"self",
".",
"_set",
"(",
"'die-on-no-workers'",
",",
"no_workers",
",",
"cast",
"=",
"... | Do exit on certain events
:param bool no_workers: Shutdown uWSGI when no workers are running.
:param bool idle: Shutdown uWSGI when idle.
:param bool reload: Force exit even if a reload is requested.
:param bool sig_term: Exit on SIGTERM instead of brutal workers reload.
... | [
"Do",
"exit",
"on",
"certain",
"events"
] | train | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/master_process.py#L59-L78 |
idlesign/uwsgiconf | uwsgiconf/options/master_process.py | MasterProcess.set_exception_handling_params | def set_exception_handling_params(self, handler=None, catch=None, no_write_exception=None):
"""Exception handling related params.
:param str|unicode|list[str|unicode] handler: Register one or more exception handling C-functions.
:param bool catch: Catch exceptions and report them as http outpu... | python | def set_exception_handling_params(self, handler=None, catch=None, no_write_exception=None):
"""Exception handling related params.
:param str|unicode|list[str|unicode] handler: Register one or more exception handling C-functions.
:param bool catch: Catch exceptions and report them as http outpu... | [
"def",
"set_exception_handling_params",
"(",
"self",
",",
"handler",
"=",
"None",
",",
"catch",
"=",
"None",
",",
"no_write_exception",
"=",
"None",
")",
":",
"self",
".",
"_set",
"(",
"'exception-handler'",
",",
"handler",
",",
"multi",
"=",
"True",
")",
... | Exception handling related params.
:param str|unicode|list[str|unicode] handler: Register one or more exception handling C-functions.
:param bool catch: Catch exceptions and report them as http output (including stack trace and env params).
.. warning:: Use only for testing purposes.
... | [
"Exception",
"handling",
"related",
"params",
"."
] | train | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/master_process.py#L80-L100 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.