cereja.utils

Copyright (c) 2019 The Cereja Project

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class cereja.utils.CjTest(instance_obj)[source]

Bases: object

Parameters:

instance_obj (object)

add_check(*check_)[source]
Parameters:

check_ (_Attr)

classmethod build_test(reference)[source]
check_all()[source]
check_attr(attr_name)[source]
Parameters:

attr_name (str | _Attr)

property checks
property n_checks
parse_attr(attr_)[source]
Parameters:

attr_ (str)

remove_check(index)[source]
Parameters:

index (int)

class cereja.utils.DataAnalyzer(data)[source]

Bases: object

TYPES_DATA_ITERATOR_MAP = {<class 'float'>: <class 'cereja.utils._utils.DataNumberIterator'>, <class 'int'>: <class 'cereja.utils._utils.DataNumberIterator'>, <class 'str'>: <class 'cereja.utils._utils.DataStringIterator'>}
get_by_type(t)[source]
property has_numbers
property has_strings
property is_empty
property is_mixed_type
property is_numbers
property is_strings
property length
property numbers
property report
property strings
property types
class cereja.utils.DataIterator(data, **kwargs)[source]

Bases: object

Parameters:

data (Iterable | Sequence | DataIterator)

property analyzer: DataAnalyzer

Get a data analyzer for the data iterator.

Returns:

A data analyzer for the data iterator.

Return type:

DataAnalyzer

batch(batch_size=1, step=None)[source]

Create batches of data from the iterator.

Parameters:
  • batch_size (int, optional) – The size of each batch. Default is 1.

  • step (int, optional) – The step size between batches. Default is 1.

Returns:

A new DataIterator instance containing the batches.

Return type:

DataIterator

combinations(r, is_sorted=False)[source]

Get the r-length subsequences of the data iterator. @param r: The length of the subsequences. @param is_sorted: Whether to sort the subsequences. Default is False. @return:

Return type:

DataIterator

Parameters:

r (<property object at 0x7f53a0060f40>)

cycle()[source]

Take the first n elements from the data iterator.

Parameters:

n (int, optional) – The number of elements to take. If None, all elements are taken.

Returns:

An iterable containing the first n elements.

Return type:

Iterable[Any]

enumerate(start=0)[source]

Enumerate the data and return a new DataIterator instance with the enumerated data.

Parameters:

start (int) – The starting index for enumeration.

Returns:

A new DataIterator instance containing the enumerated data.

Return type:

DataIterator

filter(func)[source]

Filter the data using the given function and return a new DataIterator instance with the filtered data.

Parameters:

func (Callable[[Any], bool]) – The function to filter the data.

Returns:

A new DataIterator instance containing the filtered data.

Return type:

DataIterator

property first: Any

Get the first element of the data iterator.

Returns:

The first element of the iterator.

Return type:

Any

flatten()[source]

Flatten the data iterator and return a new DataIterator instance with the flattened data.

Returns:

A new DataIterator instance containing the flattened data.

Return type:

DataIterator

property float: DataNumberIterator

Convert the data to float and return a new DataIterator instance with the converted data.

Returns:

A new DataIterator instance containing the converted data.

Return type:

DataIterator

property freq

Get the frequency of the data iterator.

Returns:

A dictionary containing the frequency of the data iterator.

Return type:

Dict

group_by(func=<function DataIterator.<lambda>>)[source]
Return type:

Dict

Parameters:

func (Callable[[Any], Any])

property int: DataNumberIterator

Convert the data to integer and return a new DataIterator instance with the converted data.

Returns:

A new DataIterator instance containing the converted data.

Return type:

DataIterator

property is_empty: bool

Check if the data iterator is empty.

Returns:

True if the iterator is empty, False otherwise.

Return type:

bool

property last: Any

Get the last element of the data iterator.

Returns:

The last element of the iterator.

Return type:

Any

property length: int
map(func)[source]

Map the data using the given function and return a new DataIterator instance with the mapped data.

Parameters:

func (Callable[[Any], Any]) – The function to map the data.

Returns:

A new DataIterator instance containing the mapped data.

Return type:

DataIterator

property next

Get the next element of the data iterator.

