sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
Get another leaf node with name `val` if possible
entailment
def can_into(self, val: str) -> bool: """Determine if there is a leaf node with name `val`""" return val in self.paths or (self.param and self.param_name == val)
Determine if there is a leaf node with name `val`
entailment
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
place a leaf node
entailment
def keys(self) -> Iterator[str]: """return all possible paths one can take from this ApiNode""" if self.param: yield self.param_name yield from self.paths.keys()
return all possible paths one can take from this ApiNode
entailment
def add_param(self, group=None, type_='', field='', description=''): """parse and append a param""" group = group or '(Parameter)' group = group.lower()[1:-1] p = Param(type_, field, description) self.params[group][p.field] = p
parse and append a param
entailment
def add_success(self, group=None, type_='', field='', description=''): """parse and append a success data param""" group = group or '(200)' group = int(group.lower()[1:-1]) self.retcode = self.retcode or group if group != self.retcode: raise ValueError('Two or more re...
parse and append a success data param
entailment
def render_docstring(self): """make a nice docstring for ipython""" res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self) if self.params: for group, params in self.params.items(): res += '\n' + group + ' params:\n' for param in params.v...
make a nice docstring for ipython
entailment
def validate(self, obj): """check if obj has this api param""" if self.path: for i in self.path: obj = obj[i] obj = obj[self.field] raise NotImplementedError('Validation is not implemented yet')
check if obj has this api param
entailment
def render_docstring(self): """make a nice docstring for ipython""" default = (' = ' + str(self.default)) if self.default else '' opt = 'optional' if self.is_optional else '' can_be = ' '.join(self.possible_values) if self.possible_values else '' can_be = 'one of [{}]'.format(can...
make a nice docstring for ipython
entailment
def is_uuid(u): """validator for plumbum prompt""" if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex: return u return False
validator for plumbum prompt
entailment
def load_conf(configfile, config=None): """Get authentication data from the AUTH_CONF file.""" default_login = 'your-login-for-api-here' default_password = 'your-password-for-api-here' config = config or {} configfile = local.path(configfile) if not configfile.exists(): configfile.dirnam...
Get authentication data from the AUTH_CONF file.
entailment
def get_content(api, rebuild_cache=False): """get content from server or cache""" if hasattr(get_content, 'cache') and not rebuild_cache: return get_content.cache if not os.path.exists(CONTENT_JSON) or rebuild_cache: import locale content_endpoint = api.content.get # pylint: ...
get content from server or cache
entailment
def get_additional_rewards(api): """returns list of non-user rewards (potion, armoire, gear)""" c = get_content(api) tasks = [c[i] for i in ['potion', 'armoire']] tasks.extend(api.user.inventory.buy.get()) for task in tasks: task['id'] = task['alias'] = task['key'] return tasks
returns list of non-user rewards (potion, armoire, gear)
entailment
def color(cls, value): """task value/score color""" index = bisect(cls.breakpoints, value) return colors.fg(cls.colors_[index])
task value/score color
entailment
def augment_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): super(CustomGenerator, self).__init__() # TODO: does this ...
Replace the existing cls.__init__() method with a new one which also initialises the field generators and similar bookkeeping.
entailment
def find_field_generators(obj): """ Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces. """ cls_dict = obj.__class__.__dict__ obj_dict = obj.__dict__ #debug_print_dict(cls_dict, 'cls_dict') #debug_prin...
Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces.
entailment
def set_item_class_name(cls_obj): """ Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux """ if '__tohu__items__name__' in...
Return the first part of the class name of this custom generator. This will be used for the class name of the items produced by this generator. Examples: FoobarGenerator -> Foobar QuuxGenerator -> Quux
entailment
def make_item_class_for_custom_generator(obj): """ obj: The custom generator instance for which to create an item class """ clsname = obj.__tohu_items_name__ attr_names = obj.field_gens.keys() return make_item_class(clsname, attr_names)
obj: The custom generator instance for which to create an item class
entailment
def add_new_init_method(obj): """ Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. ...
Replace the existing obj.__init__() method with a new one which calls the original one and in addition performs the following actions: (1) Finds all instances of tohu.BaseGenerator in the namespace and collects them in the dictionary `self.field_gens`. (2) ..to do..
entailment
def add_new_reset_method(obj): """ Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`. """ # # Create and assign automatically generated reset() method # def ne...
Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`.
entailment
def add_new_next_method(obj): """ TODO """ def new_next(self): field_values = [next(g) for g in self.field_gens.values()] return self.item_cls(*field_values) obj.__next__ = new_next
TODO
entailment
def add_new_spawn_method(obj): """ TODO """ def new_spawn(self): # TODO/FIXME: Check that this does the right thing: # (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour) # (ii) ensure that it...
TODO
entailment
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2): """ Helper function to check that the operator `op` can be applied to items produced by g1 and g2. """ g1_tmp_copy = g1.spawn() g2_tmp_copy = g2.spawn() sample_item_1 = next(g1_tmp_copy) sample_item_2 = next(g2_tmp_copy) ...
Helper function to check that the operator `op` can be applied to items produced by g1 and g2.
entailment
def add_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _dependent_generators attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): self._dependent_generators = [] orig_init(s...
Replace the existing cls.__init__() method with a new one which also initialises the _dependent_generators attribute to an empty list.
entailment
def add_new_repr_method(cls): """ Add default __repr__ method in case no user-defined one is present. """ if isinstance(cls.__repr__, WrapperDescriptorType): cls.__repr__ = lambda self: f"<{self.__class__.__name__}, id={hex(id(self))}>" else: # Keep the user-defined __repr__ method ...
Add default __repr__ method in case no user-defined one is present.
entailment
def add_new_reset_method(cls): """ Replace existing cls.reset() method with a new one which also calls reset() on any clones. """ orig_reset = cls.reset def new_reset(self, seed=None): logger.debug(f"Calling reset() on {self} (seed={seed})") orig_reset(self, seed) for c ...
Replace existing cls.reset() method with a new one which also calls reset() on any clones.
entailment
def generate(self, N, *, seed=None, progressbar=False): """ Return sequence of `N` elements. If `seed` is not None, the generator is reset using this seed before generating the elements. """ if seed is not None: self.reset(seed) items = islice(self, N...
Return sequence of `N` elements. If `seed` is not None, the generator is reset using this seed before generating the elements.
entailment
def tohu_id(self): """ Return (truncated) md5 hash representing this generator. We truncate the hash simply for readability, as this is purely intended for debugging purposes and the risk of any collisions will be negligible. """ myhash = hashlib.md5(str(id(self))...
Return (truncated) md5 hash representing this generator. We truncate the hash simply for readability, as this is purely intended for debugging purposes and the risk of any collisions will be negligible.
entailment
def _set_item_class(self): """ cls: The custom generator class for which to create an item-class """ clsname = self.__tohu_items_name__ self.item_cls = make_item_class(clsname, self.field_names)
cls: The custom generator class for which to create an item-class
entailment
def _find_field_generator_templates(self): """ Return a dictionary of the form {name: field_generator} containing all tohu generators defined in the class and instance namespace of this custom generator. """ field_gen_templates = {} # Extract field generators fro...
Return a dictionary of the form {name: field_generator} containing all tohu generators defined in the class and instance namespace of this custom generator.
entailment
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'): """ Helper function to generate a CSV header line depending on the combination of arguments provided. """ if isinstance(header, str): # user-provided header line header_line = header + newl...
Helper function to generate a CSV header line depending on the combination of arguments provided.
entailment
def _extract_schema_if_given(table_name): """ Return a pair (schema, table) derived from the given `table_name` (anything before the first '.' if the name contains one; otherwise the return value of `schema` is None). Examples: >>> _extract_schema_if_given('some_schema.my_table') (...
Return a pair (schema, table) derived from the given `table_name` (anything before the first '.' if the name contains one; otherwise the return value of `schema` is None). Examples: >>> _extract_schema_if_given('some_schema.my_table') ('some_schema', 'my_table') >>> _extract_schem...
entailment
def to_df(self, fields=None): """ Export items as rows in a pandas dataframe table. Parameters ---------- fields: list or dict List of field names to export, or dictionary mapping output column names to attribute names of the generators. Exa...
Export items as rows in a pandas dataframe table. 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...
entailment
def to_csv(self, filename=None, *, fields=None, append=False, header=True, header_prefix='', sep=',', newline='\n'): """ Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `app...
Parameters ---------- filename: str or None The file to which output will be written. By default, any existing content is overwritten. Use `append=True` to open the file in append mode instead. If filename is None, the generated CSV output is returned instead of writt...
entailment
def spawn_generator(self, g): """ Return a fresh spawn of g unless g is already contained in this SpawnMapping, in which case return the previously spawned generator. """ try: return self.mapping[g] except KeyError: return g._spawn(self)
Return a fresh spawn of g unless g is already contained in this SpawnMapping, in which case return the previously spawned generator.
entailment
def spawn(self, spawn_mapping=None): """ Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) but is otherwise independent, i.e. there is no link between the two generators (as opposed to a cloned generator, which ...
Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) but is otherwise independent, i.e. there is no link between the two generators (as opposed to a cloned generator, which is automatically reset whenever the original gene...
entailment
def clone(self, spawn_mapping=None): """ Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) and which is automatically reset whenever the original generator is reset. """ c = self.spawn(spawn_mapping) ...
Return an exact copy of this generator which behaves the same way (i.e., produces the same elements in the same order) and which is automatically reset whenever the original generator is reset.
entailment
def all_generators(self): """ Convenience property to iterate over all generators in arg_gens and kwarg_gens. """ for arg_gen in self.arg_gens: yield arg_gen for kwarg_gen in self.kwarg_gens.values(): yield kwarg_gen
Convenience property to iterate over all generators in arg_gens and kwarg_gens.
entailment
def Split(g, *, maxbuffer=10, tuple_len=None): """ Split a tuple generator into individual generators. Parameters ---------- g: tohu generator The generator to be split. The items produced by `g` must be tuples. maxbuffer: integer Maximum number of items produced by `g` that wil...
Split a tuple generator into individual generators. 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.
entailment
def tuple_len(self): """ Length of tuples produced by this generator. """ try: return self._tuple_len except AttributeError: raise NotImplementedError("Class {} does not implement attribute 'tuple_len'.".format(self.__class__.__name__))
Length of tuples produced by this generator.
entailment
def show_faults(): """ Return all valid/active faults ordered by ID to allow the user to pick and choose. :return: List of Tuples where the Tuple elements are: (fault id, fault template) """ cursor = CONN.cursor() query = "select fau_id, fault from surfaults where fau_is_valid = 'y' order by...
Return all valid/active faults ordered by ID to allow the user to pick and choose. :return: List of Tuples where the Tuple elements are: (fault id, fault template)
entailment
def show_sentences(): """ Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value. """ cursor = CONN.cursor() query = "select sen_id, sentence from sursentences where sen_...
Return all valid/active sentences ordered by ID to allow the user to pick and choose. :return: Dict containing the sentence ID as the key and the sentence structure as the value.
entailment
def get_fault(fault_id=None): """Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit...
Retrieve a randomly-generated error message as a unicode string. :param fault_id: Allows you to optionally specify an integer representing the fault_id from the database table. This allows you to retrieve a specific fault each time, albeit with different keywords.
entailment
def get_sentence(sentence_id=None): """Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each tim...
Retrieve a randomly-generated sentence as a unicode string. :param sentence_id: Allows you to optionally specify an integer representing the sentence_id from the database table. This allows you to retrieve a specific sentence each time, albeit with different keywords.
entailment
def __get_sentence(counts, sentence_id=None): """Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id: """ # First of all we need a cursor and a query to retrieve our ID's cursor = CONN.cursor() check_query = "select sen_id from su...
Let's fetch a random sentence that we then need to substitute bits of... @ :param counts: :param sentence_id:
entailment
def __get_verb(counts): """Let's fetch a VERB :param counts: """ cursor = CONN.cursor() check_query = "select verb_id from surverbs" cursor.execute(check_query) check_result = cursor.fetchall() id_list = [] for row in check_result: id_list.append(row[0]) rand = random...
Let's fetch a VERB :param counts:
entailment
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'...
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...
entailment
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...
pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts:
entailment
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...
Lets find and replace all instances of #VERB :param _sentence: :param counts:
entailment
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...
Lets find and replace all instances of #NOUN :param _sentence: :param counts:
entailment
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...
Lets find and replace all instances of #ADJECTIVE_MAYBE :param _sentence: :param counts:
entailment
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', ...
Lets find and replace all instances of #ADJECTIVE :param _sentence: :param counts:
entailment
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...
Lets find and replace all instances of #NAME :param _sentence: :param counts:
entailment
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...
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:
entailment
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....
Lets find and replace all instances of #RANDOM :param _sentence:
entailment
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...
Allows the use of repeating random-elements such as in the 'Ten green bottles' type sentences. :param sentence:
entailment
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...
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:
entailment
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...
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:
entailment
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...
Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return:
entailment
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
Internal helper function used by `explode_columns()`.
entailment
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...
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] ...
entailment
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...
Helper function which prints a sequence of `num` items produced by the random generator `gen`.
entailment
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='...
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')]
entailment
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())...
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())
entailment
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)}
Return all generators in this namespace which are not clones.
entailment
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...
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
entailment
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...
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...
entailment
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 ...
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...
entailment
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: # ...
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).
entailment
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 ...
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...
entailment
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...
Helper function which updates `field_gens` with any items in the dictionary `adict` that are instances of `TohuUltraBaseGenerator`.
entailment
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...
Return dictionary with the names and instances of all tohu.BaseGenerator occurring in the given object's class & instance namespaces.
entailment
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...
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 ...
entailment
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)
cls: The custom generator class for which to create an item-class
entailment
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`. ...
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..
entailment
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
TODO
entailment
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...
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`.
entailment
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) ...
TODO
entailment
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_...
Helper method which explicitly resets all input generators to the derived generator. This should only ever be called for testing or debugging.
entailment
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: ...
Helper function to spot-check that the items produces by this generator have the attribute `name`.
entailment
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...
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...
entailment
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...
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...
entailment
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:...
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 ...
entailment
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)
Reset this generator's seed generator and any clones.
entailment
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...
Kwargs: initial_namespace: defaults:
entailment
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...
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...
entailment
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}...
Return a configuration object
entailment
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` ...
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_...
entailment
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' ...
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.
entailment
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 ...
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...
entailment
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...
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)
entailment
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: ...
Merge variables into a single dictionary Applies to CLI provided variables only
entailment
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...
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...
entailment
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...
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...
entailment
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(...
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
entailment
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...
Verify that all required strings are in the file
entailment
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...
Find all matches of an expression in a file
entailment
def replace(self, match, content): """Replace all occurences of the regex in all matches from a file with a specific value. """ new_string = self.replace_expression.sub(self.replace_with, match) logger.info('Replacing: [ %s ] --> [ %s ]', match, new_string) new_content = ...
Replace all occurences of the regex in all matches from a file with a specific value.
entailment
def set_exit_events(self, no_workers=None, idle=None, reload=None, sig_term=None): """Do exit on certain events :param bool no_workers: Shutdown uWSGI when no workers are running. :param bool idle: Shutdown uWSGI when idle. :param bool reload: Force exit even if a reload is requested....
Do exit on certain events :param bool no_workers: Shutdown uWSGI when no workers are running. :param bool idle: Shutdown uWSGI when idle. :param bool reload: Force exit even if a reload is requested. :param bool sig_term: Exit on SIGTERM instead of brutal workers reload. ...
entailment
def set_exception_handling_params(self, handler=None, catch=None, no_write_exception=None): """Exception handling related params. :param str|unicode|list[str|unicode] handler: Register one or more exception handling C-functions. :param bool catch: Catch exceptions and report them as http outpu...
Exception handling related params. :param str|unicode|list[str|unicode] handler: Register one or more exception handling C-functions. :param bool catch: Catch exceptions and report them as http output (including stack trace and env params). .. warning:: Use only for testing purposes. ...
entailment