repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
ASMfreaK/habitipy
habitipy/api.py
download_api
def download_api(branch=None) -> str: """download API documentation from _branch_ of Habitica\'s repo on Github""" habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica' if not branch: branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name'] curl = local...
python
def download_api(branch=None) -> str: """download API documentation from _branch_ of Habitica\'s repo on Github""" habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica' if not branch: branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name'] curl = local...
[ "def", "download_api", "(", "branch", "=", "None", ")", "->", "str", ":", "habitica_github_api", "=", "'https://api.github.com/repos/HabitRPG/habitica'", "if", "not", "branch", ":", "branch", "=", "requests", ".", "get", "(", "habitica_github_api", "+", "'/releases/...
download API documentation from _branch_ of Habitica\'s repo on Github
[ "download", "API", "documentation", "from", "_branch_", "of", "Habitica", "\\", "s", "repo", "on", "Github" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L287-L297
train
download API documentation from Habitica s repo on Github
ASMfreaK/habitipy
habitipy/api.py
save_apidoc
def save_apidoc(text: str) -> None: """save `text` to apidoc cache""" apidoc_local = local.path(APIDOC_LOCAL_FILE) if not apidoc_local.dirname.exists(): apidoc_local.dirname.mkdir() with open(apidoc_local, 'w') as f: f.write(text)
python
def save_apidoc(text: str) -> None: """save `text` to apidoc cache""" apidoc_local = local.path(APIDOC_LOCAL_FILE) if not apidoc_local.dirname.exists(): apidoc_local.dirname.mkdir() with open(apidoc_local, 'w') as f: f.write(text)
[ "def", "save_apidoc", "(", "text", ":", "str", ")", "->", "None", ":", "apidoc_local", "=", "local", ".", "path", "(", "APIDOC_LOCAL_FILE", ")", "if", "not", "apidoc_local", ".", "dirname", ".", "exists", "(", ")", ":", "apidoc_local", ".", "dirname", "....
save `text` to apidoc cache
[ "save", "text", "to", "apidoc", "cache" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L300-L306
train
save text to apidoc cache
ASMfreaK/habitipy
habitipy/api.py
parse_apidoc
def parse_apidoc( file_or_branch, from_github=False, save_github_version=True ) -> List['ApiEndpoint']: """read file and parse apiDoc lines""" apis = [] # type: List[ApiEndpoint] regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *' regex += r'(?P<field>[^ ]*) *(?P<description>.*)...
python
def parse_apidoc( file_or_branch, from_github=False, save_github_version=True ) -> List['ApiEndpoint']: """read file and parse apiDoc lines""" apis = [] # type: List[ApiEndpoint] regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *' regex += r'(?P<field>[^ ]*) *(?P<description>.*)...
[ "def", "parse_apidoc", "(", "file_or_branch", ",", "from_github", "=", "False", ",", "save_github_version", "=", "True", ")", "->", "List", "[", "'ApiEndpoint'", "]", ":", "apis", "=", "[", "]", "# type: List[ApiEndpoint]", "regex", "=", "r'(?P<group>\\([^)]*\\)){...
read file and parse apiDoc lines
[ "read", "file", "and", "parse", "apiDoc", "lines" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L309-L353
train
read file and parse apiDoc lines
ASMfreaK/habitipy
habitipy/api.py
ApiNode.into
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
python
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
[ "def", "into", "(", "self", ",", "val", ":", "str", ")", "->", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ":", "if", "val", "in", "self", ".", "paths", ":", "return", "self", ".", "paths", "[", "val", "]", "if", "self", ".", "param", "...
Get another leaf node with name `val` if possible
[ "Get", "another", "leaf", "node", "with", "name", "val", "if", "possible" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L52-L58
train
Get another leaf node with name val if possible
ASMfreaK/habitipy
habitipy/api.py
ApiNode.can_into
def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
python
def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
[ "def", "can_into", "(", "self", ",", "val", ":", "str", ")", "->", "bool", ":", "return", "val", "in", "self", ".", "paths", "or", "(", "self", ".", "param", "and", "self", ".", "param_name", "==", "val", ")" ]
Determine if there is a leaf node with name `val`
[ "Determine", "if", "there", "is", "a", "leaf", "node", "with", "name", "val" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L60-L62
train
Determine if the node with name val can be inserted into this node.
ASMfreaK/habitipy
habitipy/api.py
ApiNode.place
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
python
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
[ "def", "place", "(", "self", ",", "part", ":", "str", ",", "val", ":", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ")", ":", "if", "part", ".", "startswith", "(", "':'", ")", ":", "if", "self", ".", "param", "and", "self", ".", "param", ...
place a leaf node
[ "place", "a", "leaf", "node" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L64-L74
train
place a leaf node
ASMfreaK/habitipy
habitipy/api.py
ApiNode.keys
def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
python
def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
[ "def", "keys", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "if", "self", ".", "param", ":", "yield", "self", ".", "param_name", "yield", "from", "self", ".", "paths", ".", "keys", "(", ")" ]
return all possible paths one can take from this ApiNode
[ "return", "all", "possible", "paths", "one", "can", "take", "from", "this", "ApiNode" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L76-L80
train
return all possible paths one can take from this ApiNode
ASMfreaK/habitipy
habitipy/api.py
ApiEndpoint.add_param
def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p
python
def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p
[ "def", "add_param", "(", "self", ",", "group", "=", "None", ",", "type_", "=", "''", ",", "field", "=", "''", ",", "description", "=", "''", ")", ":", "group", "=", "group", "or", "'(Parameter)'", "group", "=", "group", ".", "lower", "(", ")", "[",...
parse and append a param
[ "parse", "and", "append", "a", "param" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L368-L373
train
parse and append a param
ASMfreaK/habitipy
habitipy/api.py
ApiEndpoint.add_success
def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more re...
python
def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more re...
[ "def", "add_success", "(", "self", ",", "group", "=", "None", ",", "type_", "=", "''", ",", "field", "=", "''", ",", "description", "=", "''", ")", ":", "group", "=", "group", "or", "'(200)'", "group", "=", "int", "(", "group", ".", "lower", "(", ...
parse and append a success data param
[ "parse", "and", "append", "a", "success", "data", "param" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L375-L384
train
parse and append a success data param
ASMfreaK/habitipy
habitipy/api.py
ApiEndpoint.render_docstring
def render_docstring(self): """make a nice docstring for ipython""" res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for param in params.v...
python
def render_docstring(self): """make a nice docstring for ipython""" res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for param in params.v...
[ "def", "render_docstring", "(", "self", ")", ":", "res", "=", "'{{{self.method}}} {self.uri} {self.title}\\n'", ".", "format", "(", "self", "=", "self", ")", "if", "self", ".", "params", ":", "for", "group", ",", "params", "in", "self", ".", "params", ".", ...
make a nice docstring for ipython
[ "make", "a", "nice", "docstring", "for", "ipython" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L389-L397
train
make a nice docstring for ipython
ASMfreaK/habitipy
habitipy/api.py
Param.validate
def validate(self, obj): """check if obj has this api param""" if self.path: for i in self.path: obj = obj[i] obj = obj[self.field] raise NotImplementedError('Validation is not implemented yet')
python
def validate(self, obj): """check if obj has this api param""" if self.path: for i in self.path: obj = obj[i] obj = obj[self.field] raise NotImplementedError('Validation is not implemented yet')
[ "def", "validate", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "path", ":", "for", "i", "in", "self", ".", "path", ":", "obj", "=", "obj", "[", "i", "]", "obj", "=", "obj", "[", "self", ".", "field", "]", "raise", "NotImplementedError",...
check if obj has this api param
[ "check", "if", "obj", "has", "this", "api", "param" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L439-L446
train
check if obj has this api param
ASMfreaK/habitipy
habitipy/api.py
Param.render_docstring
def render_docstring(self): """make a nice docstring for ipython""" default = (' = ' + str(self.default)) if self.default else '' opt = 'optional' if self.is_optional else '' can_be = ' '.join(self.possible_values) if self.possible_values else '' can_be = 'one of [{}]'.format(can...
python
def render_docstring(self): """make a nice docstring for ipython""" default = (' = ' + str(self.default)) if self.default else '' opt = 'optional' if self.is_optional else '' can_be = ' '.join(self.possible_values) if self.possible_values else '' can_be = 'one of [{}]'.format(can...
[ "def", "render_docstring", "(", "self", ")", ":", "default", "=", "(", "' = '", "+", "str", "(", "self", ".", "default", ")", ")", "if", "self", ".", "default", "else", "''", "opt", "=", "'optional'", "if", "self", ".", "is_optional", "else", "''", "...
make a nice docstring for ipython
[ "make", "a", "nice", "docstring", "for", "ipython" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L448-L456
train
make a nice docstring for ipython
ASMfreaK/habitipy
habitipy/cli.py
is_uuid
def is_uuid(u): """validator for plumbum prompt""" if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex: return u return False
python
def is_uuid(u): """validator for plumbum prompt""" if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex: return u return False
[ "def", "is_uuid", "(", "u", ")", ":", "if", "isinstance", "(", "u", ",", "str", ")", "and", "u", ".", "replace", "(", "'-'", ",", "''", ")", "==", "uuid", ".", "UUID", "(", "u", ")", ".", "hex", ":", "return", "u", "return", "False" ]
validator for plumbum prompt
[ "validator", "for", "plumbum", "prompt" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L48-L52
train
validator for plumbum prompt
ASMfreaK/habitipy
habitipy/cli.py
load_conf
def load_conf(configfile, config=None): """Get authentication data from the AUTH_CONF file.""" default_login = 'your-login-for-api-here' default_password = 'your-password-for-api-here' config = config or {} configfile = local.path(configfile) if not configfile.exists(): configfile.dirnam...
python
def load_conf(configfile, config=None): """Get authentication data from the AUTH_CONF file.""" default_login = 'your-login-for-api-here' default_password = 'your-password-for-api-here' config = config or {} configfile = local.path(configfile) if not configfile.exists(): configfile.dirnam...
[ "def", "load_conf", "(", "configfile", ",", "config", "=", "None", ")", ":", "default_login", "=", "'your-login-for-api-here'", "default_password", "=", "'your-password-for-api-here'", "config", "=", "config", "or", "{", "}", "configfile", "=", "local", ".", "path...
Get authentication data from the AUTH_CONF file.
[ "Get", "authentication", "data", "from", "the", "AUTH_CONF", "file", "." ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L55-L97
train
Load the AUTH_CONF file and return the config dict.
ASMfreaK/habitipy
habitipy/cli.py
get_content
def get_content(api, rebuild_cache=False): """get content from server or cache""" if hasattr(get_content, 'cache') and not rebuild_cache: return get_content.cache if not os.path.exists(CONTENT_JSON) or rebuild_cache: import locale content_endpoint = api.content.get # pylint: ...
python
def get_content(api, rebuild_cache=False): """get content from server or cache""" if hasattr(get_content, 'cache') and not rebuild_cache: return get_content.cache if not os.path.exists(CONTENT_JSON) or rebuild_cache: import locale content_endpoint = api.content.get # pylint: ...
[ "def", "get_content", "(", "api", ",", "rebuild_cache", "=", "False", ")", ":", "if", "hasattr", "(", "get_content", ",", "'cache'", ")", "and", "not", "rebuild_cache", ":", "return", "get_content", ".", "cache", "if", "not", "os", ".", "path", ".", "exi...
get content from server or cache
[ "get", "content", "from", "server", "or", "cache" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L126-L164
train
get content from server or cache
ASMfreaK/habitipy
habitipy/cli.py
get_additional_rewards
def get_additional_rewards(api): """returns list of non-user rewards (potion, armoire, gear)""" c = get_content(api) tasks = [c[i] for i in ['potion', 'armoire']] tasks.extend(api.user.inventory.buy.get()) for task in tasks: task['id'] = task['alias'] = task['key'] return tasks
python
def get_additional_rewards(api): """returns list of non-user rewards (potion, armoire, gear)""" c = get_content(api) tasks = [c[i] for i in ['potion', 'armoire']] tasks.extend(api.user.inventory.buy.get()) for task in tasks: task['id'] = task['alias'] = task['key'] return tasks
[ "def", "get_additional_rewards", "(", "api", ")", ":", "c", "=", "get_content", "(", "api", ")", "tasks", "=", "[", "c", "[", "i", "]", "for", "i", "in", "[", "'potion'", ",", "'armoire'", "]", "]", "tasks", ".", "extend", "(", "api", ".", "user", ...
returns list of non-user rewards (potion, armoire, gear)
[ "returns", "list", "of", "non", "-", "user", "rewards", "(", "potion", "armoire", "gear", ")" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L365-L372
train
returns list of non - user rewards
ASMfreaK/habitipy
habitipy/cli.py
ScoreInfo.color
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
python
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
[ "def", "color", "(", "cls", ",", "value", ")", ":", "index", "=", "bisect", "(", "cls", ".", "breakpoints", ",", "value", ")", "return", "colors", ".", "fg", "(", "cls", ".", "colors_", "[", "index", "]", ")" ]
task value/score color
[ "task", "value", "/", "score", "color" ]
555b8b20faf6d553353092614a8a0d612f0adbde
https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/cli.py#L289-L292
train
task value color
maxalbert/tohu
tohu/v6/custom_generator/custom_generator.py
augment_init_method
def augment_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): super(CustomGenerator, self).__init__() # TODO: does this ...
python
def augment_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): super(CustomGenerator, self).__init__() # TODO: does this ...
[ "def", "augment_init_method", "(", "cls", ")", ":", "orig_init", "=", "cls", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "CustomGenerator", ",", "self", ")", ".", "__init__", "(", ...
Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping.
[ "Replace", "the", "existing", "cls", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "also", "initialises", "the", "field", "generators", "and", "similar", "bookkeeping", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/custom_generator.py#L9-L39
train
Augment the existing cls. __init__ method with a new one which also initialises the field generators and similar bookkeeping.
maxalbert/tohu
tohu/v2/custom_generator.py
find_field_generators
def find_field_generators(obj): """ Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces. """ cls_dict = obj.__class__.__dict__ obj_dict = obj.__dict__ #debug_print_dict(cls_dict, 'cls_dict') #debug_prin...
python
def find_field_generators(obj): """ Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces. """ cls_dict = obj.__class__.__dict__ obj_dict = obj.__dict__ #debug_print_dict(cls_dict, 'cls_dict') #debug_prin...
[ "def", "find_field_generators", "(", "obj", ")", ":", "cls_dict", "=", "obj", ".", "__class__", ".", "__dict__", "obj_dict", "=", "obj", ".", "__dict__", "#debug_print_dict(cls_dict, 'cls_dict')", "#debug_print_dict(obj_dict, 'obj_dict')", "field_gens", "=", "{", "}", ...
Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces.
[ "Return", "dictionary", "with", "the", "names", "and", "instances", "of", "all", "tohu", ".", "BaseGenerator", "occurring", "in", "the", "given", "object", "s", "class", "&", "instance", "namespaces", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L20-L36
train
Find all tohu. BaseGenerator occurring in the given object s class & instance namespaces.
maxalbert/tohu
tohu/v2/custom_generator.py
set_item_class_name
def set_item_class_name(cls_obj): """ Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux """ if '__tohu__items__name__' in...
python
def set_item_class_name(cls_obj): """ Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux """ if '__tohu__items__name__' in...
[ "def", "set_item_class_name", "(", "cls_obj", ")", ":", "if", "'__tohu__items__name__'", "in", "cls_obj", ".", "__dict__", ":", "logger", ".", "debug", "(", "f\"Using item class name '{cls_obj.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')\"", ")", "else",...
Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux
[ "Return", "the", "first", "part", "of", "the", "class", "name", "of", "this", "custom", "generator", ".", "This", "will", "be", "used", "for", "the", "class", "name", "of", "the", "items", "produced", "by", "this", "generator", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L39-L59
train
Set the class name of the items produced by this custom generator.
maxalbert/tohu
tohu/v2/custom_generator.py
make_item_class_for_custom_generator
def make_item_class_for_custom_generator(obj): """ obj: The custom generator instance for which to create an item class """ clsname = obj.__tohu_items_name__ attr_names = obj.field_gens.keys() return make_item_class(clsname, attr_names)
python
def make_item_class_for_custom_generator(obj): """ obj: The custom generator instance for which to create an item class """ clsname = obj.__tohu_items_name__ attr_names = obj.field_gens.keys() return make_item_class(clsname, attr_names)
[ "def", "make_item_class_for_custom_generator", "(", "obj", ")", ":", "clsname", "=", "obj", ".", "__tohu_items_name__", "attr_names", "=", "obj", ".", "field_gens", ".", "keys", "(", ")", "return", "make_item_class", "(", "clsname", ",", "attr_names", ")" ]
obj: The custom generator instance for which to create an item class
[ "obj", ":", "The", "custom", "generator", "instance", "for", "which", "to", "create", "an", "item", "class" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L108-L115
train
Returns the class name for the item class for the given custom generator instance.
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_init_method
def add_new_init_method(obj): """ Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. ...
python
def add_new_init_method(obj): """ Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. ...
[ "def", "add_new_init_method", "(", "obj", ")", ":", "orig_init", "=", "obj", ".", "__init__", "def", "new_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "f\"Initialising new {self}\"", ")", "# Call ori...
Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. (2) ..to do..
[ "Replace", "the", "existing", "obj", ".", "__init__", "()", "method", "with", "a", "new", "one", "which", "calls", "the", "original", "one", "and", "in", "addition", "performs", "the", "following", "actions", ":" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L118-L192
train
Add a new init method to obj.
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_reset_method
def add_new_reset_method(obj): """ Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`. """ # # Create and assign automatically generated reset() method # def ne...
python
def add_new_reset_method(obj): """ Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`. """ # # Create and assign automatically generated reset() method # def ne...
[ "def", "add_new_reset_method", "(", "obj", ")", ":", "#", "# Create and assign automatically generated reset() method", "#", "def", "new_reset", "(", "self", ",", "seed", "=", "None", ")", ":", "logger", ".", "debug", "(", "f'[EEE] Inside automatically generated reset()...
Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`.
[ "Attach", "a", "new", "reset", "()", "method", "to", "obj", "which", "resets", "the", "internal", "seed", "generator", "of", "obj", "and", "then", "resets", "each", "of", "its", "constituent", "field", "generators", "found", "in", "obj", ".", "field_gens", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L195-L225
train
Add a new reset method to obj which resets the internal internal
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_next_method
def add_new_next_method(obj): """ TODO """ def new_next(self): field_values = [next(g) for g in self.field_gens.values()] return self.item_cls(*field_values) obj.__next__ = new_next
python
def add_new_next_method(obj): """ TODO """ def new_next(self): field_values = [next(g) for g in self.field_gens.values()] return self.item_cls(*field_values) obj.__next__ = new_next
[ "def", "add_new_next_method", "(", "obj", ")", ":", "def", "new_next", "(", "self", ")", ":", "field_values", "=", "[", "next", "(", "g", ")", "for", "g", "in", "self", ".", "field_gens", ".", "values", "(", ")", "]", "return", "self", ".", "item_cls...
TODO
[ "TODO" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L228-L237
train
Add a method to obj that returns the next item in the hierarchy.
maxalbert/tohu
tohu/v2/custom_generator.py
add_new_spawn_method
def add_new_spawn_method(obj): """ TODO """ def new_spawn(self): # TODO/FIXME: Check that this does the right thing: # (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour) # (ii) ensure that it...
python
def add_new_spawn_method(obj): """ TODO """ def new_spawn(self): # TODO/FIXME: Check that this does the right thing: # (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour) # (ii) ensure that it...
[ "def", "add_new_spawn_method", "(", "obj", ")", ":", "def", "new_spawn", "(", "self", ")", ":", "# TODO/FIXME: Check that this does the right thing:", "# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviou...
TODO
[ "TODO" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L240-L252
train
Add a new spawn method to the object.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/set_special_methods.py#L16-L28
train
Helper function to check that the operator op can be applied to items produced by g1 and g2.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L113-L125
train
Add a new init method to the class.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L128-L137
train
Add default __repr__ method in case no user - defined one is present.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L141-L155
train
Add a new reset method to the class which also replaces existing cls. reset method with a new one which also adds a new reset method which also adds a new reset method to any clones.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base.py#L34-L50
train
Generate a sequence of N elements from the current generator.
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", "...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/base_NEW.py#L122-L130
train
Return the tohu id of the current object.
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" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/custom_generator.py#L130-L136
train
Sets the item class for which to generate the item.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/custom_generator.py#L142-L160
train
Find all tohu generators defined in the class and instance namespace and return a dictionary of the form {name : field_generator containing all tohu generators defined in the class and instance namespace .
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L14-L29
train
Helper function to generate a CSV header line depending on the combination of arguments provided.
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", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L32-L49
train
Extract schema and table from a given table name.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L101-L130
train
Export items as rows in a pandas dataframe table.
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...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/item_list.py#L132-L206
train
Exports the current state of the object to a CSV file.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L30-L39
train
Return a fresh spawn of g unless g is already there.
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", ".", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L171-L189
train
Spawn a new generator which behaves the same way as this one.
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...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v5/base.py#L195-L204
train
Return an exact copy of this generator which behaves the same way returns the same copy and which is the same elements in the same order as the original generator.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/derived_generators.py#L40-L48
train
Iterate over all generators in the context.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/generators.py#L956-L975
train
Splits a generator into individual generators.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/generators.py#L48-L55
train
Returns the length of the tuple produced by this generator.
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", "." ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L71-L82
train
Return all valid and active faults ordered by ID.
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", "." ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L94-L111
train
Return all valid and active sentences ordered by ID.
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"...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L185-L229
train
Retrieve a randomly - generated error message as a unicode string.
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", ...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L237-L282
train
Retrieves a randomly - generated sentence from the database table.
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", "..." ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L327-L364
train
Let s fetch a random sentence that we then need to substitute bits of...
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L367-L392
train
Let s fetch a VERB by random number
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...
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L478-L518
train
This function takes a count of each of the database tables so we know our max_adjectives max_names max_nouns max_sentences max_faults max_verbs and max_verb to the calling function...
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L521-L559
train
process a single sentence from the tuple
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L562-L576
train
Lets find and replace all instances of verbs with the same value
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L579-L594
train
Lets find and replace all instances of NOUN with the corresponding number
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L597-L619
train
Lets find and replace all instances of ADJECTIVE_MAYBE and ADJECTIVE_MAYBE with the appropriate value.
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L622-L638
train
Lets find and replace all instances of ADJECTIVE and get the correct ID
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L641-L656
train
Lets find and replace all instances of NAME with the corresponding names.
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", "." ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L659-L683
train
Lets find and replace all instances of an in the next A sequence.
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", ":" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L686-L716
train
Lets find and replace all instances of RANDOM with a random one.
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", "." ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L719-L760
train
Replaces repeating random elements in a word sentence.
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", ".", "############" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L763-L790
train
This function replaces all instances of the uppercase and cap the next word in the sentence.
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?" ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L793-L811
train
replace all CAPALL with uppercase
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", "." ]
7fdd2eae534410df16ee1f9d7e9bb77aa10decab
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L814-L841
train
This function checks if the number of spaces in the sentence is correct.
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", "()", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L48-L54
train
Internal helper function used by explode_columns().
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L57-L97
train
Given a dataframe with certain columns that contain lists return another dataframe where the elements in each list are "exploded" into individual rows.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L100-L110
train
Helper function which prints a sequence of num items produced by the random generator gen.
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", ")", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L113-L128
train
Helper function to create a list of namedtuples which are useful for testing and debugging.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/utils.py#L148-L175
train
Ensures input represents a valid date and return the corresponding datetime. date object.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/tohu_namespace.py#L60-L64
train
Return all generators in this namespace which are not clones.
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" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/utils.py#L11-L54
train
Creates a new class which can be used to create a tohu items class.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/custom_generator/utils.py#L57-L92
train
Returns a string which defines the name of the class which will be used by the custom generator.
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", "...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/primitive_generators.py#L511-L532
train
Initializes the random generator to be used for picking elements from the input sequence.
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...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/primitive_generators.py#L534-L548
train
Transfer the internal state from other to self.
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", "...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v4/primitive_generators.py#L589-L610
train
Initializes the random generator to be used for picking elements from the input sequence.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L22-L29
train
Helper function which updates the dict field_gens with any items in the dict adict that are instances of TohuUltraBaseGenerator.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L32-L48
train
Find all tohu. BaseGenerator templates occurring in the given object.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L51-L80
train
Set the class name of the items to be produced by the custom generator class.
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" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L129-L136
train
Returns the class that is used to create the item class for the given custom generator class.
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", ":" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L139-L192
train
Add a new init method to the class.
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" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L195-L204
train
Add a new next method to the class.
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", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L207-L237
train
Add a new reset method to cls which resets the internal internal
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" ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator_NEW.py#L240-L259
train
Add a new spawn method to the class.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/derived_generators.py#L20-L35
train
Reset all input generators to the derived generator.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/derived_generators.py#L201-L210
train
Helper function to spot - check that the items produces by this generator have the attribute name.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L104-L180
train
Export items as rows in a pandas dataframe table.
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", "=", ...
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L182-L280
train
Exports the current state of the entry to a CSV file.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/item_list.py#L282-L345
train
Export items in a PostgreSQL table.
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", "." ]
43380162fadec99cdd5c5c3152dd6b7d3a9d39a8
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/base.py#L121-L129
train
Reset this generator s seed generator and any clones.
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", ":" ]
36d08280ab7c45568fdf206fcdb4cf771d240c6b
https://github.com/depop/python-flexisettings/blob/36d08280ab7c45568fdf206fcdb4cf771d240c6b/flexisettings/__init__.py#L90-L114
train
Load the config from the object.
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" ]
36d08280ab7c45568fdf206fcdb4cf771d240c6b
https://github.com/depop/python-flexisettings/blob/36d08280ab7c45568fdf206fcdb4cf771d240c6b/flexisettings/utils.py#L47-L75
train
Override environment vars and reload the Settings object
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L72-L83
train
Imports a YAML file into a configuration object
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", "." ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L120-L167
train
Get all files under base_dir that match filename_regex.
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", "." ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L328-L340
train
Check if the user provided tags match the tags set in the config.
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L343-L378
train
Iterate over all paths in config_file_path and process each.
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L503-L545
train
Handles a path in a single or multiple files in a single archive.
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L705-L717
train
Build a dictionary of variables that can be used to create a new node.
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", "." ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L859-L898
train
This function is used to run the repex command line interface.
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...
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L217-L293
train
This function expands a variable in a file and returns a dict with the expanded variables.
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L302-L315
train
Expand variable to its corresponding value in_string
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L589-L603
train
Verify that all required strings are in the file_to_handle and that all required strings are in the file_to_handle.
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" ]
589e442857fa4a99fa88670d7df1a72f983bbd28
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L605-L618
train
Find all matches of an expression in a file