Returns:

The next element of the iterator.

Return type:

Any

random()[source]

Shuffle the data randomly and return a new DataIterator instance with the shuffled data.

Returns:

A new DataIterator instance containing the shuffled data.

Return type:

DataIterator

reduce(func, initial=None)[source]

Reduce the data using the given function and return the result. @param func: @param initial: @return:

Return type:

Any

Parameters:

func (Callable[[Any, Any], Any])

save(path, exist_ok=False, **kwargs)[source]

Save the data iterator to a file. @param path: The path to save the data iterator. @param exist_ok: Whether to overwrite the file if it already exists.

Returns: None

Parameters:

path (<property object at 0x7f53a0060ef0>)

sort(key=None, reverse=False)[source]

Sort the data using the given key and return a new DataIterator instance with the sorted data.

Parameters:
  • key (Optional[Callable[[Any], Any]]) – The key function to sort the data.

  • reverse (bool) – Whether to sort the data in reverse order.

Returns:

A new DataIterator instance containing the sorted data.

Return type:

DataIterator

property str: DataStringIterator

Convert the data to string and return a new DataIterator instance with the converted data.

Returns:

A new DataIterator instance containing the converted data.

Return type:

DataIterator

summary()[source]

Get a summary of the data iterator.

Returns:

A dictionary containing the summary of the data iterator.

Return type:

Dict

take(n=None)[source]
Return type:

list

Parameters:

n (int)

class cereja.utils.GitRepository(repo_path='.')[source]

Bases: object

Facade para operações comuns de Git com cache de branches.

property all_branches: list[str]
property branches_count: dict[str, int]
checkout(branch, create_new=False)[source]

Troca para a branch especificada, opcionalmente criando uma nova.

Parameters:
  • branch (str)

  • create_new (bool)

property current_branch: str

Retorna a branch atual.

diff(branch, file_pattern=None, check_origin=True)[source]

Retorna o diff entre a branch atual e a branch especificada, opcionalmente filtrando por padrão de arquivo. :type branch: str :param branch: Nome da branch para comparar com a atual :type file_pattern: str :param file_pattern: Padrão de arquivo para filtrar (ex: ‘.py’, ‘docs/’)

Returns:

Saída do comando git diff

Return type:

str

Raises:

ValueError – Se a branch não existir

Parameters:
  • branch (str)

  • file_pattern (str)

  • check_origin (bool)

property has_remote: bool

Verifica se o repositório tem um remoto configurado.

property is_clean: bool

Verifica se o repositório está limpo (sem mudanças não commitadas).

property is_repo: bool

Verifica se o diretório atual é um repositório Git.

last_commit(branch=None)[source]

Retorna o último commit da branch especificada ou da atual.

Return type:

str

Parameters:

branch (str)

property local_branches: list[str]
log(branch=None, max_count=10)[source]

Retorna o log de commits da branch especificada ou da atual.

Return type:

str

Parameters:
  • branch (str)

  • max_count (int)

messages(branch=None, max_count=10)[source]

Retorna uma lista de mensagens de commit da branch especificada ou da atual.

Return type:

list[str]

Parameters:
  • branch (str)

  • max_count (int)

property need_commit: bool

Verifica se há mudanças não commitadas.

pull(remote='origin', branch=None)[source]

Puxa mudanças do remoto especificado, opcionalmente para uma branch específica.

Parameters:
push(remote='origin', branch=None, set_upstream=False)[source]

Empurra mudanças para o remoto especificado, opcionalmente para uma branch específica.

Parameters:
  • remote (str)

  • branch (str)

  • set_upstream (bool)

refresh_branches()[source]

Atualiza cache das branches locais e remotas.

property remote_branches: list[str]
property remotes: list[str]

Retorna lista de remotos configurados.

class cereja.utils.PoolMeta[source]

Bases: type

A thread-safe implementation to control the maximum number of instances.

get_instances()[source]
get_max_instances()[source]
release_instance(instance)[source]
set_max_instances(max_instances)[source]
class cereja.utils.SingletonMeta[source]

Bases: type

A thread-safe implementation of Singleton.

cereja.utils.Source(reference)[source]
Parameters:

