Search is not available for this dataset
text
stringlengths
75
104k
def get_file_handler(file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, handler=logging.FileHandler, **handler_kwargs): """ Set up a file handler to add to a logger. :param file_path: file to write the log to, defaults t...
def setup_logger(module_name=None, level=logging.INFO, stream=sys.stderr, file_path=None, log_format=log_formats.easy_read, suppress_warning=True): """ Grabs the specified logger and adds wanted handlers to it. Will default to adding a stream handler. :param module_nam...
def add_stream_handler(logger=None, stream=sys.stderr, level=logging.INFO, log_format=log_formats.easy_read): """ Addes a newly created stream handler to the specified logger :param logger: logging name or object to modify, defaults to root logger :param stream: which stream to u...
def add_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read): """ Addes a newly created file handler to the specified logger :param logger: logging name or object to modify, defaults to root logger :param file_path: path to file to lo...
def add_rotating_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, max_bytes=10*sizes.mb, backup_count=5, **handler_kwargs): """ Adds a rotating ...
def add_timed_rotating_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, when='w0', interval=1, backup_count=5, **handler_kwa...
def remove_stream_handlers(logger=None): """ Remove only stream handlers from the specified logger :param logger: logging name or object to modify, defaults to root logger """ if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) new_handlers = [] for handle...
def remove_file_handlers(logger=None): """ Remove only file handlers from the specified logger. Will go through and close each handler for safety. :param logger: logging name or object to modify, defaults to root logger """ if not isinstance(logger, logging.Logger): logger = logging.get...
def remove_all_handlers(logger=None): """ Safely remove all handlers from the logger :param logger: logging name or object to modify, defaults to root logger """ if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) remove_file_handlers(logger) logger.handle...
def change_logger_levels(logger=None, level=logging.DEBUG): """ Go through the logger and handlers and update their levels to the one specified. :param logger: logging name or object to modify, defaults to root logger :param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error) ...
def get_registered_loggers(hide_children=False, hide_reusables=False): """ Find the names of all loggers currently registered :param hide_children: only return top level logger names :param hide_reusables: hide the reusables loggers :return: list of logger names """ return [logger for logg...
def unique(max_retries=10, wait=0, alt_return="-no_alt_return-", exception=Exception, error_text=None): """ Wrapper. Makes sure the function's return value has not been returned before or else it run with the same inputs again. .. code: python import reusables import random ...
def lock_it(lock=g_lock): """ Wrapper. Simple wrapper to make sure a function is only run once at a time. .. code: python import reusables import time def func_one(_): time.sleep(5) @reusables.lock_it() def func_two(_): time.sleep(5) ...
def time_it(log=None, message=None, append=None): """ Wrapper. Time the amount of time it takes the execution of the function and print it. If log is true, make sure to set the logging level of 'reusables' to INFO level or lower. .. code:: python import time import reusables ...
def queue_it(queue=g_queue, **put_args): """ Wrapper. Instead of returning the result of the function, add it to a queue. .. code: python import reusables import queue my_queue = queue.Queue() @reusables.queue_it(my_queue) def func(a): return a ...
def log_exception(log="reusables", message=None, exceptions=(Exception, ), level=logging.ERROR, show_traceback=True): """ Wrapper. Log the traceback to any exceptions raised. Possible to raise custom exception. .. code :: python @reusables.log_exception() def test(): ...
def catch_it(exceptions=(Exception, ), default=None, handler=None): """ If the function encounters an exception, catch it, and return the specified default or sent to a handler function instead. .. code :: python def handle_error(exception, func, *args, **kwargs): print(f"{func.__n...
def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None, raised_exception=ReusablesError, raised_message=None): """ Retry a function if an exception is raised, or if output_check returns False. Message format options: {func} {args} {kwargs} :param exceptions: tuple of ex...
def extract(archive_file, path=".", delete_on_success=False, enable_rar=False): """ Automatically detect archive type and extract all files to specified path. .. code:: python import os os.listdir(".") # ['test_structure.zip'] reusables.extract("test_structure...
def archive(files_to_archive, name="archive.zip", archive_type=None, overwrite=False, store=False, depth=None, err_non_exist=True, allow_zip_64=True, **tarfile_kwargs): """ Archive a list of files (or files inside a folder), can chose between - zip - tar - gz (tar.gz...
def list_to_csv(my_list, csv_file): """ Save a matrix (list of lists) to a file as a CSV .. code:: python my_list = [["Name", "Location"], ["Chris", "South Pole"], ["Harry", "Depth of Winter"], ["Bob", "Skull"]] reusables.list_to_cs...
def csv_to_list(csv_file): """ Open and transform a CSV file into a matrix (list of lists). .. code:: python reusables.csv_to_list("example.csv") # [['Name', 'Location'], # ['Chris', 'South Pole'], # ['Harry', 'Depth of Winter'], # ['Bob', 'Skull']] :param c...
def load_json(json_file, **kwargs): """ Open and load data from a JSON file .. code:: python reusables.load_json("example.json") # {u'key_1': u'val_1', u'key_for_dict': {u'sub_dict_key': 8}} :param json_file: Path to JSON file as string :param kwargs: Additional arguments for the ...
def save_json(data, json_file, indent=4, **kwargs): """ Takes a dictionary and saves it to a file as JSON .. code:: python my_dict = {"key_1": "val_1", "key_for_dict": {"sub_dict_key": 8}} reusables.save_json(my_dict,"example.json") example.json .. code:: ...
def config_dict(config_file=None, auto_find=False, verify=True, **cfg_options): """ Return configuration options as dictionary. Accepts either a single config file or a list of files. Auto find will search for all .cfg, .config and .ini in the execution directory and package root (unsafe but handy). ...
def config_namespace(config_file=None, auto_find=False, verify=True, **cfg_options): """ Return configuration options as a Namespace. .. code:: python reusables.config_namespace(os.path.join("test", "data", "test_config.ini")) ...
def _walk(directory, enable_scandir=False, **kwargs): """ Internal function to return walk generator either from os or scandir :param directory: directory to traverse :param enable_scandir: on python < 3.5 enable external scandir package :param kwargs: arguments to pass to walk function :return...
def os_tree(directory, enable_scandir=False): """ Return a directories contents as a dictionary hierarchy. .. code:: python reusables.os_tree(".") # {'doc': {'build': {'doctrees': {}, # 'html': {'_sources': {}, '_static': {}}}, # 'source': {}}, ...
def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True): """ Hash a given file with md5, or any other and return the hex digest. You can run `hashlib.algorithms_available` to see which are available on your system unless you have an archaic python version, you poor soul). This funct...
def find_files(directory=".", ext=None, name=None, match_case=False, disable_glob=False, depth=None, abspath=False, enable_scandir=False): """ Walk through a file directory and return an iterator of files that match requirements. Will autodetect if name has glob as magic ch...
def remove_empty_directories(root_directory, dry_run=False, ignore_errors=True, enable_scandir=False): """ Remove all empty folders from a path. Returns list of empty directories. :param root_directory: base directory to start at :param dry_run: just return a list of what w...
def remove_empty_files(root_directory, dry_run=False, ignore_errors=True, enable_scandir=False): """ Remove all empty files from a path. Returns list of the empty files removed. :param root_directory: base directory to start at :param dry_run: just return a list of what would be ...
def dup_finder(file_path, directory=".", enable_scandir=False): """ Check a directory for duplicates of the specified file. This is meant for a single file only, for checking a directory for dups, use directory_duplicates. This is designed to be as fast as possible by doing lighter checks befor...
def directory_duplicates(directory, hash_type='md5', **kwargs): """ Find all duplicates in a directory. Will return a list, in that list are lists of duplicate files. .. code: python dups = reusables.directory_duplicates('C:\\Users\\Me\\Pictures') print(len(dups)) # 56 ...
def join_paths(*paths, **kwargs): """ Join multiple paths together and return the absolute path of them. If 'safe' is specified, this function will 'clean' the path with the 'safe_path' function. This will clean root decelerations from the path after the first item. Would like to do 'safe=False...
def join_here(*paths, **kwargs): """ Join any path or paths as a sub directory of the current file's directory. .. code:: python reusables.join_here("Makefile") # 'C:\\Reusables\\Makefile' :param paths: paths to join together :param kwargs: 'strict', do not strip os.sep :param...
def check_filename(filename): """ Returns a boolean stating if the filename is safe to use or not. Note that this does not test for "legal" names accepted, but a more restricted set of: Letters, numbers, spaces, hyphens, underscores and periods. :param filename: name of a file as a string :retu...
def safe_filename(filename, replacement="_"): """ Replace unsafe filename characters with underscores. Note that this does not test for "legal" names accepted, but a more restricted set of: Letters, numbers, spaces, hyphens, underscores and periods. :param filename: name of a file as a string :...
def safe_path(path, replacement="_"): """ Replace unsafe path characters with underscores. Do NOT use this with existing paths that cannot be modified, this to to help generate new, clean paths. Supports windows and *nix systems. :param path: path as a string :param replacement: character ...
def change_task_size(self, size): """Blocking request to change number of running tasks""" self._pause.value = True self.log.debug("About to change task size to {0}".format(size)) try: size = int(size) except ValueError: self.log.error("Cannot change task ...
def stop(self): """Hard stop the server and sub process""" self._end.value = True if self.background_process: try: self.background_process.terminate() except Exception: pass for task_id, values in self.current_tasks.items(): ...
def get_state(self): """Get general information about the state of the class""" return {"started": (True if self.background_process and self.background_process.is_alive() else False), "paused": self._pause.value, "stopped": self._end.value, ...
def main_loop(self, stop_at_empty=False): """Blocking function that can be run directly, if so would probably want to specify 'stop_at_empty' to true, or have a separate process adding items to the queue. """ try: while True: self.hook_pre_command() ...
def run(self): """Start the main loop as a background process. *nix only""" if win_based: raise NotImplementedError("Please run main_loop, " "backgrounding not supported on Windows") self.background_process = mp.Process(target=self.main_loop) ...
def cmd(command, ignore_stderr=False, raise_on_return=False, timeout=None, encoding="utf-8"): """ Run a shell command and have it automatically decoded and printed :param command: Command to run as str :param ignore_stderr: To not print stderr :param raise_on_return: Run CompletedProcess.check_...
def pushd(directory): """Change working directories in style and stay organized! :param directory: Where do you want to go and remember? :return: saved directory stack """ directory = os.path.expanduser(directory) _saved_paths.insert(0, os.path.abspath(os.getcwd())) os.chdir(directory) ...
def popd(): """Go back to where you once were. :return: saved directory stack """ try: directory = _saved_paths.pop(0) except IndexError: return [os.getcwd()] os.chdir(directory) return [directory] + _saved_paths
def ls(params="", directory=".", printed=True): """Know the best python implantation of ls? It's just to subprocess ls... (uses dir on windows). :param params: options to pass to ls or dir :param directory: if not this directory :param printed: If you're using this, you probably wanted it just prin...
def find(name=None, ext=None, directory=".", match_case=False, disable_glob=False, depth=None): """ Designed for the interactive interpreter by making default order of find_files faster. :param name: Part of the file name :param ext: Extensions of the file you are looking for :param direct...
def head(file_path, lines=10, encoding="utf-8", printed=True, errors='strict'): """ Read the first N lines of a file, defaults to 10 :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on binary :par...
def tail(file_path, lines=10, encoding="utf-8", printed=True, errors='strict'): """ A really silly way to get the last N lines, defaults to 10. :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on bin...
def cp(src, dst, overwrite=False): """ Copy files to a new location. :param src: list (or string) of paths of files to copy :param dst: file or folder to copy item(s) to :param overwrite: IF the file already exists, should I overwrite it? """ if not isinstance(src, list): src = [sr...
def cut(string, characters=2, trailing="normal"): """ Split a string into a list of N characters each. .. code:: python reusables.cut("abcdefghi") # ['ab', 'cd', 'ef', 'gh', 'i'] trailing gives you the following options: * normal: leaves remaining characters in their own last pos...
def int_to_roman(integer): """ Convert an integer into a string of roman numbers. .. code: python reusables.int_to_roman(445) # 'CDXLV' :param integer: :return: roman string """ if not isinstance(integer, int): raise ValueError("Input integer must be of type int")...
def roman_to_int(roman_string): """ Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer """ roman_string = roman_string.upper().strip() if "IIII" in roman_...
def int_to_words(number, european=False): """ Converts an integer or float to words. .. code: python reusables.int_to_number(445) # 'four hundred forty-five' reusables.int_to_number(1.45) # 'one and forty-five hundredths' :param number: String, integer, or float to co...
def filter_osm_file(): """ Downloads (and compiles) osmfilter tool from web and calls that osmfilter to only filter out only the road elements. """ print_info('Filtering OSM file...') start_time = time.time() if check_osmfilter(): # params = '--keep="highway=motorway =motorway...
def task_list(): """ Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task Compiles a readable list for Job model task choices """ try: jobs_module = settings.RQ_JOBS_MODULE except AttributeError: raise ImproperlyConfigured(_("You have to define RQ_JOBS_MODULE...
def rq_job(self): """The last RQ Job this ran on""" if not self.rq_id or not self.rq_origin: return try: return RQJob.fetch(self.rq_id, connection=get_connection(self.rq_origin)) except NoSuchJobError: return
def rq_link(self): """Link to Django-RQ status page for this job""" if self.rq_job: url = reverse('rq_job_detail', kwargs={'job_id': self.rq_id, 'queue_index': queue_index_by_name(self.rq_origin)}) return '<a href="{}">{}</a>'.format(url, self.rq_id)
def rq_task(self): """ The function to call for this task. Config errors are caught by tasks_list() already. """ task_path = self.task.split('.') module_name = '.'.join(task_path[:-1]) task_name = task_path[-1] module = importlib.import_module(module_name...
def fix_module(job): """ Fix for tasks without a module. Provides backwards compatibility with < 0.1.5 """ modules = settings.RQ_JOBS_MODULE if not type(modules) == tuple: modules = [modules] for module in modules: try: module_match = importlib.import_module(module) ...
async def drop_model_tables(models, **drop_table_kwargs): """Drop tables for all given models (in the right order).""" for m in reversed(sort_models_topologically(models)): await m.drop_table(**drop_table_kwargs)
async def model_to_dict(model, recurse=True, backrefs=False, only=None, exclude=None, seen=None, extra_attrs=None, fields_from_query=None, max_depth=None): """ Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether for...
async def extract_rows(self, file_or_name, **reader_kwargs): """ Extract `self.sample_size` rows from the CSV file and analyze their data-types. :param str file_or_name: A string filename or a file handle. :param reader_kwargs: Arbitrary parameters to pass to the CSV reader. ...
def get_checks(self): """Return a list of functions to use when testing values.""" return [ self.is_date, self.is_datetime, self.is_integer, self.is_float, self.default]
def analyze(self, rows): """ Analyze the given rows and try to determine the type of value stored. :param list rows: A list-of-lists containing one or more rows from a csv file. :returns: A list of peewee Field objects for each column in the CSV. """ ...
def clean_text(self, text): '''Clean text using bleach.''' if text is None: return '' text = re.sub(ILLEGAL_CHARACTERS_RE, '', text) if '<' in text or '&lt' in text: text = clean(text, tags=self.tags, strip=self.strip) return unescape(text)
def path(self, category = None, image = None, feature = None): """ Constructs the path to categories, images and features. This path function assumes that the following storage scheme is used on the hard disk to access categories, images and features: - categories: /impath/categor...
def get_image(self, cat, img): """ Loads an image from disk. """ filename = self.path(cat, img) data = [] if filename.endswith('mat'): data = loadmat(filename)['output'] else: data = imread(filename) if self.size is not None: return imr...
def get_feature(self, cat, img, feature): """ Load a feature from disk. """ filename = self.path(cat, img, feature) data = loadmat(filename) name = [k for k in list(data.keys()) if not k.startswith('__')] if self.size is not None: return imresize(data[...
def save_image(self, cat, img, data): """Saves a new image.""" filename = self.path(cat, img) mkdir(filename) if type(data) == np.ndarray: data = Image.fromarray(data).convert('RGB') data.save(filename)
def save_feature(self, cat, img, feature, data): """Saves a new feature.""" filename = self.path(cat, img, feature) mkdir(filename) savemat(filename, {'output':data})
def factorise_field(dm, field_name, boundary_char = None, parameter_name=None): """This removes a common beginning from the data of the fields, placing the common element in a parameter and the different endings in the fields. if parameter_name is None, then it will be <field_name>_common. So ...
def randsample(vec, nr_samples, with_replacement = False): """ Draws nr_samples random samples from vec. """ if not with_replacement: return np.random.permutation(vec)[0:nr_samples] else: return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)]
def calc_resize_factor(prediction, image_size): """ Calculates how much prediction.shape and image_size differ. """ resize_factor_x = prediction.shape[1] / float(image_size[1]) resize_factor_y = prediction.shape[0] / float(image_size[0]) if abs(resize_factor_x - resize_factor_y) > 1.0/image_size...
def dict_2_mat(data, fill = True): """ Creates a NumPy array from a dictionary with only integers as keys and NumPy arrays as values. Dimension 0 of the resulting array is formed from data.keys(). Missing values in keys can be filled up with np.nan (default) or ignored. Parameters ---------...
def dict_fun(data, function): """ Apply a function to all values in a dictionary, return a dictionary with results. Parameters ---------- data : dict a dictionary whose values are adequate input to the second argument of this function. function : function a function...
def snip_string_middle(string, max_len=20, snip_string='...'): """ >>> snip_string_middle('this is long', 8) 'th...ong' >>> snip_string_middle('this is long', 12) 'this is long' >>> snip_string_middle('this is long', 8, '~') 'thi~long' """ #warn('use snip_string() instead', Dep...
def snip_string(string, max_len=20, snip_string='...', snip_point=0.5): """ Snips a string so that it is no longer than max_len, replacing deleted characters with the snip_string. The snip is done at snip_point, which is a fraction between 0 and 1, indicating relatively where along the string to sni...
def find_common_beginning(string_list, boundary_char = None): """Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char. ...
def factorise_strings (string_list, boundary_char=None): """Given a list of strings, finds the longest string that is common to the *beginning* of all strings in the list and returns a new list whose elements lack this common beginning. boundary_char defines a boundary that must be preserved, so th...
def load(path, variable='Datamat'): """ Load datamat at path. Parameters: path : string Absolute path of the file to load from. """ f = h5py.File(path,'r') try: dm = fromhdf5(f[variable]) finally: f.close() return dm
def VectorFactory(fields, parameters, categories = None): ''' Creates a datamat from a dictionary that contains lists/arrays as values. Input: fields: Dictionary The values will be used as fields of the datamat and the keys as field names. parameters: Dictionary ...
def filter(self, index): #@ReservedAssignment """ Filters a datamat by different aspects. This function is a device to filter the datamat by certain logical conditions. It takes as input a logical array (contains only True or False for every datapoint) and kicks out all datapoin...
def copy(self): """ Returns a copy of the datamat. """ return self.filter(np.ones(self._num_fix).astype(bool))
def save(self, path): """ Saves Datamat to path. Parameters: path : string Absolute path of the file to save to. """ f = h5py.File(path, 'w') try: fm_group = f.create_group('Datamat') for field in self.fieldnames(): ...
def set_param(self, key, value): """ Set the value of a parameter. """ self.__dict__[key] = value self._parameters[key] = value
def by_field(self, field): """ Returns an iterator that iterates over unique values of field Parameters: field : string Filters the datamat for every unique value in field and yields the filtered datamat. Returns: datamat : Datamat...
def by_cat(self): """ Iterates over categories and returns a filtered datamat. If a categories object is attached, the images object for the given category is returned as well (else None is returned). Returns: (datamat, categories) : A tuple that contains first the ...
def by_filenumber(self): """ Iterates over categories and returns a filtered datamat. If a categories object is attached, the images object for the given category is returned as well (else None is returned). Returns: (datamat, categories) : A tuple that contains fir...
def add_field(self, name, data): """ Add a new field to the datamat. Parameters: name : string Name of the new field data : list Data for the new field, must be same length as all other fields. """ if name in self._fields: ...
def add_field_like(self, name, like_array): """ Add a new field to the Datamat with the dtype of the like_array and the shape of the like_array except for the first dimension which will be instead the field-length of this Datamat. """ new_shape = list(like_array.shape) ...
def annotate (self, src_dm, data_field, key_field, take_first=True): """ Adds a new field (data_field) to the Datamat with data from the corresponding field of another Datamat (src_dm). This is accomplished through the use of a key_field, which is used to determine how the data is c...
def rm_field(self, name): """ Remove a field from the datamat. Parameters: name : string Name of the field to be removed """ if not name in self._fields: raise ValueError self._fields.remove(name) del self.__dict__[name]
def add_parameter(self, name, value): """ Adds a parameter to the existing Datamat. Fails if parameter with same name already exists or if name is otherwise in this objects ___dict__ dictionary. """ if name in self._parameters: raise ValueError("'%s' is alrea...
def rm_parameter(self, name): """ Removes a parameter to the existing Datamat. Fails if parameter doesn't exist. """ if name not in self._parameters: raise ValueError("no '%s' parameter found" % (name)) del self._parameters[name] del self.__dict__[na...
def parameter_to_field(self, name): """ Promotes a parameter to a field by creating a new array of same size as the other existing fields, filling it with the current value of the parameter, and then removing that parameter. """ if name not in self._parameters: ...
def join(self, fm_new, minimal_subset=True): """ Adds content of a new Datamat to this Datamat. If a parameter of the Datamats is not equal or does not exist in one, it is promoted to a field. If the two Datamats have different fields then the elements for the Datamats ...
def makeAngLenHist(ad, ld, fm = None, collapse=True, fit=spline_base.fit2d): """ Histograms and performs a spline fit on the given data, usually angle and length differences. Parameters: ad : array The data to be histogrammed along the x-axis. May range from -180 t...