text stringlengths 81 112k |
|---|
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
def l... |
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":... |
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.... |
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... |
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
def _walk(directory, enable_scandir=False, **kwa... |
Return a directories contents as a dictionary hierarchy.
.. code:: python
reusables.os_tree(".")
# {'doc': {'build': {'doctrees': {},
# 'html': {'_sources': {}, '_static': {}}},
# 'source': {}},
# 'reusables': {'__pycache__': {}},
# 'test... |
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.... |
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... |
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... |
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... |
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... |
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',
... |
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
... |
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... |
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
def... |
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... |
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... |
Blocking request to change number of running tasks
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 ValueEr... |
Hard stop the server and sub process
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 ... |
Get general information about the state of the class
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.... |
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.
def main_loop(self, stop_at_empty=False):
"""Blocking function that can be run directly, if so would probably
want to specify '... |
Start the main loop as a background process. *nix only
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.ba... |
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... |
Change working directories in style and stay organized!
:param directory: Where do you want to go and remember?
:return: saved directory stack
def pushd(directory):
"""Change working directories in style and stay organized!
:param directory: Where do you want to go and remember?
:return: saved di... |
Go back to where you once were.
:return: saved directory stack
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... |
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... |
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... |
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:... |
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... |
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?
def cp(src, dst, overwrite=False):
"""
Copy files to a new location.
:param src: list (or str... |
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... |
Convert an integer into a string of roman numbers.
.. code: python
reusables.int_to_roman(445)
# 'CDXLV'
:param integer:
:return: roman string
def int_to_roman(integer):
"""
Convert an integer into a string of roman numbers.
.. code: python
reusables.int_to_roman(4... |
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
def roman_to_int(roman_string):
"""
Converts a string of roman numbers into an integer.
.. code: python
... |
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 ... |
Downloads (and compiles) osmfilter tool from web and
calls that osmfilter to only filter out only the road elements.
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 f... |
Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task
Compiles a readable list for Job model task choices
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_... |
The last RQ Job this ran on
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 |
Link to Django-RQ status page for this job
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 h... |
The function to call for this task.
Config errors are caught by tasks_list() already.
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_pat... |
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
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 mod... |
Drop tables for all given models (in the right order).
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) |
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.
... |
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
... |
Return a list of functions to use when testing values.
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] |
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 analyze(self, rows):
"""
Analyze the gi... |
Clean text using bleach.
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 '<' in text:
text = clean(text, tags=self.tags, strip=self.strip)
return une... |
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
-... |
Loads an image from disk.
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 N... |
Load a feature from disk.
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:
... |
Saves a new image.
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 feature.
def save_feature(self, cat, img, feature, data):
"""Saves a new feature."""
filename = self.path(cat, img, feature)
mkdir(filename)
savemat(filename, {'output':data}) |
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 ... |
Draws nr_samples random samples from vec.
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),... |
Calculates how much prediction.shape and image_size differ.
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])
... |
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... |
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
... |
>>> 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'
def snip_string_middle(string, max_len=20, snip_string='...'):
"""
>>> snip_string_middle('this is long', 8)
'th...ong... |
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)... |
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 find_common_beginning(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 that the
common string removed must end with this char.
... |
Load datamat at path.
Parameters:
path : string
Absolute path of the file to load from.
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:
... |
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... |
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... |
Returns a copy of the datamat.
def copy(self):
"""
Returns a copy of the datamat.
"""
return self.filter(np.ones(self._num_fix).astype(bool)) |
Saves Datamat to path.
Parameters:
path : string
Absolute path of the file to save to.
def save(self, path):
"""
Saves Datamat to path.
Parameters:
path : string
Absolute path of the file to save to.
"""
f = h5py.... |
Set the value of a parameter.
def set_param(self, key, value):
"""
Set the value of a parameter.
"""
self.__dict__[key] = value
self._parameters[key] = value |
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... |
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 ... |
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 ... |
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.
def add_field(self, name, data):
"""
Add a new field to the datamat.
Par... |
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.
def add_field_like(self, name, like_array):
"""
Add a new field to the Datamat with the dtype of the
... |
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... |
Remove a field from the datamat.
Parameters:
name : string
Name of the field to be removed
def rm_field(self, name):
"""
Remove a field from the datamat.
Parameters:
name : string
Name of the field to be removed
"""
... |
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.
def add_parameter(self, name, value):
"""
Adds a parameter to the existing Datamat.
Fails if parameter with same name alread... |
Removes a parameter to the existing Datamat.
Fails if parameter doesn't exist.
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' pa... |
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.
def parameter_to_field(self, name):
"""
Promotes a parameter to a field by creating a new array of sam... |
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_... |
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.
... |
Constructs a (fitted) histogram of the given data.
Parameters:
x_val : array
The data to be histogrammed along the x-axis.
y_val : array
The data to be histogrammed along the y-axis.
fit : function or None, optional
The function to use in order to fi... |
Computes the distribution of angle and length
combinations that were made as first saccades
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
def firstSacDist(fm):
"""
Computes the distribution of angle and length
combinations that ... |
Computes the distribution of trajectory lengths, i.e.
the number of saccades that were made as a part of one trajectory
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
def trajLenDist(fm):
"""
Computes the distribution of trajectory lengt... |
Transforms the given number element into a range of [-180, 180],
which covers all possible angle differences. This method reshifts larger or
smaller numbers that might be the output of other angular calculations
into that range by adding or subtracting 360, respectively.
To make sure that angular data... |
Prepares the data to be replicated. Calculates the second-order length
and angle dependencies between saccades and stores them in a fitted
histogram.
Parameters:
fit : function, optional
The method to use for fitting the histogram
full_H1 : twod... |
Calculates the coordinates after a specific saccade was made.
Parameters:
(x,y) : tuple of floats or ints
The coordinates before the saccade was made
angle : float or int
The angle that the next saccade encloses with the
horizonta... |
Draws a new length- and angle-difference pair and calculates
length and angle absolutes matching the last saccade drawn.
Parameters:
prev_angle : float, optional
The last angle that was drawn in the current trajectory
prev_length : float, optional
... |
Generates a given number of trajectories, using the method sample().
Returns a fixmat with the generated data.
Parameters:
num_samples : int, optional
The number of trajectories that shall be generated.
def sample_many(self, num_samples = 2000):
"""
... |
Draws a trajectory length, first coordinates, lengths, angles and
length-angle-difference pairs according to the empirical distribution.
Each call creates one complete trajectory.
def sample(self):
"""
Draws a trajectory length, first coordinates, lengths, angles and
length-a... |
Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn.
def drawFrom(self, cumsum, r):
"""
Draws a value from a cumulative sum.
... |
Load fixmat at path.
Parameters:
path : string
Absolute path of the file to load from.
def load(path):
"""
Load fixmat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
if 'Fixmat' in f:
... |
Computes a fixation density map for the calling fixmat.
Creates a map the size of the image fixations were recorded on.
Every pixel contains the frequency of fixations
for this image. The fixation map is smoothed by convolution with a
Gaussian kernel to approximate the area with highest processi... |
Computes the relative bias, i.e. the distribution of saccade angles
and amplitudes.
Parameters:
fm : DataMat
The fixation data to use
scale_factor : double
Returns:
2D probability distribution of saccade angles and amplitudes.
def relative_bias(fm, scale_factor = 1, ... |
Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instance of stimuli.Categories, optional
If given, the resulting fixmat provides direct access
... |
Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links data in categories to data in fixmat.
def FixmatFactory(fixmatfile, categories = None, var_name = 'fi... |
Adds feature values of feature 'feature' to all fixations in
the calling fixmat.
For fixations out of the image boundaries, NaNs are returned.
The function generates a new attribute field named with the
string in features that contains an np.array listing feature
values... |
Generates two M x N matrices with M feature values at fixations for
N features. Controls are a random sample out of all non-fixated regions
of an image or fixations of the same subject group on a randomly chosen
image. Fixations are pooled over all subjects in the calling fixmat.
... |
Compute velocity of eye-movements.
Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates
of gaze location. The function assumes that the values in x,y are sampled
continously at a rate specified by 'Hz'.
def get_velocity(samplemat, Hz, blinks=None):
'''
Compute velocity of eye-... |
Detect saccades in a stream of gaze location samples.
Coordinates in samplemat are assumed to be in degrees.
Saccades are detect by a velocity/acceleration threshold approach.
A saccade starts when a) the velocity is above threshold, b) the
acceleration is above acc_thresh at least once during the int... |
Detect Fixation from saccades.
Fixations are defined as intervals between saccades. This function
also calcuates start and end times (in ms) for each fixation.
Input:
samplemat: datamat
Contains the recorded samples and associated metadata.
saccades: ndarray
Logical ... |
Parse a subscription list and return a dict containing the results.
:param parse_obj: A file-like object or a string containing a URL, an
absolute or relative filename, or an XML document.
:type parse_obj: str or file
:param agent: User-Agent header to be sent when requesting a URL
:type agent:... |
Constructs an categories object for all image / category
combinations in the fixmat.
Parameters:
fm: FixMat
Used for extracting valid category/image combination.
loader: loader
Loader that accesses the stimuli for this fixmat
Returns:
Categories object... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.