reference (Any)

class cereja.utils.SourceCodeAnalyzer(reference)[source]

Bases: object

Parameters:

reference (Any)

property argument_count: int
property argument_defaults: dict
property argument_names: list
property arguments
property docstring: str | None
property has_arguments: bool
property has_kwargs: bool
property has_varargs: bool
property name: str
property optional_arguments: list
property required_arguments: list
save_source_code(path, **kwargs)[source]
Parameters:

path (str)

property source_code: str
class cereja.utils.Timer(interval=-1, start=True, auto_reset=False)[source]

Bases: object

A Timer class to manage time intervals and check if a specified interval has passed.

_interval

The time interval in seconds.

Type:

float

_start

The start time in seconds since the epoch.

Type:

float

_auto_reset

Whether the timer should automatically reset after the interval has passed.

Type:

bool

property auto_reset

Get the auto reset setting.

Returns:

True if the timer automatically resets after the interval has passed, False otherwise.

Return type:

bool

property elapsed

Get the elapsed time since the timer was started.

Returns:

The elapsed time in seconds.

Return type:

float

property interval

Get the time interval.

Returns:

The time interval in seconds.

Return type:

float

property is_timeout
iter_over(iterable)[source]

Iterate over an iterable and wait until the timer interval has passed. @param iterable: An iterable object. @return: An iterator object.

property remaining

Get the remaining time until the interval has passed.

Returns:

The remaining time in seconds.

Return type:

float

reset()[source]
start()[source]

Start the timer by setting the start time to the current time.

property started: bool
property time_overflow
wait()[source]

Wait until the timer interval has passed.

cereja.utils.camel_case_to_snake(value)[source]
Parameters:

value (str)

cereja.utils.camel_to_snake(value)[source]
Parameters:

value (str)

cereja.utils.can_do(obj)[source]

List methods and attributes of a Python object.

It is essentially the builtin dir function without the private methods and attributes

@param obj: Any @return: list of attr names sorted by name

Return type:

List[str]

Parameters:

obj (Any)

cereja.utils.check_type_on_sequence(sequence, t)[source]

Check if all elements in a sequence are of a certain type.

Parameters:
  • sequence (list) – The sequence to be checked.

  • t (type or tuple) – The type or tuple of types to check against.

Returns:

True if all elements are of the specified type, False otherwise.

Return type:

bool

cereja.utils.chunk(data, batch_size=None, fill_with=None, is_random=False, max_batches=None)[source]

e.g: >>> import cereja as cj

Return type:

List[Union[Sequence, List, Tuple, Dict]]

Parameters:
  • data (Sequence)

  • batch_size (int)

  • fill_with (Any)

  • is_random (bool)

  • max_batches (int)

>>> data = list(range(15))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> cj.chunk(data, batch_size=4)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14]]
>>> cj.chunk(data, batch_size=4, is_random=True, fill_with=0)
[[7, 2, 11, 4], [10, 6, 1, 13], [12, 9, 5, 0], [8, 3, 14, 0]]
>>> data = {"key1": 'value1', "key2": 'value2', "key3": 'value3', "key4": 'value4'}
>>> cj.chunk(data, batch_size=2,is_random=True)
[{'key3': 'value3', 'key2': 'value2'}, {'key1': 'value1', 'key4': 'value4'}]

@param data: Iterable data @param batch_size: number of items per batch @param fill_with: Any, but isn’t valid for dict @param is_random: shuffle data @param max_batches: limit number of batches @return: list of batches

cereja.utils.clipboard()[source]
Return type:

str

cereja.utils.combinations(iterable, size, is_sorted=False)[source]

Generate all possible combinations of a certain size from an iterable.

Args: iterable (iterable): An iterable of Python objects. size (int): The size of each combination.

Returns: list of tuples: A list containing tuples of the combinations generated.

cereja.utils.combinations_sizes(iterable, min_size, max_size, is_sorted=False)[source]

Generate all possible combinations for all sizes within the specified range from an iterable.

Args: iterable (iterable): An iterable of Python objects. min_size (int): The minimum size of the combinations. max_size (int): The maximum size of the combinations.

