sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
Set up a file handler to add to a logger. :param file_path: file to write the log to, defaults to out.log :param level: logging level to set handler at :param log_format: formatter to use :param handler: logging handler to use, defaults to FileHandler :param handler_kwargs: options to pass to the h...
entailment
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...
Grabs the specified logger and adds wanted handlers to it. Will default to adding a stream handler. :param module_name: logger name to use :param level: logging level to set logger at :param stream: stream to log to, or None :param file_path: file path to log to, or None :param log_format: form...
entailment
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...
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 use, defaults to sys.stderr :param level: logging level to set handler at :param log_format: formatter to use
entailment
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...
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 log to :param level: logging level to set handler at :param log_format: formatter to use
entailment
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 ...
Adds a rotating 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 log to :param level: logging level to set handler at :param log_format: log formatter :param max_bytes: Max file size in bytes before rota...
entailment
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...
Adds a timed rotating file handler to the specified logger. Defaults to weekly rotation, with 5 backups. :param logger: logging name or object to modify, defaults to root logger :param file_path: path to file to log to :param level: logging level to set handler at :param log_format: log formatter ...
entailment
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...
Remove only stream handlers from the specified logger :param logger: logging name or object to modify, defaults to root logger
entailment
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...
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
entailment
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...
Safely remove all handlers from the logger :param logger: logging name or object to modify, defaults to root logger
entailment
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) ...
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)
entailment
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...
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
entailment
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 ...
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 @reusables.unique(max_retries=100) def poor_uuid(): return random.randint(0, 10) print([p...
entailment
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) ...
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) @reusables.time_it(message="test_1 ...
entailment
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 ...
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 reusables.add_stream_handler('reusables') @re...
entailment
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 ...
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 func(10) print(my_queue.get()) # 1...
entailment
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(): ...
Wrapper. Log the traceback to any exceptions raised. Possible to raise custom exception. .. code :: python @reusables.log_exception() def test(): raise Exception("Bad") # 2016-12-26 12:38:01,381 - reusables ERROR Exception in test - Bad # Traceback (most recent ...
entailment
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...
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.__name__} raised {exception} when called with {args}") @reusables.catch_it...
entailment
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...
Retry a function if an exception is raised, or if output_check returns False. Message format options: {func} {args} {kwargs} :param exceptions: tuple of exceptions to catch :param tries: number of tries to retry the function :param wait: time to wait between executions in seconds :param handle...
entailment
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...
Automatically detect archive type and extract all files to specified path. .. code:: python import os os.listdir(".") # ['test_structure.zip'] reusables.extract("test_structure.zip") os.listdir(".") # [ 'test_structure', 'test_structure.zip'] :param archive...
entailment
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...
Archive a list of files (or files inside a folder), can chose between - zip - tar - gz (tar.gz, tgz) - bz2 (tar.bz2) .. code:: python reusables.archive(['reusables', '.travis.yml'], name="my_archive.bz2") # 'C:\\Users\\Me\\Reusables\\m...
entailment
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...
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_csv(my_list, "example.csv") example.csv ...
entailment
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...
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 csv_file: Path to CSV file as str :r...
entailment
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 ...
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 json.load command :return: Dictionary
entailment
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:: ...
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:: { "key_1": "val_1", "key_for_dict":...
entailment
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). ...
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). .. code:: python reusables.config_dict(os.path.join("test", "data", "test_config....
entailment
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")) ...
Return configuration options as a Namespace. .. code:: python reusables.config_namespace(os.path.join("test", "data", "test_config.ini")) # <Namespace: {'General': {'example': 'A regul...> :param config_file: path or paths to the files location...
entailment
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...
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: walk generator
entailment
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': {}}, ...
Return a directories contents as a dictionary hierarchy. .. code:: python reusables.os_tree(".") # {'doc': {'build': {'doctrees': {}, # 'html': {'_sources': {}, '_static': {}}}, # 'source': {}}, # 'reusables': {'__pycache__': {}}, # 'test...
entailment
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...
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 function is designed to be non memory intensive. .. code:: python reusables....
entailment
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...
Walk through a file directory and return an iterator of files that match requirements. Will autodetect if name has glob as magic characters. Note: For the example below, you can use find_files_list to return as a list, this is simply an easy way to show the output. .. code:: python list(r...
entailment
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...
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 would be removed :param ignore_errors: Permissions are a pain, just ignore if you blocked :param enable_scandir: on python < 3.5 enable e...
entailment
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 ...
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 removed :param ignore_errors: Permissions are a pain, just ignore if you blocked :param enable_scandir: on python < 3.5 enab...
entailment
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...
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 before progressing to more extensive ones, in order they are: 1. File si...
entailment
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 ...
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 print(dups) # [['C:\\Users\\Me\\Pictures\\IMG_20161127.jpg', ...
entailment
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...
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' instead of '**kwargs' but stupider versions ...
entailment
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...
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 kwargs: 'safe', make them into a safe path i...
entailment
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...
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 :return: boolean if it is a safe file name
entailment
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 :...
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 :param replacement: character to use as a replacement of ba...
entailment
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 ...
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 to use in place of bad characters :return: a s...
entailment
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 ...
Blocking request to change number of running tasks
entailment
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(): ...
Hard stop the server and sub process
entailment
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, ...
Get general information about the state of the class
entailment
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() ...
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.
entailment
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) ...
Start the main loop as a background process. *nix only
entailment
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_...
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_returncode() :param timeout: timeout to pass to communicate if python 3 :param encoding: How the outpu...
entailment
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) ...
Change working directories in style and stay organized! :param directory: Where do you want to go and remember? :return: saved directory stack
entailment
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
Go back to where you once were. :return: saved directory stack
entailment
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...
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 printed :return: if not printed, you can parse it yours...
entailment
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...
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 directory: Top location to recursively search for matching files :param match_case: If name has to be a direct matc...
entailment
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...
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 :param printed: Automatically print the lines instead of returning it :param errors: Decoding errors:...
entailment
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...
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 binary :param printed: Automatically print the lines instead of returning it :param errors: Deco...
entailment
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...
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?
entailment
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...
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 position * remove: return the list without the remainder char...
entailment
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")...
Convert an integer into a string of roman numbers. .. code: python reusables.int_to_roman(445) # 'CDXLV' :param integer: :return: roman string
entailment
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_...
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
entailment
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...
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 convert to words. The decimal can only be up to ...
entailment
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...
Downloads (and compiles) osmfilter tool from web and calls that osmfilter to only filter out only the road elements.
entailment
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...
Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task Compiles a readable list for Job model task choices
entailment
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
The last RQ Job this ran on
entailment
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)
Link to Django-RQ status page for this job
entailment
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...
The function to call for this task. Config errors are caught by tasks_list() already.
entailment
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) ...
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
entailment
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)
Drop tables for all given models (in the right order).
entailment
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...
Convert a model instance (and any related objects) to a dictionary. :param bool recurse: Whether foreign-keys should be recursed. :param bool backrefs: Whether lists of related objects should be recursed. :param only: A list (or set) of field instances indicating which fields should be included. ...
entailment
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. ...
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. :returns: A 2-tuple containing a list of headers and list of rows ...
entailment
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]
Return a list of functions to use when testing values.
entailment
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. """ ...
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.
entailment
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)
Clean text using bleach.
entailment
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...
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/category - images: /impath/category/category_image.png -...
entailment
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...
Loads an image from disk.
entailment
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[...
Load a feature from disk.
entailment
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)
Saves a new image.
entailment
def save_feature(self, cat, img, feature, data): """Saves a new feature.""" filename = self.path(cat, img, feature) mkdir(filename) savemat(filename, {'output':data})
Saves a new feature.
entailment
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 ...
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 far, it's probably only useful for the file_name. TODO: remove field entirely ...
entailment
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)]
Draws nr_samples random samples from vec.
entailment
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...
Calculates how much prediction.shape and image_size differ.
entailment
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 ---------...
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 ---------- data : dict a dictionary with int...
entailment
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...
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 that takes one argument Returns ...
entailment
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...
>>> 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'
entailment
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...
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 snip. snip_point of 0.5 would be the middle. >>> snip_string('this is long', 8)...
entailment
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. ...
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.
entailment
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...
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 that the common string removed must end with this char. ...
entailment
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
Load datamat at path. Parameters: path : string Absolute path of the file to load from.
entailment
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 ...
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 A dictionary whose values are added as parameters. Keys are us...
entailment
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...
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 datapoints for which the array says False. The logical array can c...
entailment
def copy(self): """ Returns a copy of the datamat. """ return self.filter(np.ones(self._num_fix).astype(bool))
Returns a copy of the datamat.
entailment
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(): ...
Saves Datamat to path. Parameters: path : string Absolute path of the file to save to.
entailment
def set_param(self, key, value): """ Set the value of a parameter. """ self.__dict__[key] = value self._parameters[key] = value
Set the value of a parameter.
entailment
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...
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 that is filtered according to one of the uniqu...
entailment
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 ...
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 filtered datamat (has ...
entailment
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...
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 filtered datamat (has ...
entailment
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: ...
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.
entailment
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) ...
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.
entailment
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...
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 copied. This operation corresponds loosely to an SQL join operation. The two...
entailment
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]
Remove a field from the datamat. Parameters: name : string Name of the field to be removed
entailment
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...
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.
entailment
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...
Removes a parameter to the existing Datamat. Fails if parameter doesn't exist.
entailment
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: ...
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.
entailment
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 ...
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 that did not have the field will be NaN, unless 'minimal_...
entailment
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...
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 to 180. ld : array The data to be histogrammed along the y-axis. ...
entailment