INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
transposes rows and columns | def pivot(self):
"""
transposes rows and columns
"""
self.op_data = [list(i) for i in zip(*self.ip_data)] |
convert list to key value pairs
This should also create unique id's to allow for any
dataset to be transposed, and then later manipulated
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
should be converted to
ID COLNUM VAL
r1c1, | def key_value_pairs(self):
"""
convert list to key value pairs
This should also create unique id's to allow for any
dataset to be transposed, and then later manipulated
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
should be converted to
ID COLNUM VAL... |
This takes a table of data conaining a person identifier (Name or ID)
and returns a table showing all links based on a common column
Ip table Links by Location Links by Job
NAME Location Job
John Perth Plumber Location,Perth,John,Fred Job,Farmer,Mary,Jane
... | def data_to_links(self, id_col_num, link_col_num, include_links_self='Y'):
"""
This takes a table of data conaining a person identifier (Name or ID)
and returns a table showing all links based on a common column
Ip table Links by Location Links by Job
NAME Lo... |
This is the reverse of data_to_links and takes a links table and
generates a data table as follows
Input Table Output Table
Cat_Name,CAT_val,Person_a,person_b NAME,Location
Location,Perth,John,Fred John,Perth
Location,Perth,John,Cindy ... | def links_to_data(self, col_name_col_num, col_val_col_num, id_a_col_num, id_b_col_num):
"""
This is the reverse of data_to_links and takes a links table and
generates a data table as follows
Input Table Output Table
Cat_Name,CAT_val,Person_a,person_b NAM... |
try each strategy with different amounts | def find_best_plan(self):
"""
try each strategy with different amounts
"""
for plan in self.plans:
for strat in self.strategy:
self.run_plan(plan, strat) |
loads previously exported CSV file to redis database | def load_data(fname):
""" loads previously exported CSV file to redis database """
print('Loading ' + fname + ' to redis')
r = redis.StrictRedis(host = '127.0.0.1', port = 6379, db = 0);
with open(fname, 'r') as f:
for line_num, row in enumerate(f):
if row.strip('') != '':
... |
takes a row from an n3 file and returns the triple
NOTE - currently parses a CSV line already split via
cyc_extract.py | def parse_n3(row, src='csv'):
"""
takes a row from an n3 file and returns the triple
NOTE - currently parses a CSV line already split via
cyc_extract.py
"""
if row.strip() == '':
return '',''
l_root = 'opencyc'
key = ''
val = ''
if src == 'csv':
cols = row.split... |
takes a large data file and produces a HTML summary as html | def summarise_file_as_html(fname):
"""
takes a large data file and produces a HTML summary as html
"""
txt = '<H1>' + fname + '</H1>'
num_lines = 0
print('Reading OpenCyc file - ', fname)
with open(ip_folder + os.sep + fname, 'r') as f:
txt += '<PRE>'
for line in f:
... |
Example to show AIKIF logging of results.
Generates a sequence of random grids and runs the
Game of Life, saving results | def main():
"""
Example to show AIKIF logging of results.
Generates a sequence of random grids and runs the
Game of Life, saving results
"""
iterations = 9 # how many simulations to run
years = 3 # how many times to run each simulation
width = 22 # grid height
... |
run a single game of life for 'years' and log start and
end living cells to aikif | def run_game_of_life(years, width, height, time_delay, silent="N"):
"""
run a single game of life for 'years' and log start and
end living cells to aikif
"""
lfe = mod_grid.GameOfLife(width, height, ['.', 'x'], 1)
set_random_starting_grid(lfe)
lg.record_source(lfe, 'game_of_life_console.py'... |
generate a random grid for game of life using a
set of patterns (just to make it interesting) | def set_random_starting_grid(lfe):
"""
generate a random grid for game of life using a
set of patterns (just to make it interesting)
"""
cls_patterns = mod_grid.GameOfLifePatterns(25)
print(cls_patterns)
exit(0)
patterns = cls_patterns.get_patterns()
for pattern in patterns:
... |
allows display of a game of life on a console via
resetting cursor position to a set point - looks 'ok'
for testing but not production quality. | def print_there(x, y, text):
""""
allows display of a game of life on a console via
resetting cursor position to a set point - looks 'ok'
for testing but not production quality.
"""
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush() |
takes a blob of text and finds delimiter OR guesses
the column positions to parse into a table.
input: txt = blob of text, lines separated by \n
output: res = table of text | def parse_text_to_table(txt):
"""
takes a blob of text and finds delimiter OR guesses
the column positions to parse into a table.
input: txt = blob of text, lines separated by \n
output: res = table of text
"""
res = [] # resulting table
delim = identify_delim(txt)
print('txt to pars... |
assume no delimiter in this file, so guess the best
fixed column widths to split by | def identify_col_pos(txt):
"""
assume no delimiter in this file, so guess the best
fixed column widths to split by
"""
res = []
#res.append(0)
lines = txt.split('\n')
prev_ch = ''
for col_pos, ch in enumerate(lines[0]):
if _is_white_space(ch) is False and _is_white_space(prev_ch) is True:
res.a... |
read a CSV file to list without worrying about odd characters | def load_tbl_from_csv(fname):
"""
read a CSV file to list without worrying about odd characters
"""
import csv
rows_to_load = []
with open(fname, 'r', encoding='cp1252', errors='ignore') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',' )
reader = csv.reader(csvfile)
rows_to_load ... |
reads the characters in txt and returns a dictionary
of all letters | def _get_dict_char_count(txt):
"""
reads the characters in txt and returns a dictionary
of all letters
"""
dct = {}
for letter in txt:
if letter in dct:
dct[letter] += 1
else:
dct[letter] = 1
return dct |
identifies delimiters and returns a count by ROW
in the text file as well as the delimiter value (if any)
The delim is determined if the count of delims is consistant
in all rows. | def identify_delim(txt):
"""
identifies delimiters and returns a count by ROW
in the text file as well as the delimiter value (if any)
The delim is determined if the count of delims is consistant
in all rows.
"""
possible_delims = _get_dict_char_count(txt) # {'C': 3, 'a': 4, 'b': 5, 'c': 6, ',': 6, 'A': ... |
takes a string and truncates to standard form for data matching.
Based on the spec at OpenRefine
https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint
- remove leading and trailing whitespace
- change all characters to their lowercase representation
- remove all punctuation and control... | def fingerprint(txt):
"""
takes a string and truncates to standard form for data matching.
Based on the spec at OpenRefine
https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint
- remove leading and trailing whitespace
- change all characters to their lowercase representation
- remo... |
Updating OS environment variables and current script path and filename. | def update_environment_variables(self, filename):
"""Updating OS environment variables and current script path and filename."""
self.env.update({'PIPELINE_BASH_FILE_ORIGINAL': filename})
filename = os.path.join('/root/scripts', os.path.basename(filename))
self.env.update({'PIPELINE_BASH_... |
Creator function for creating an instance of a Bash. | def creator(entry, config):
"""Creator function for creating an instance of a Bash."""
template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')
with open(template_file) as handle:
template = handle.read()
# all fields are re-rendered vi... |
Creator function for creating an instance of a Docker image script. | def creator(entry, config):
"""Creator function for creating an instance of a Docker image script."""
# writing Dockerfile
dockerfile = render(config.script, model=config.model, env=config.env,
variables=config.variables, item=config.item)
filename = "dockerfi... |
Creates the environment
in your subclassed create function include the line below
super().build(arg1, arg2, arg2, ...) | def create(self, num):
"""
Creates the environment
in your subclassed create function include the line below
super().build(arg1, arg2, arg2, ...)
"""
self.log.record_process('enviroment.py', 'Creating ' + str(num) + ' environments - ' + self.name) |
Simplify redirect of stdout.
Taken from here: https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/ | def stdout_redirector():
"""
Simplify redirect of stdout.
Taken from here: https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/
"""
old_stdout = sys.stdout
sys.stdout = Stream()
try:
yield sys.stdout
finally:
sys.stdout.close()
sys.stdout... |
Generating a temporary file with content.
Args:
content (str): file content (usually a script, Dockerfile, playbook or config file)
prefix (str): the filename starts with this prefix (default: no prefix)
suffix (str): the filename ends with this suffix (default: no suffix)
Returns:
... | def write_temporary_file(content, prefix='', suffix=''):
"""
Generating a temporary file with content.
Args:
content (str): file content (usually a script, Dockerfile, playbook or config file)
prefix (str): the filename starts with this prefix (default: no prefix)
suffix (str): the ... |
Prints filename of a new migration | def print_new(ctx, name, migration_type):
"""Prints filename of a new migration"""
click.echo(ctx.obj.repository.generate_migration_name(name, migration_type)) |
logs the agent details to logfile
unique_name_file (list_agents.txtlist_agents_names.txt) = list of all instances of all agents | def _log_agent_name(self, unique_name_file):
"""
logs the agent details to logfile
unique_name_file (list_agents.txtlist_agents_names.txt) = list of all instances of all agents
"""
agt_list = os.path.join(root_fldr, 'data', unique_name_file)
if os.path.exists(agt_list):
... |
Starts an agent with standard logging | def start(self):
"""
Starts an agent with standard logging
"""
self.running = True
self.status = 'RUNNING'
self.mylog.record_process('agent', self.name + ' - starting') |
set coords of agent in an arbitrary world | def set_coords(self, x=0, y=0, z=0, t=0):
"""
set coords of agent in an arbitrary world
"""
self.coords = {}
self.coords['x'] = x
self.coords['y'] = y
self.coords['z'] = z
self.coords['t'] = t |
Load catchment object from a ``.CD3`` or ``.xml`` file.
If there is also a corresponding ``.AM`` file (annual maximum flow data) or
a ``.PT`` file (peaks over threshold data) in the same folder as the CD3 file, these datasets will also be loaded.
:param file_path: Location of CD3 or xml file
:type fil... | def from_file(file_path, incl_pot=True):
"""
Load catchment object from a ``.CD3`` or ``.xml`` file.
If there is also a corresponding ``.AM`` file (annual maximum flow data) or
a ``.PT`` file (peaks over threshold data) in the same folder as the CD3 file, these datasets will also be loaded.
:param... |
Load catchment object into the database.
A catchment/station number (:attr:`catchment.id`) must be provided. If :attr:`method` is set to `update`, any
existing catchment in the database with the same catchment number will be updated.
:param catchment: New catchment object to replace any existing catchment... | def to_db(catchment, session, method='create', autocommit=False):
"""
Load catchment object into the database.
A catchment/station number (:attr:`catchment.id`) must be provided. If :attr:`method` is set to `update`, any
existing catchment in the database with the same catchment number will be updated.... |
Import an entire folder (incl. sub-folders) into the database
:param path: Folder location
:type path: str
:param session: database session to use, typically `floodestimation.db.Session()`
:type session: :class:`sqlalchemy.orm.session.Session`
:param method: - ``create``: only new catchments will b... | def folder_to_db(path, session, method='create', autocommit=False, incl_pot=True):
"""
Import an entire folder (incl. sub-folders) into the database
:param path: Folder location
:type path: str
:param session: database session to use, typically `floodestimation.db.Session()`
:type session: :cla... |
Retrieves all gauged catchments (incl. catchment descriptors and annual maximum flow data) from the National River
Flow Archive and saves it to a (sqlite) database.
:param session: database session to use, typically `floodestimation.db.Session()`
:type session: :class:`sqlalchemy.orm.session.Session`
:... | def nrfa_to_db(session, method='create', autocommit=False, incl_pot=True):
"""
Retrieves all gauged catchments (incl. catchment descriptors and annual maximum flow data) from the National River
Flow Archive and saves it to a (sqlite) database.
:param session: database session to use, typically `floodes... |
Add catchments from a user folder to the database.
The user folder is specified in the ``config.ini`` file like this::
[import]
folder = path/to/import/folder
If this configuration key does not exist this will be silently ignored.
:param session: database session to use, typically `flood... | def userdata_to_db(session, method='update', autocommit=False):
"""
Add catchments from a user folder to the database.
The user folder is specified in the ``config.ini`` file like this::
[import]
folder = path/to/import/folder
If this configuration key does not exist this will be sile... |
finds the window by caption and returns handle (int) | def get_window_by_caption(caption):
"""
finds the window by caption and returns handle (int)
"""
try:
hwnd = win32gui.FindWindow(None, caption)
return hwnd
except Exception as ex:
print('error calling win32gui.FindWindow ' + str(ex))
return -1 |
sends the text 'txt' to the window handle hwnd using SendMessage | def send_text(hwnd, txt):
"""
sends the text 'txt' to the window handle hwnd using SendMessage
"""
try:
for c in txt:
if c == '\n':
win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32api.SendMessage(hwnd, win32con.WM_KEYUP, win... |
start an app | def launch_app(app_path, params=[], time_before_kill_app=15):
"""
start an app
"""
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print('res = ', res)
if res == 0:
return True
else:
re... |
use shell to bring the application with caption to front | def app_activate(caption):
"""
use shell to bring the application with caption to front
"""
try:
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate(caption)
except Exception as ex:
print('error calling win32com.client.Dispatch (AppActivate)') |
sends the text or keys to the active application using shell
Note, that the imp module shows deprecation warning.
Examples:
shell.SendKeys("^a") # CTRL+A
shell.SendKeys("{DELETE}") # Delete key
shell.SendKeys("hello this is a lot of text with a //") | def send_keys(key_string):
"""
sends the text or keys to the active application using shell
Note, that the imp module shows deprecation warning.
Examples:
shell.SendKeys("^a") # CTRL+A
shell.SendKeys("{DELETE}") # Delete key
shell.SendKeys("hello this is a lot of text with a //"... |
Return a list of catchments sorted by distance to `subject_catchment` **and filtered to only include catchments
suitable for QMED analyses**.
:param subject_catchment: catchment object to measure distances to
:type subject_catchment: :class:`floodestimation.entities.Catchment`
:param li... | def nearest_qmed_catchments(self, subject_catchment, limit=None, dist_limit=500):
"""
Return a list of catchments sorted by distance to `subject_catchment` **and filtered to only include catchments
suitable for QMED analyses**.
:param subject_catchment: catchment object to measure dista... |
Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function`
:param subject_catchment: subject catchment to find similar catchments for
:type subject_catchment: :class:`floodestimation.entities.Catchment`
:param similarity_dist_function: a method retur... | def most_similar_catchments(self, subject_catchment, similarity_dist_function, records_limit=500,
include_subject_catchment='auto'):
"""
Return a list of catchments sorted by hydrological similarity defined by `similarity_distance_function`
:param subject_catchme... |
Reads and parses a sam file.
:param SAMfile: /path/to/file.sam
:param header: logical, if True, reads the header information
:returns: a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ','QUAL' and a list of the headers if header=Tru... | def readSAM(SAMfile,header=False):
"""
Reads and parses a sam file.
:param SAMfile: /path/to/file.sam
:param header: logical, if True, reads the header information
:returns: a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ'... |
Writes a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ','QUAL' into a sam file
:param sam: pandas dataframe to be writen
:param SAMfile: /path/to/file.sam
:returns: nothing | def writeSAM(sam,SAMfile,header=None):
"""
Writes a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ','QUAL' into a sam file
:param sam: pandas dataframe to be writen
:param SAMfile: /path/to/file.sam
:returns: nothing
""... |
returns a string representation of the bias details | def get_bias_details(self):
"""
returns a string representation of the bias details
"""
res = 'Bias File Details\n'
for b in self.bias_details:
if len(b) > 2:
res += b[0].ljust(35)
res += b[1].ljust(35)
res += b[2].ljust... |
Explains a SAM flag.
:param x: flag
:returns: complete SAM flag explanaition | def SAMflags(x):
"""
Explains a SAM flag.
:param x: flag
:returns: complete SAM flag explanaition
"""
flags=[]
if x & 1:
l="1: Read paired"
else:
l="0: Read unpaired"
flags.append(l)
if x & 2 :
l="1: Read mapped in proper pair"
else:
l="0: ... |
returns a weighting from 0 to 1 based on the sources.
Due to fractions multiplying resulting in very small
numbers, adding 0.5 to bias calculations which means
actual range is 0.5 -> 1.5 (still testing)
Note - range should be from 0 - > 1 | def _calculate_bias(self):
"""
returns a weighting from 0 to 1 based on the sources.
Due to fractions multiplying resulting in very small
numbers, adding 0.5 to bias calculations which means
actual range is 0.5 -> 1.5 (still testing)
Note - range should be from ... |
read the bias file based on the short_filename
and return as a dictionary | def _read_bias_rating(self, short_filename):
"""
read the bias file based on the short_filename
and return as a dictionary
"""
res = {}
full_name = os.path.join(root_fldr, 'aikif', 'data', 'ref', short_filename)
lg.record_process('bias.py','reading ' + full_name)
... |
returns the home folder and program root depending on OS | def get_root_folder():
"""
returns the home folder and program root depending on OS
"""
locations = {
'linux':{'hme':'/home/duncan/', 'core_folder':'/home/duncan/dev/src/python/AIKIF'},
'win32':{'hme':'T:\\user\\', 'core_folder':'T:\\user\\dev\\src\\python\\AIKIF'},
'cygwin':{'hme':os.... |
read a simple text file from a private location to get
username and password | def read_credentials(fname):
"""
read a simple text file from a private location to get
username and password
"""
with open(fname, 'r') as f:
username = f.readline().strip('\n')
password = f.readline().strip('\n')
return username, password |
module intended to be imported in most AIKIF utils
to manage folder paths, user settings, etc.
Modify the parameters at the top of this file to suit | def show_config():
"""
module intended to be imported in most AIKIF utils
to manage folder paths, user settings, etc.
Modify the parameters at the top of this file to suit
"""
res = ''
res += '\n---------- Folder Locations ---------\n'
for k,v in fldrs.items():
res += str(k) + ' ... |
return the matrix as a list of lists
raw graph = {'1': ['2', '3', '4'], '2': ['6', '7']}
6 nodes: ['1', '2', '3', '4', '6', '7']
5 links: [['1', '2'], ['1', '3'], ['1', '4'], ['2', '6'], ['2', '7']]
[0, 1, 1, 1, 0, 0]
[1, 0, 0, 0, 1, 1]
[1, 0, 0, 0, 0, 0]
[1, 0,... | def get_adjacency_matrix(self, show_in_console=False):
""" return the matrix as a list of lists
raw graph = {'1': ['2', '3', '4'], '2': ['6', '7']}
6 nodes: ['1', '2', '3', '4', '6', '7']
5 links: [['1', '2'], ['1', '3'], ['1', '4'], ['2', '6'], ['2', '7']]
[0, 1, 1, 1, 0, 0]
... |
Selectes motifs from a meme file based on the number of sites.
:param memeFile: MEME file to be read
:param outFile: MEME file to be written
:param minSites: minimum number of sites each motif needs to have to be valid
:returns: nothing | def filterMotifs(memeFile,outFile, minSites):
"""
Selectes motifs from a meme file based on the number of sites.
:param memeFile: MEME file to be read
:param outFile: MEME file to be written
:param minSites: minimum number of sites each motif needs to have to be valid
:returns: nothing
"""... |
reads the file and cleans into standard text ready for parsing | def _read_file(self):
"""
reads the file and cleans into standard text ready for parsing
"""
self.raw = []
with open(self.fname, 'r') as f:
for line in f:
#print(line)
if line.startswith('#'):
pass # comment
... |
Restore the default configuration and remove the user's config file. | def reset(self):
"""
Restore the default configuration and remove the user's config file.
"""
# Delete user config file
try:
os.remove(self._user_config_file)
except FileNotFoundError:
pass
# Empty and refill the config object
for... |
Write data to user config file. | def save(self):
"""
Write data to user config file.
"""
with open(self._user_config_file, 'w', encoding='utf-8') as f:
self.write(f) |
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param fallback: Fallback/default value
:return: Datetime in UTC
:rtype: :class:`datetime.datetime` | def get_datetime(self, section, option, fallback):
"""
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param fallback: Fallback/default value
:return: Datetime in UTC
:rtype: :class:`datetime.datetim... |
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param value: Datetime value to set
:type value: :class:`datetime.datetime` | def set_datetime(self, section, option, value):
"""
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param value: Datetime value to set
:type value: :class:`datetime.datetime`
"""
self[section... |
General Machine Learning Formulas
Intermezzo - computing Logarithms
log2(x) = y <=> 2^y = x
Definition of Entropy
k
E = - SUM ( p[i] log2(p[i])
i=1
where
k = possible values enumerated 1,2,...,k
p[i] = c[i] / n is the fraction of elements having ... | def ml_entropy(lst):
"""
General Machine Learning Formulas
Intermezzo - computing Logarithms
log2(x) = y <=> 2^y = x
Definition of Entropy
k
E = - SUM ( p[i] log2(p[i])
i=1
where
k = possible values enumerated 1,2,...,k
p[i] = c[i] / n is... |
Read the magic file | def _magic_data(filename=os.path.join(here, 'magic_data.json')):
""" Read the magic file"""
with open(filename) as f:
data = json.load(f)
headers = [_create_puremagic(x) for x in data['headers']]
footers = [_create_puremagic(x) for x in data['footers']]
return headers, footers |
The length of the largest magic string + its offset | def _max_lengths():
""" The length of the largest magic string + its offset"""
max_header_length = max([len(x.byte_match) + x.offset
for x in magic_header_array])
max_footer_length = max([len(x.byte_match) + abs(x.offset)
for x in magic_footer_array]... |
Rough confidence based on string length and file extension | def _confidence(matches, ext=None):
""" Rough confidence based on string length and file extension"""
results = []
for match in matches:
con = (0.8 if len(match.extension) > 9 else
float("0.{0}".format(len(match.extension))))
if ext == match.extension:
con = 0.9
... |
Attempt to identify 'data' by its magic numbers | def _identify_all(header, footer, ext=None):
""" Attempt to identify 'data' by its magic numbers"""
# Capture the length of the data
# That way we do not try to identify bytes that don't exist
matches = list()
for magic_row in magic_header_array:
start = magic_row.offset
end = magic... |
Discover what type of file it is based on the incoming string | def _magic(header, footer, mime, ext=None):
""" Discover what type of file it is based on the incoming string """
if not header:
raise ValueError("Input was empty")
info = _identify_all(header, footer, ext)[0]
if mime:
return info.mime_type
return info.extension if not \
isin... |
Grab the start and end of the file | def _file_details(filename):
""" Grab the start and end of the file"""
max_head, max_foot = _max_lengths()
with open(filename, "rb") as fin:
head = fin.read(max_head)
try:
fin.seek(-max_foot, os.SEEK_END)
except IOError:
fin.seek(0)
foot = fin.read()
... |
Scan a filename for it's extension.
:param filename: string of the filename
:return: the extension off the end (empty string if it can't find one) | def ext_from_filename(filename):
""" Scan a filename for it's extension.
:param filename: string of the filename
:return: the extension off the end (empty string if it can't find one)
"""
try:
base, ext = filename.lower().rsplit(".", 1)
except ValueError:
return ''
ext = ".{... |
Opens file, attempts to identify content based
off magic number and will return the file extension.
If mime is True it will return the mime type instead.
:param filename: path to file
:param mime: Return mime, not extension
:return: guessed extension or mime | def from_file(filename, mime=False):
""" Opens file, attempts to identify content based
off magic number and will return the file extension.
If mime is True it will return the mime type instead.
:param filename: path to file
:param mime: Return mime, not extension
:return: guessed extension or ... |
Reads in string, attempts to identify content based
off magic number and will return the file extension.
If mime is True it will return the mime type instead.
If filename is provided it will be used in the computation.
:param string: string representation to check
:param mime: Return mime, not exte... | def from_string(string, mime=False, filename=None):
""" Reads in string, attempts to identify content based
off magic number and will return the file extension.
If mime is True it will return the mime type instead.
If filename is provided it will be used in the computation.
:param string: string re... |
Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first.
:param filename: path to file
:return: list of possible matches, highest confidence first | def magic_file(filename):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first.
:param filename: path to file
:return: list of possible matches, highest confidence first
"""
head, foot = _file_details(filename)
if not head:
raise ValueError... |
Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first
If filename is provided it will be used in the computation.
:param string: string representation to check
:param filename: original filename
:return: list of possible matches, highest confidence first | def magic_string(string, filename=None):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first
If filename is provided it will be used in the computation.
:param string: string representation to check
:param filename: original filename
:return: list of ... |
Reads a GTF file and labels the respective columns in agreement with GTF file standards:
'seqname','source','feature','start','end','score','strand','frame','attribute'.
:param infile: path/to/file.gtf
:returns: a Pandas dataframe of the respective GTF | def readGTF(infile):
"""
Reads a GTF file and labels the respective columns in agreement with GTF file standards:
'seqname','source','feature','start','end','score','strand','frame','attribute'.
:param infile: path/to/file.gtf
:returns: a Pandas dataframe of the respective GTF
"""
df=pd.re... |
Returns a field of choice from the attribute column of the GTF
:param field: field to be retrieved
:returns: a Pandas dataframe with one columns containing the field of choice | def retrieve_GTF_field(field,gtf):
"""
Returns a field of choice from the attribute column of the GTF
:param field: field to be retrieved
:returns: a Pandas dataframe with one columns containing the field of choice
"""
inGTF=gtf.copy()
def splits(x):
l=x.split(";")
l=[ s.sp... |
List the type of attributes in a the attribute section of a GTF file
:param inGTF: GTF dataframe to be analysed
:returns: a list of attributes present in the attribute section | def attributesGTF(inGTF):
"""
List the type of attributes in a the attribute section of a GTF file
:param inGTF: GTF dataframe to be analysed
:returns: a list of attributes present in the attribute section
"""
df=pd.DataFrame(inGTF['attribute'].str.split(";").tolist())
desc=[]
for i in... |
Reads an extracts all attributes in the attributes section of a GTF and constructs a new dataframe wiht one collumn per attribute instead of the attributes column
:param inGTF: GTF dataframe to be parsed
:returns: a dataframe of the orignal input GTF with attributes parsed. | def parseGTF(inGTF):
"""
Reads an extracts all attributes in the attributes section of a GTF and constructs a new dataframe wiht one collumn per attribute instead of the attributes column
:param inGTF: GTF dataframe to be parsed
:returns: a dataframe of the orignal input GTF with attributes parsed.
... |
Write a GTF dataframe into a file
:param inGTF: GTF dataframe to be written. It should either have 9 columns with the last one being the "attributes" section or more than 9 columns where all columns after the 8th will be colapsed into one.
:param file_path: path/to/the/file.gtf
:returns: nothing | def writeGTF(inGTF,file_path):
"""
Write a GTF dataframe into a file
:param inGTF: GTF dataframe to be written. It should either have 9 columns with the last one being the "attributes" section or more than 9 columns where all columns after the 8th will be colapsed into one.
:param file_path: path/to/th... |
Transform a GTF dataframe into a bed dataframe
:param inGTF: GTF dataframe for transformation
:param name: field of the GTF data frame to be use for the bed 'name' positon
returns: a bed dataframe with the corresponding bed fiels: 'chrom','chromStart','chromEnd','name','score','strand' | def GTFtoBED(inGTF,name):
"""
Transform a GTF dataframe into a bed dataframe
:param inGTF: GTF dataframe for transformation
:param name: field of the GTF data frame to be use for the bed 'name' positon
returns: a bed dataframe with the corresponding bed fiels: 'chrom','chromStart','chromEnd','name... |
Gets all positions of all bases in an exon
:param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry.
df must contain 'seqname','feature','start','end','strand','frame','gene_id',
'transcript_id','exon_id','exon_number']
:param feature: feature up... | def MAPGenoToTrans(parsedGTF,feature):
"""
Gets all positions of all bases in an exon
:param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry.
df must contain 'seqname','feature','start','end','strand','frame','gene_id',
'transcript_id','exo... |
Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923910:'234,235,236,1021,..'}
:param refCol: header of the reference c... | def GetTransPosition(df,field,dic,refCol="transcript_id"):
"""
Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923... |
download a file from a public website with no logon required
output = open(filename,'wb')
output.write(request.urlopen(url).read())
output.close() | def download_file_no_logon(url, filename):
"""
download a file from a public website with no logon required
output = open(filename,'wb')
output.write(request.urlopen(url).read())
output.close()
"""
import urllib.request
#url = "http://www.google.com/"
request = urllib.reques... |
having problems with urllib on a specific site so trying requests | def get_protected_page(url, user, pwd, filename):
"""
having problems with urllib on a specific site so trying requests
"""
import requests
r = requests.get(url, auth=(user, pwd))
print(r.status_code)
if r.status_code == 200:
print('success')
with open(filename, 'wb') as fd:
... |
Currently fails behind proxy...
# https://docs.python.org/3/library/urllib.request.html#examples | def download_file_proxy(p_url, p_op_file, p_username, p_password, proxies):
"""
Currently fails behind proxy...
# https://docs.python.org/3/library/urllib.request.html#examples
"""
chunk_size=4096
import requests
r = requests.get(p_url, auth=(p_username, p_password), proxies=proxies)
#pr... |
Currently not working...
# https://docs.python.org/3/library/urllib.request.html#examples
# Create an OpenerDirector with support for Basic HTTP Authentication... | def download_file(p_realm, p_url, p_op_file, p_username, p_password):
"""
Currently not working...
# https://docs.python.org/3/library/urllib.request.html#examples
# Create an OpenerDirector with support for Basic HTTP Authentication...
"""
auth_handler = urllib.request.HTTPBasicAuthHandler()
... |
parse the 'rawFilesTable.txt' file into a pandas dataframe | def read_rawFilesTable(filename):
"""parse the 'rawFilesTable.txt' file into a pandas dataframe"""
exp = pd.read_table(filename)
expected_columns = {'File', 'Exists', 'Size', 'Data format', 'Parameter group', 'Experiment', 'Fraction'}
found_columns = set(exp.columns)
if len(expected_columns - found_... |
Add an instance method or function
Args:
m: The instance method or function to store | def add_method(self, m, **kwargs):
"""Add an instance method or function
Args:
m: The instance method or function to store
"""
if isinstance(m, types.FunctionType):
self['function', id(m)] = m
else:
f, obj = get_method_vars(m)
wrke... |
Remove an instance method or function if it exists
Args:
m: The instance method or function to remove | def del_method(self, m):
"""Remove an instance method or function if it exists
Args:
m: The instance method or function to remove
"""
if isinstance(m, types.FunctionType) and not iscoroutinefunction(m):
wrkey = ('function', id(m))
else:
f, obj... |
Remove any stored instance methods that belong to an object
Args:
obj: The instance object to remove | def del_instance(self, obj):
"""Remove any stored instance methods that belong to an object
Args:
obj: The instance object to remove
"""
to_remove = set()
for wrkey, _obj in self.iter_instances():
if obj is _obj:
to_remove.add(wrkey)
... |
Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object | def iter_instances(self):
"""Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object
"""
for wrkey in set(self.keys()):
obj = self.get(wrkey)
if obj is None:
... |
Iterate over stored functions and instance methods
Yields:
Instance methods or function objects | def iter_methods(self):
"""Iterate over stored functions and instance methods
Yields:
Instance methods or function objects
"""
for wrkey, obj in self.iter_instances():
f, obj_id = wrkey
if f == 'function':
yield self[wrkey]
... |
reads the subject file to a list, to confirm config is setup | def load_data_subject_areas(subject_file):
"""
reads the subject file to a list, to confirm config is setup
"""
lst = []
if os.path.exists(subject_file):
with open(subject_file, 'r') as f:
for line in f:
lst.append(line.strip())
else:
print('MISSING DA... |
reads the ontology yaml file and does basic verifcation | def check_ontology(fname):
"""
reads the ontology yaml file and does basic verifcation
"""
with open(fname, 'r') as stream:
y = yaml.safe_load(stream)
import pprint
pprint.pprint(y) |
top level function used for new data processing which attempts
to find a level in a heirarchy and return the key and filename
usage res = FindOntology('file') # returns 'SYSTEM-PC-FILE' | def find_ontology(self, txt):
"""
top level function used for new data processing which attempts
to find a level in a heirarchy and return the key and filename
usage res = FindOntology('file') # returns 'SYSTEM-PC-FILE'
"""
totFound = 0
searchString = txt.upper()... |
top level function used to simply return the
ONE ACTUAL string used for data types | def find_type(self, txt):
"""
top level function used to simply return the
ONE ACTUAL string used for data types
"""
searchString = txt.upper()
match = 'Unknown'
for i in self.lst_type:
if searchString in i:
match = i
return ma... |
returns the file based on dataType and subjectArea | def get_full_filename(self, dataType, subjectArea):
"""
returns the file based on dataType and subjectArea
"""
return dataPath + os.sep + 'core' + os.sep + dataType + '_' + subjectArea + '.CSV' |
Parses a database URL in this format:
[database type]://[username]:[password]@[host]:[port]/[database name]
or, for cloud SQL:
[database type]://[username]:[password]@[project_id]:[instance_name]/[database name] | def parse(url):
"""
Parses a database URL in this format:
[database type]://[username]:[password]@[host]:[port]/[database name]
or, for cloud SQL:
[database type]://[username]:[password]@[project_id]:[instance_name]/[database name]
"""
config = {}
url = urlparse.urlparse(url)
# Re... |
Get a logger by name. | def get_logger(name):
"""Get a logger by name."""
if name is None:
return NoLogger()
logger = logging.getLogger(name)
if Logger.use_external_configuration:
logger.propagate = False
return logger |
read the list of thoughts from a text file | def load_plan(self, fname):
""" read the list of thoughts from a text file """
with open(fname, "r") as f:
for line in f:
if line != '':
tpe, txt = self.parse_plan_from_string(line)
#print('tpe= "' + tpe + '"', txt)
... |
adds a constraint for the plan | def add_constraint(self, name, tpe, val):
"""
adds a constraint for the plan
"""
self.constraint.append([name, tpe, val]) |
calculates basic stats on the MapRule elements of the maps
to give a quick overview. | def get_maps_stats(self):
"""
calculates basic stats on the MapRule elements of the maps
to give a quick overview.
"""
tpes = {}
for m in self.maps:
if m.tpe in tpes:
tpes[m.tpe] += 1
else:
tpes[m.tpe] = 1
re... |
load the rules from file | def load_rules(self):
"""
load the rules from file
"""
self.maps = []
with open(self.map_file, 'r') as f:
for line in f:
if line.strip(' ')[0:1] != '#':
rule = MapRule(line)
#print('rule = ', rule)
... |
save the rules to file after web updates or program changes | def save_rules(self, op_file):
"""
save the rules to file after web updates or program changes
"""
with open(op_file, 'w') as f:
for m in self.maps:
f.write(m.format_for_file_output()) |
takes the filename to be read and uses the maps setup
on class instantiation to process the file.
This is a top level function and uses self.maps which
should be the column descriptions (in order). | def process_raw_file(self, raw_file_name, field_names):
"""
takes the filename to be read and uses the maps setup
on class instantiation to process the file.
This is a top level function and uses self.maps which
should be the column descriptions (in order).
"""
... |
function to decide how to process
the raw data (which can be any format).
Note - not 100% sure how this will be implemented
should we pass the filename (currently takes a line) | def identify_data(self, tpe, raw_data):
"""
function to decide how to process
the raw data (which can be any format).
Note - not 100% sure how this will be implemented
should we pass the filename (currently takes a line)
"""
num_applicable_rules = 0
forma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.