Returns: list of tuples: A list containing tuples of all combinations for sizes between min_size and max_size.

cereja.utils.combine_with_all(a, b, n_a_combinations=1, is_random=False)[source]
Return type:

List[Tuple[Any, ...]]

Parameters:
  • a (list)

  • b (list)

  • n_a_combinations (int)

  • is_random (bool)

>>> a = [1, 2, 3]
>>> b = ['anything_a', 'anything_b']
>>> combine_with_all(a, b)
[(1, 'anything_a'), (1, 'anything_b'), (2, 'anything_a'), (2, 'anything_b'), (3, 'anything_a'), (3, 'anything_b')]
>>> combine_with_all(a, b, n_a_combinations=2)
[((1, 2), 'anything_a'), ((1, 2), 'anything_b'),
((1, 3), 'anything_a'), ((1, 3), 'anything_b'),
((2, 3), 'anything_a'), ((2, 3), 'anything_b')]
cereja.utils.decode_coordinates(lparam)[source]

Decode the lParam value back into the original coordinates (x, y).

The decoding is done by extracting the lower 16 bits for the x-coordinate and the upper 16 bits for the y-coordinate.

Parameters:

lparam (int) – The encoded lParam value.

Returns:

A tuple containing the x and y coordinates.

Return type:

tuple

cereja.utils.dict_append(obj, key, *v, unique_values=False, sort_values_by=None, reverse=False)[source]

Add items to a key in the dictionary. If the key doesn’t exist, it’s created with a list and the given values.

e.g:

Return type:

Dict

Parameters:
  • obj (Dict[Any, List | Tuple])

  • key (Any)

  • unique_values (bool)

  • sort_values_by (Callable | None)

  • reverse (bool)

>>> my_dict = {}
>>> dict_append(my_dict, 'key_eg', 1,2,3,4,5,6)
{'key_eg': [1, 2, 3, 4, 5, 6]}
>>> dict_append(my_dict, 'key_eg', [1,2])
{'key_eg': [1, 2, 3, 4, 5, 6, [1, 2]]}

Parameters: - obj: A dictionary with list or tuple values. - key: The key to which the values should be added. - v: The values to be added. - unique_values: Whether to ensure the values are unique. - sort_values_by: Optional function to sort the values. - reverse: Used if sort_values_by is passed.

Returns: Updated dictionary.

cereja.utils.dict_filter_value(obj, f)[source]

Results is a filtered dict by f func result

@param obj: is a dict @param f: function filter @return:

Return type:

Any

Parameters:

obj (Dict[Any, Any])

cereja.utils.dict_max_value(obj)[source]

Results is a filtered dict by max value

Return type:

Any

Parameters:

obj (Dict[Any, Any])

>>> import cereja as cj
>>> cj.dict_max_value({'oi': 10, 'aqui': 20, 'sei': 20})
{'aqui': 20, 'sei': 20}

@param obj: is a dict @return: dict filtered

cereja.utils.dict_min_value(obj)[source]

Results is a filtered dict by min value

Return type:

Any

Parameters:

obj (Dict[Any, Any])

>>> import cereja as cj
>>> cj.dict_min_value({'oi': 10, 'aqui': 20, 'sei': 20})
{'oi': 10}

@param obj: is a dict @return: dict filtered

cereja.utils.dict_to_tuple(obj)[source]
cereja.utils.dict_values_len(obj, max_len=None, min_len=None, take_len=False)[source]
cereja.utils.encode_coordinates(x, y)[source]

Encode the coordinates (x, y) into a single lParam value.

The encoding is done by shifting the y-coordinate 16 bits to the left and then performing a bitwise OR with the x-coordinate.

Parameters:
  • x (int) – The x-coordinate.

  • y (int) – The y-coordinate.

Returns:

The encoded lParam value.

Return type:

int

cereja.utils.fill(value, max_size, with_=' ')[source]

Calculates and adds value

Return type:

Any

Parameters:

value (list | str | tuple)

cereja.utils.format_safe_traceback(exc, *, secrets=(), path_prefixes=None, include_source=False)[source]

Return a sanitized traceback without modifying the exception.

Frame and SyntaxError filenames use basenames, except configured prefixes preserve suffixes (e.g. {r’C:project’: ‘<project>’}). Home and cwd prefixes are included automatically. Explicit entries override equivalent defaults; slash styles are equivalent, matching is case-sensitive, longest prefix wins. Filesystem roots are ignored. Messages and notes use literal prefix matching.

Non-empty literal secrets are case-sensitive and take priority over path replacements. Replacement labels are not recursively expanded. Source lines (including SyntaxError text) are omitted unless include_source is true; local variables are never captured. Standard chain suppression and exception group truncation apply.

This is best-effort redaction, not automatic sensitive-data detection: unknown paths in messages and unspecified or encoded secrets may remain.

Return type:

str

Parameters:
  • exc (BaseException)

  • secrets (Iterable[str])

  • path_prefixes (Mapping[str, str] | None)

  • include_source (bool)

cereja.utils.get_attr_if_exists(obj, attr)[source]
Return type:

Optional[object]

Parameters:
  • obj (Any)

  • attr (str)

cereja.utils.get_batch_strides(data, kernel_size, strides=1, fill_=False, take_index=False)[source]

Returns batches of fixed window size (kernel_size) with a given stride @param data: iterable @param kernel_size: window size @param strides: default is 1 @param take_index: add number of index on items @param fill_: padding last batch if it needs

cereja.utils.get_implements(klass)[source]
Parameters:

klass (type)

cereja.utils.get_instances_of(klass)[source]
Parameters:

klass (type)

cereja.utils.get_version(version=None)[source]

Dotted version of the string type is expected e.g: ‘1.0.3.a.3’ # Pep440 see https://www.python.org/dev/peps/pep-0440/ :type version: Union[str, Tuple[int, int, int, str, int]] :param version: Dotted version of the string

Return type:

Tuple[int, int, int, str, int]

Parameters:

version (str | Tuple[int, int, int, str, int])

cereja.utils.get_version_pep440_compliant(version=None)[source]

Dotted version of the string type is expected e.g: ‘1.0.3.a.3’ # Pep440 see https://www.python.org/dev/peps/pep-0440/ :type version: str :param version: Dotted version of the string

Return type:

str

Parameters:

version (str)

cereja.utils.get_zero_mask(number, max_len=3)[source]

Returns string of numbers formated with zero mask eg. >>> get_zero_mask(100, 4) ‘0100’ >>> get_zero_mask(101, 4) ‘0101’ >>> get_zero_mask(101, 4) ‘0101’

Return type:

str

Parameters:
cereja.utils.group_by(values, fn, get_freq=False)[source]

group items by result of fn (function)

eg. >>> import cereja as cj >>> values = [‘joab’, ‘leite’, ‘da’, ‘silva’, ‘Neto’, ‘você’] >>> cj.group_by(values, lambda x: ‘N’ if x.lower().startswith(‘n’) else ‘OTHER’) # {‘OTHER’: [‘joab’, ‘leite’, ‘da’, ‘silva’, ‘você’], ‘N’: [‘Neto’]} >>> cj.group_by(values, lambda x: ‘N’ if x.lower().startswith(‘n’) else ‘OTHER’, get_freq=True) # ({‘OTHER’: [‘joab’, ‘leite’, ‘da’, ‘silva’, ‘você’], ‘N’: [‘Neto’]}, # {‘OTHER’: 5, ‘N’: 1})

@param values: list of values @param fn: a function @param get_freq: if True, returns a tuple containing the main result of the function followed by the frequency distribution of the groups, respectively

Return type:

Union[dict, Tuple[dict, dict]]

Parameters:

get_freq (bool)

cereja.utils.has_length(seq)[source]
cereja.utils.import_string(dotted_path)[source]

Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed.

cereja.utils.install_if_not(lib_name)[source]
Parameters:

lib_name (str)

cereja.utils.invert_dict(dict_)[source]

Inverts the key by value e.g: >>> example = {“a”: “b”, “c”: “d”} >>> invert_dict(example) {“b” : “a”, “d”: “c”} :rtype: dict :return: dict

Parameters:

dict_ (dict | set)

Return type:

dict

cereja.utils.is_indexable(v)[source]
cereja.utils.is_iterable(obj)[source]

Return whether an object is iterable or not.

This function checks if the object has an __iter__ method or supports sequence-like indexing via __getitem__.

Parameters: obj (Any): Any object to check for iterability.

Returns: bool: True if the object is iterable, False otherwise.

Return type:

bool

Parameters:

obj (Any)

cereja.utils.is_numeric_sequence(obj)[source]
Return type:

bool

Parameters:

obj (Sequence[int | float | complex])

cereja.utils.is_sequence(obj)[source]

Return whether an object a Sequence or not, exclude strings and empty obj.

Parameters:

obj (Any) – Any object for check

Return type:

bool

cereja.utils.latest_git()[source]

Return a numeric identifier of the latest git changeset.

cereja.utils.list_methods(klass)[source]
Return type:

List[str]

cereja.utils.list_to_tuple(obj)[source]
cereja.utils.logger_level()[source]
cereja.utils.map_values(obj, fn)[source]
Return type:

Union[dict, list, tuple, Iterator]

Parameters:
  • obj (dict | list | tuple | Iterator)

  • fn (Callable)

cereja.utils.module_references(instance, **kwargs)[source]

dict of all functions and classes defined in the module. To also list the variables it is necessary to define explicitly with the special variable on your module _include **kwargs: _include -> to includes any definition and variables _exclude -> to exclude any definition :type instance: ModuleType :param instance: :rtype: dict :return: List[str]

Parameters:

instance (ModuleType)

Return type:

dict

cereja.utils.obj_repr(obj_, attr_limit=10, val_limit=3, show_methods=False, show_private=False, deep=3)[source]
cereja.utils.prune_values(values, factor=2)[source]

Prunes the values in the sequence by reducing the number of elements based on the given factor.

Parameters:
  • values (Sequence) – The sequence of values to be pruned.

  • factor (int) – The factor by which to prune the values. Default is 2.

Returns:

The pruned sequence of values.

Return type:

Sequence

Raises:

TypeError – If the input values are not subscriptable.

cereja.utils.rescale_values(values, granularity, interpolation=False, fill_with=None, filling='inner')[source]
Return type:

List[Any]

Parameters:
  • values (List[Any])

  • granularity (int)

  • interpolation (bool)

Resizes a list of values eg.

>>> import cereja as cj
>>> cj.rescale_values(values=list(range(100)),granularity=12)
[0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88]
>>> cj.rescale_values(values=list(range(5)),granularity=10)
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
>>> cj.rescale_values(values=list(range(5)),granularity=10, filling='pre')
[0, 0, 0, 0, 0, 0, 1, 2, 3, 4]
>>> cj.rescale_values(values=list(range(5)),granularity=10, filling='post')
[0, 1, 2, 3, 4, 4, 4, 4, 4, 4]

@note if you don’t send any value for filling a value will be chosen arbitrarily depending on the filling type.

If interpolation is set to True, then the resized values are calculated by interpolation, otherwise they are sub- ou upsampled from the original list

@param values: Sequence of anything @param granularity: is a integer @param interpolation: is a boolean @param fill_with: only scale up, send any value for filling @param filling: in case of scale up, you can define how the filling will be (pre, inner, post). ‘inner’ is default. @return: rescaled list of values.

cereja.utils.sample(v, k=None, is_random=False)[source]

Get sample of anything

@param v: Any @param k: int @param is_random: default False @return: sample iterable

Return type:

Union[list, dict, set, Any]

Parameters:
  • v (Sequence)

  • k (int)

  • is_random (bool)

cereja.utils.set_interval(func, sec, is_daemon=False)[source]

Call a function every sec seconds @param func: function @param is_daemon: If True, the thread will be a daemon @param sec: seconds

Return type:

IntervalScheduler

Parameters:
  • func (Callable)

  • sec (float)

cereja.utils.set_log_level(level)[source]

Default log level is INFO CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0

Parameters:

level (int | str)

cereja.utils.snake_case_to_camel(value, upper_first=False)[source]
cereja.utils.sort_dict(obj, by_keys=False, by_values=False, reverse=False, by_len_values=False, func_values=None, func_keys=None)[source]
Return type:

OrderedDict

Parameters:

obj (dict)

cereja.utils.split_sequence(seq, is_break_fn)[source]

Split a sequence into subsequences based on a break function. @param seq: sequence to split @param is_break_fn: function that returns True if the sequence should be split at the current index e.g: >>> import cereja as cj >>> seq = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> cj.split_sequence(seq, lambda current_val: current_val % 3 == 0) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> cj.split_sequence(seq, lambda current_val, next_val: current_val % 2 == 0 and next_val % 3 == 0) [[1, 2], [3, 4, 5, 6, 7, 8], [9]] >>> cj.split_sequence(seq, lambda: True) [[1], [2], [3], [4], [5], [6], [7], [8], [9]] >>> cj.split_sequence(seq, lambda current_val, next_val, index: seq[index-1] % 2 == 0 and current_val % 3 == 0) [[1, 2, 3], [4, 5, 6, 7, 8, 9]] @return: list of subsequences

Return type:

List[List[Any]]

Parameters:
  • seq (List[Any])

  • is_break_fn (Callable)

cereja.utils.str_gen(pattern)[source]
Return type:

Sequence[AnyStr]

Parameters:

pattern (AnyStr)

cereja.utils.stride_values(data, kernel_size, strides=1, fill_=False, take_index=False)

Returns batches of fixed window size (kernel_size) with a given stride @param data: iterable @param kernel_size: window size @param strides: default is 1 @param take_index: add number of index on items @param fill_: padding last batch if it needs

cereja.utils.string_to_literal(val)[source]
Parameters:

val (str | bytes)

cereja.utils.time_format(seconds, format_='%H:%M:%S')[source]

Default format is ‘%H:%M:%S’ If the time exceeds 24 hours, it will return a format like ‘X days HH:MM:SS’

Return type:

Union[str, float]

Parameters:

seconds (float)

>>> time_format(3600)
'01:00:00'
>>> time_format(90000)
'1 days 01:00:00'
cereja.utils.to_tuple(obj)[source]
cereja.utils.truncate(data, k_iter=0, k_str=0, k_dict_keys=0)[source]

Truncates the data to the specified number of elements in half(+1 if odd) + half, adding a filler in between. If the data is a dictionary, then truncates recursively until data is “truncatable”. Allows to specify a different to k to strings and number of dictionary keys. :type data: Sequence :param data: sequence :type k_iter: int :param k_iter: number of elements of iterable data to return :type k_str: int :param k_str: number of elements of strings to return :type k_dict_keys: int :param k_dict_keys: number of dictionary keys to return

Returns:

truncated data

Parameters:
  • data (Sequence)

  • k_iter (int)

  • k_str (int)

  • k_dict_keys (int)

cereja.utils.type_table_of(o)[source]
Parameters:

o (list | tuple | dict)

cereja.utils.value_from_memory(memory_id)[source]

Retrieve the Python object stored at a specific memory address.

Args: memory_id (int): The memory address of the object.

Returns: object: The Python object stored at the given memory address, or None if the retrieval fails.

cereja.utils.visualize_sample(v, k=None, is_random=False, tr_k_iter=6, tr_k_str=20, tr_k_dict_keys=20, p_print=True, str_width=200)[source]

Samples then (p)prints a (truncated) version of the sample. Helpful for visualizing data structures. :type v: Sequence :param v: sequence :type k: int :param k: number of samples :type is_random: bool :param is_random: should shuffle :type tr_k_iter: int :param tr_k_iter: how many items of iterables to keep in the truncated version of the sample, 0 to disable :type tr_k_str: int :param tr_k_str: truncated length of strings, 0 to disable :type tr_k_dict_keys: int :param tr_k_dict_keys: truncated number of dictionary keys, 0 to disable :type p_print: bool :param p_print: should pprint or print :type str_width: int :param str_width: width of strings in the output, used if p_print

Parameters:
  • v (Sequence)

  • k (int)

  • is_random (bool)

  • tr_k_iter (int)

  • tr_k_str (int)

  • tr_k_dict_keys (int)

  • p_print (bool)

  • str_width (int)