INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Execute a recipe and creates new folder and files.
:param recipe: Name of the recipe
:param plugin: Name of the plugin, to which the recipe must belong. | def build(self, recipe, plugin=None):
"""
Execute a recipe and creates new folder and files.
:param recipe: Name of the recipe
:param plugin: Name of the plugin, to which the recipe must belong.
"""
if recipe not in self.recipes.keys():
raise RecipeMissingExc... |
Buildes the recipe and creates needed folder and files.
May ask the user for some parameter inputs.
:param output_dir: Path, where the recipe shall be build. Default is the current working directory
:return: location of the installed recipe | def build(self, output_dir=None, **kwargs):
"""
Buildes the recipe and creates needed folder and files.
May ask the user for some parameter inputs.
:param output_dir: Path, where the recipe shall be build. Default is the current working directory
:return: location of the install... |
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract metadata from \
the given PDF file, to retrieve citations (and more) from the \
provided PDF file. This function returns the raw output of \
CERMINE call.
.. note::
Try to use a local CERMINE JAR file, and fall... | def cermine(pdf_file, force_api=False, override_local=None):
"""
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract metadata from \
the given PDF file, to retrieve citations (and more) from the \
provided PDF file. This function returns the raw output of \
CERMINE ca... |
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract DOIs of cited \
papers from a PDF file.
.. note::
Try to use a local CERMINE JAR file, and falls back to using the API. \
JAR file is expected to be found in \
``libbmc/external/cermine.jar``. You can o... | def cermine_dois(pdf_file, force_api=False, override_local=None):
"""
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract DOIs of cited \
papers from a PDF file.
.. note::
Try to use a local CERMINE JAR file, and falls back to using the API. \
JAR file is expect... |
Run `Grobid <https://github.com/kermitt2/grobid>`_ on a given folder to \
extract references.
.. note::
Before using this function, you have to download and build Grobid on \
your system. See \
`<https://grobid.readthedocs.org/en/latest/Install-Grobid/>`_ \
... | def grobid(pdf_folder, grobid_home=None, grobid_jar=None):
"""
Run `Grobid <https://github.com/kermitt2/grobid>`_ on a given folder to \
extract references.
.. note::
Before using this function, you have to download and build Grobid on \
your system. See \
... |
Extract DOIs of references using \
`pdfextract <https://github.com/CrossRef/pdfextract>`_.
.. note::
See ``libbmc.citations.pdf.pdfextract`` function as this one is just \
a wrapper around it.
See ``libbmc.citations.plaintext.get_cited_dois`` as well for the \
... | def pdfextract_dois(pdf_file):
"""
Extract DOIs of references using \
`pdfextract <https://github.com/CrossRef/pdfextract>`_.
.. note::
See ``libbmc.citations.pdf.pdfextract`` function as this one is just \
a wrapper around it.
See ``libbmc.citations.plaintext.g... |
high level function that can estimate where user is based
on predefined setups. | def where_am_i():
"""
high level function that can estimate where user is based
on predefined setups.
"""
locations = {'Work':0, 'Home':0}
for ssid in scan_for_ssids():
#print('checking scanned_ssid ', ssid)
for l in logged_ssids:
#print('checking logged_ssid ', l)
... |
prints all attributes and returns them as a dictionary
(mainly for testing how it will all integrate) | def dump_all(self, silent='NO'):
"""
prints all attributes and returns them as a dictionary
(mainly for testing how it will all integrate)
"""
all_params = []
all_params.append(dict(name='phone', val=self.transport))
all_params.append(dict(name='username', val=s... |
extrapolate a human readable summary of the contexts | def summarise(self):
"""
extrapolate a human readable summary of the contexts
"""
res = ''
if self.user == 'Developer':
if self.host == 'Home PC':
res += 'At Home'
else:
res += 'Away from PC'
elif self.user == 'Us... |
returns the host computer running this program | def get_host(self):
"""
returns the host computer running this program
"""
import socket
host_name = socket.gethostname()
for h in hosts:
if h['name'] == host_name:
return h['type'], h['name']
return dict(type='Unknown', name=host_nam... |
returns the username on this computer | def get_user(self):
"""
returns the username on this computer
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
break
for u in users:
if u['name'] == user:
retu... |
FUNCTION STUB - TODO
The intention is to get data from the mobile in the format:
gps_lat = 137.000
gps_lng = 100.000
moving = True | False
move_dist_10_sc = 0
move_dist_2_mn = 4
move_dist_10_mn = 4
move... | def inspect_phone(self, gps_lat_long = [137.0000,100.0000], moving = False, move_dist_2_mn = 4, on_charge = True, screen_saver = False):
"""
FUNCTION STUB - TODO
The intention is to get data from the mobile in the format:
gps_lat = 137.000
gps_lng = 100.00... |
get details of CPU, RAM usage of this PC | def get_host_usage(self):
"""
get details of CPU, RAM usage of this PC
"""
import psutil
process_names = [proc.name for proc in psutil.process_iter()]
cpu_pct = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
return str(cpu_pct), str(len(pro... |
Provide schema for shell configuration. | def schema():
"""Provide schema for shell configuration."""
return Schema({
'script': And(Or(type(' '), type(u' ')), len),
Optional('title', default=''): str,
Optional('model', default={}): {Optional(And(str, len)): object},
Optional('env', default={}): {O... |
Sets the key/value pairs in the given dict as
attributes of this result object. | def _transform_to_attrs(self, response):
"""Sets the key/value pairs in the given dict as
attributes of this result object.
"""
response_dict = self._desiarialize_response(response)
self.__dict__.update(response_dict) |
Modifies the given dict into a flat dict consisting of only
key/value pairs. | def _flatten_dict(self, dict_):
"""Modifies the given dict into a flat dict consisting of only
key/value pairs.
"""
flattened_dict = {}
for (key, value) in dict_.iteritems():
if isinstance(value, dict):
flattened_dict.update(self._flatten_dict(value))
... |
returns an object Project which matches name | def get_by_name(self, name):
""" returns an object Project which matches name """
for p in self.project_list:
if p.nme == name:
return p
return None |
handles the data sources used in projects, mainly as an
abstract to call the data sources in /lib and /dataTools | def add_source(self, name, location, schedule='Daily', op=''):
"""
handles the data sources used in projects, mainly as an
abstract to call the data sources in /lib and /dataTools
"""
if op == '':
op = name + '.log'
self.data_sources.append([name, location, s... |
run execute on all tasks IFF prior task is successful | def execute_tasks(self):
"""
run execute on all tasks IFF prior task is successful
"""
for t in self.tasks:
print('RUNNING ' + str(t.task_id) + ' = ' + t.name)
t.execute()
if t.success != '__IGNORE__RESULT__':
print(t)
p... |
create a report showing all project details | def build_report(self, op_file, tpe='md'):
"""
create a report showing all project details
"""
if tpe == 'md':
res = self.get_report_md()
elif tpe == 'rst':
res = self.get_report_rst()
elif tpe == 'html':
res = self.get_report_html()
... |
formats the project into a report in RST format | def get_report_rst(self):
"""
formats the project into a report in RST format
"""
res = ''
res += '-----------------------------------\n'
res += self.nme + '\n'
res += '-----------------------------------\n\n'
res += self.desc + '\n'
res += self.... |
formats the project into a report in MD format - WARNING - tables missing BR | def get_report_html(self):
"""
formats the project into a report in MD format - WARNING - tables missing BR
"""
res = '<h2>Project:' + self.nme + '</h2>'
res += '<p>' + self.desc + '</p>'
res += '<p>' + self.fldr + '</p>'
res += '<BR><h3>TABLES</h3>'
... |
adds parameters as key value pairs | def add_param(self, param_key, param_val):
"""
adds parameters as key value pairs
"""
self.params.append([param_key, param_val])
if param_key == '__success_test':
self.success = param_val |
executes all automatic tasks in order of task id | def execute(self):
"""
executes all automatic tasks in order of task id
"""
func_params = []
exec_str = self.func.__name__ + '('
for p in self.params:
if p[0][0:2] != '__': # ignore custom param names
exec_str += p[0] + '="' + self._force_st... |
Read all annotations from the specified file.
>>> annotations = read_annotations(path_or_file, separator)
>>> colnames = annotations['Column Name']
>>> types = annotations['Type']
>>> annot_row = annotations['Annot. row name']
:param path_or_file: Path or file-like object
:param separator:... | def read_annotations(path_or_file, separator='\t', reset=True):
"""
Read all annotations from the specified file.
>>> annotations = read_annotations(path_or_file, separator)
>>> colnames = annotations['Column Name']
>>> types = annotations['Type']
>>> annot_row = annotations['Annot. row nam... |
Helper function to extract N: and C: rows from annotations and pad their values | def annotation_rows(prefix, annotations):
"""
Helper function to extract N: and C: rows from annotations and pad their values
"""
ncol = len(annotations['Column Name'])
return {name.replace(prefix, '', 1) : values + [''] * (ncol - len(values))
for name, values in annotations.items() if n... |
Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''. | def create_column_index(annotations):
"""
Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''.
"""
_column_index = OrderedDict({'Column Name' : annotations['Column Name']})
categorical_rows = annotation_ro... |
Read a Perseus-formatted matrix into a pd.DataFrame.
Annotation rows will be converted into a multi-index.
By monkey-patching the returned pd.DataFrame a `to_perseus`
method for exporting the pd.DataFrame is made available.
:param path_or_file: File path or file-like object
:param kwargs: Keyword ... | def read_perseus(path_or_file, **kwargs):
"""
Read a Perseus-formatted matrix into a pd.DataFrame.
Annotation rows will be converted into a multi-index.
By monkey-patching the returned pd.DataFrame a `to_perseus`
method for exporting the pd.DataFrame is made available.
:param path_or_file: Fil... |
Save pd.DataFrame to Perseus text format.
:param df: pd.DataFrame.
:param path_or_file: File name or file-like object.
:param main_columns: Main columns. Will be infered if set to None. All numeric columns up-until the first non-numeric column are considered main columns.
:param separator: For separati... | def to_perseus(df, path_or_file, main_columns=None,
separator=separator,
convert_bool_to_category=True,
numerical_annotation_rows = set([])):
"""
Save pd.DataFrame to Perseus text format.
:param df: pd.DataFrame.
:param path_or_file: File name or file-like object.
:param mai... |
All numeric columns up-until the first non-numeric column are considered main columns.
:param df: The pd.DataFrame
:param index_level: Name of the index level of the column names. Default 'Column Name'
:param numeric_dtypes: Set of numpy.dtype containing all numeric types. Default int/float.
:returns: T... | def _infer_main_columns(df, index_level='Column Name', numeric_dtypes=_numeric_dtypes):
"""
All numeric columns up-until the first non-numeric column are considered main columns.
:param df: The pd.DataFrame
:param index_level: Name of the index level of the column names. Default 'Column Name'
:param... |
formats the entire search result in a table output | def get_page(search_text):
"""
formats the entire search result in a table output
"""
lst = search_aikif(search_text)
txt = '<table class="as-table as-table-zebra as-table-horizontal">'
for result in lst:
txt += '<TR><TD>' + result + '</TD></TR>'
txt += '</TABLE>\n\n'
return txt |
search for text - currently this looks in all folders in the
root of AIKIF but that also contains binaries so will need to
use the agent_filelist.py to specify the list of folders.
NOTE - this needs to use indexes rather than full search each time | def search_aikif(txt, formatHTML=True):
"""
search for text - currently this looks in all folders in the
root of AIKIF but that also contains binaries so will need to
use the agent_filelist.py to specify the list of folders.
NOTE - this needs to use indexes rather than full search each time
... |
highlight the search result | def format_result(line, line_num, txt):
""" highlight the search result """
return ' ' + str(line_num) + ': ' + line.replace(txt, '<span style="background-color: #FFFF00">' + txt + '</span>') |
Modules for testing happiness of 'persons' in 'worlds'
based on simplistic preferences. Just a toy - dont take seriously
----- WORLD SUMMARY for : Mars -----
population = 0
tax_rate = 0.0
tradition = 0.9
equity = 0.0
Preferences for Rover
tax_min = 0.... | def TEST():
"""
Modules for testing happiness of 'persons' in 'worlds'
based on simplistic preferences. Just a toy - dont take seriously
----- WORLD SUMMARY for : Mars -----
population = 0
tax_rate = 0.0
tradition = 0.9
equity = 0.0
Preferences for Rov... |
find the best world to make people happy | def solve(self, max_worlds=10000, silent=False):
"""
find the best world to make people happy
"""
self.num_worlds = 0
num_unhappy = 0
for tax_rate in range(self.tax_range[0],self.tax_range[1]):
for equity in range(self.equity_range[0],self.equity_range[1]):
... |
extended print details of happiness parameters | def show_details(self):
"""
extended print details of happiness parameters
"""
res = str(self)
res += '\nDETAILS\n'
for f in self.factors:
res += str(f)
return res |
calculates the estimated happiness of a person
living in a world
self._update_pref(self.person.prefs['tax_min'], self.person.prefs['tax_max'], self.world.tax_rate)
self._update_pref(self.person.prefs['tradition'], self.person.prefs['tradition'], self.world.tradition)
self._update_pref(se... | def calculate(self):
"""
calculates the estimated happiness of a person
living in a world
self._update_pref(self.person.prefs['tax_min'], self.person.prefs['tax_max'], self.world.tax_rate)
self._update_pref(self.person.prefs['tradition'], self.person.prefs['tradition'], self.worl... |
update the self rating based on the parameters.
If min max is a range (ie not equal) then add fixed value
to rating depending if current value is in range, otherwise
compare distance away from min/max (same value) | def _update_pref(self, lmin, lmax, cur):
"""
update the self rating based on the parameters.
If min max is a range (ie not equal) then add fixed value
to rating depending if current value is in range, otherwise
compare distance away from min/max (same value)
"""
r... |
this is going to be the tricky bit - probably not possible
to get the 'exact' rating for a value. Will need to do sentiment
analysis of the text to see how it matches the rating. Even that
sounds like it wont work - maybe a ML algorithm would do it, but
that requires a large body of text... | def match_value_to_text(self, text):
"""
this is going to be the tricky bit - probably not possible
to get the 'exact' rating for a value. Will need to do sentiment
analysis of the text to see how it matches the rating. Even that
sounds like it wont work - maybe a ML algorithm wo... |
convert a list to html using table formatting | def list2html(lst):
"""
convert a list to html using table formatting
"""
txt = '<TABLE width=100% border=0>'
for l in lst:
txt += '<TR>\n'
if type(l) is str:
txt+= '<TD>' + l + '</TD>\n'
elif type(l) is list:
txt+= '<TD>'
for i in l:
... |
builds a list of files and returns as a list | def GetFileList(rootPaths, lstXtn, shortNameOnly='Y'):
"""
builds a list of files and returns as a list
"""
numFiles = 0
opFileList = []
if type(rootPaths) == str:
rootPaths = [rootPaths]
for rootPath in rootPaths:
for root, dirs, files in os.walk(rootPath):
... |
returns the html for a simple edit form | def build_edit_form(title, id, cols, return_page):
"""
returns the html for a simple edit form
"""
txt = '<H3>' + title + '<H3>'
txt += '<form action="' + return_page + '" method="POST">\n' # return_page = /agents
txt += ' updating id:' + str(id) + '\n<BR>'
txt += ' <input type="hidden" ... |
returns the html to display a listbox | def build_html_listbox(lst, nme):
"""
returns the html to display a listbox
"""
res = '<select name="' + nme + '" multiple="multiple">\n'
for l in lst:
res += ' <option>' + str(l) + '</option>\n'
res += '</select>\n'
return res |
returns the html with supplied list as a HTML listbox | def build_data_list(lst):
"""
returns the html with supplied list as a HTML listbox
"""
txt = '<H3>' + List + '<H3><UL>'
for i in lst:
txt += '<LI>' + i + '</LI>'
txt += '<UL>'
return txt |
formats a standard filelist to htmk using table formats | def filelist2html(lst, fldr, hasHeader='N'):
"""
formats a standard filelist to htmk using table formats
"""
txt = '<TABLE width=100% border=0>'
numRows = 1
if lst:
for l in lst:
if hasHeader == 'Y':
if numRows == 1:
td_begin = '<TH>'
... |
creates a html link for a file using folder fldr | def link_file(f, fldr):
"""
creates a html link for a file using folder fldr
"""
fname = os.path.join(fldr,f)
if os.path.isfile(fname):
return '<a href="/aikif/data/core/' + f + '">' + f + '</a>'
else:
return f |
converts a dictionary to a HTML table row | def dict_to_htmlrow(d):
"""
converts a dictionary to a HTML table row
"""
res = "<TR>\n"
for k, v in d.items():
if type(v) == str:
res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + v + '</p></TD>'
else:
res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + str(v) ... |
reads a CSV file and converts it to HTML | def read_csv_to_html_table(csvFile, hasHeader='N'):
"""
reads a CSV file and converts it to HTML
"""
txt = '<table class="as-table as-table-zebra as-table-horizontal">'
with open(csvFile, "r") as f: #
numRows = 1
for row in f:
if hasHeader == 'Y':
if num... |
reads a CSV file and converts it to a HTML List | def read_csv_to_html_list(csvFile):
"""
reads a CSV file and converts it to a HTML List
"""
txt = ''
with open(csvFile) as csv_file:
for row in csv.reader(csv_file, delimiter=','):
txt += '<div id="table_row">'
for col in row:
txt += " "
... |
tell the agent to move to location y,x
Why is there another grd object in the agent? Because
this is NOT the main grid, rather a copy for the agent
to overwrite with planning routes, etc.
The real grid is initialised in World.__init__() class | def set_world(self, grd, start_y_x, y_x):
"""
tell the agent to move to location y,x
Why is there another grd object in the agent? Because
this is NOT the main grid, rather a copy for the agent
to overwrite with planning routes, etc.
The real grid is initialised in Worl... |
the goal of the explore agent is to move to the
target while avoiding blockages on the grid.
This function is messy and needs to be looked at.
It currently has a bug in that the backtrack oscillates
so need a new method of doing this - probably checking if
previously backtracked... | def do_your_job(self):
"""
the goal of the explore agent is to move to the
target while avoiding blockages on the grid.
This function is messy and needs to be looked at.
It currently has a bug in that the backtrack oscillates
so need a new method of doing this - probably... |
wrapper for debugging print and log methods | def lg_mv(self, log_lvl, txt):
"""
wrapper for debugging print and log methods
"""
if log_lvl <= self.LOG_LEVEL:
print(txt + str(self.current_y) + "," + str(self.current_x)) |
returns a Y,X value showing which direction the
agent should move in order to get to the target | def get_intended_direction(self):
"""
returns a Y,X value showing which direction the
agent should move in order to get to the target
"""
x = 0
y = 0
if self.target_x == self.current_x and self.target_y == self.current_y:
return y,x # target already a... |
clears the cells immediately around the grid of the agent
(just to make it find to see on the screen) | def clear_surroundings(self):
"""
clears the cells immediately around the grid of the agent
(just to make it find to see on the screen)
"""
cells_to_clear = self.grd.eight_neighbors(self.current_y, self.current_x)
for cell in cells_to_clear:
self.grd.set_tile(... |
dumps the status of the agent | def show_status(self):
"""
dumps the status of the agent
"""
txt = 'Agent Status:\n'
print(txt)
txt += "start_x = " + str(self.start_x) + "\n"
txt += "start_y = " + str(self.start_y) + "\n"
txt += "target_x = " + str(self.target_x) + "\n"
txt += ... |
collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']} | def get_audio_metadata(fname):
""" collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']}
"""
from mutagenx.easyid3 import ... |
retrieve the metadata from an MP3 file | def get_audio_metadata_old(fname):
""" retrieve the metadata from an MP3 file """
audio_dict = {}
print("IDv2 tag info for %s:" % fname)
try:
audio = mutagenx.id3.ID3(fname, translate=False)
except StandardError as err:
print("ERROR = " + str(err))
#else:
#print(audio.ppr... |
Checks cytoscape version
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
:returns: cytoscape and api version | def checkCytoscapeVersion(host=cytoscape_host,port=cytoscape_port):
"""
Checks cytoscape version
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
:returns: cytoscape and api version
"""
URL="http://"+str(host)+":"+str(port)+... |
General function for interacting with Cytoscape API.
:param namespace: namespace where the request should be executed. eg. "string"
:param commnand: command to execute. eg. "protein query"
:param PARAMs: a dictionary with the parameters. Check your swagger normaly running on
http://localhost:1234/v... | def cytoscape(namespace,command="",PARAMS={},host=cytoscape_host,port=cytoscape_port,method="POST",verbose=False):
"""
General function for interacting with Cytoscape API.
:param namespace: namespace where the request should be executed. eg. "string"
:param commnand: command to execute. eg. "protei... |
Gets tables from cytoscape
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param namespace: namepsace, default="default"
:param network: a network name or id, default="current"
:param host: cytoscape host address, default=cytoscape_host
:param po... | def getTableColumns(table, columns, namespace = "default", network = "current", host=cytoscape_host,port=cytoscape_port,verbose=False):
"""
Gets tables from cytoscape
:param table: table to retrieve eg. node
:param columns: columns to retrieve in list format
:param namespace: namepsace, default... |
Loads tables into cytoscape
:param df: a pandas dataframe to load
:param df_key: key column in df, default="index"
:param table: target table, default="node"
:param table_key_column: table key column, default="name"
:param network: a network name or id, default="current"
:param host: cytosc... | def loadTableData(df, df_key='index',table="node", \
table_key_column = "name",
network="current",\
namespace="default",\
host=cytoscape_host,port=cytoscape_port,verbose=False):
"""
Loads tables into cytoscape
:param df: a pan... |
Updates a visual style
:param title: title of the visual style
:param defaults: a list of dictionaries for each visualProperty
:param mappings: a list of dictionaries for each visualProperty
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
... | def update_style(title,defaults=None,mappings=None,host=cytoscape_host,port=cytoscape_port,verbose=False):
"""
Updates a visual style
:param title: title of the visual style
:param defaults: a list of dictionaries for each visualProperty
:param mappings: a list of dictionaries for each visualPr... |
Creates a new visual style
:param title: title of the visual style
:param defaults: a list of dictionaries for each visualProperty
:param mappings: a list of dictionaries for each visualProperty
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=123... | def create_styles(title,defaults=None,mappings=None,host=cytoscape_host,port=cytoscape_port):
"""
Creates a new visual style
:param title: title of the visual style
:param defaults: a list of dictionaries for each visualProperty
:param mappings: a list of dictionaries for each visualProperty
... |
Generates a dictionary for a given visual property
:param visualProperty: visualProperty
:param mappingType: mappingType
:param mappingColumn: mappingColumn
:param lower: for "continuous" mappings a list of the form [value,rgb_string]
:param center: for "continuous" mappings a list of the form ... | def mapVisualProperty(visualProperty,mappingType,mappingColumn,\
lower=None,center=None,upper=None,\
discrete=None,\
network="current",table="node",\
namespace="default",host=cytoscape_host,\
port=cytoscape_por... |
Checks the current network.
Note: works only on localhost
:param filetype: file type, default="PNG"
:param saveas: /path/to/non/tmp/file.prefix
:param host: cytoscape host address, default=cytoscape_host
:param port: cytoscape port, default=1234
:returns: an image | def result(filetype="PNG",saveas=None, host=cytoscape_host,port=cytoscape_port):
"""
Checks the current network.
Note: works only on localhost
:param filetype: file type, default="PNG"
:param saveas: /path/to/non/tmp/file.prefix
:param host: cytoscape host address, default=cytoscape_h... |
Plots tables from aDiff/cuffdiff into cytoscape using String protein queries.
Uses top changed genes as well as first neighbours and difusion fo generate subnetworks.
:param df: df as outputed by aDiff for differential gene expression
:param aging_genes: ENS gene ids to be labeled with a diagonal
... | def aDiffCytoscape(df,aging_genes,target,species="caenorhabditis elegans",limit=None, cutoff=0.4,\
taxon=None,host=cytoscape_host,port=cytoscape_port):
"""
Plots tables from aDiff/cuffdiff into cytoscape using String protein queries.
Uses top changed genes as well as first neighbours and ... |
Find all row names and the maximum column widths.
Args:
columns (dict): the keys are the column name and the value the max length.
Returns:
dict: column names (key) and widths (value). | def calculate_columns(sequence):
"""
Find all row names and the maximum column widths.
Args:
columns (dict): the keys are the column name and the value the max length.
Returns:
dict: column names (key) and widths (value).
"""
columns = {}
for row in sequence:
for k... |
Calculate row format.
Args:
columns (dict): the keys are the column name and the value the max length.
keys (list): optional list of keys to order columns as well as to filter for them.
Returns:
str: format for table row | def calculate_row_format(columns, keys=None):
"""
Calculate row format.
Args:
columns (dict): the keys are the column name and the value the max length.
keys (list): optional list of keys to order columns as well as to filter for them.
Returns:
str: format for table row
"""... |
Print sequence as ascii table to stdout.
Args:
sequence (list or tuple): a sequence with a dictionary each entry.
keys (list): optional list of keys to order columns as well as to filter for them. | def pprint(sequence, keys=None):
"""
Print sequence as ascii table to stdout.
Args:
sequence (list or tuple): a sequence with a dictionary each entry.
keys (list): optional list of keys to order columns as well as to filter for them.
"""
if len(sequence) > 0:
columns = calcu... |
Run pipelines in parallel.
Args:
data(dict): parameters for the pipeline (model, options, ...).
Returns:
dict: with two fields: success True/False and captured output (list of str). | def matrix_worker(data):
"""
Run pipelines in parallel.
Args:
data(dict): parameters for the pipeline (model, options, ...).
Returns:
dict: with two fields: success True/False and captured output (list of str).
"""
matrix = data['matrix']
Logger.get_logger(__name__ + '.worke... |
Running pipelines one after the other.
Returns
dict: with two fields: success True/False and captured output (list of str). | def run_matrix_ordered(self, process_data):
"""
Running pipelines one after the other.
Returns
dict: with two fields: success True/False and captured output (list of str).
"""
output = []
for entry in self.matrix:
env = entry['env'].copy()
... |
Check given matrix tags to be in the given list of matric tags.
Args:
entry (dict): matrix item (in yaml).
matrix_tags (list): represents --matrix-tags defined by user in command line.
Returns:
bool: True when matrix entry can be processed. | def can_process_matrix(entry, matrix_tags):
"""
Check given matrix tags to be in the given list of matric tags.
Args:
entry (dict): matrix item (in yaml).
matrix_tags (list): represents --matrix-tags defined by user in command line.
Returns:
bool: Tru... |
Running pipelines in parallel. | def run_matrix_in_parallel(self, process_data):
"""Running pipelines in parallel."""
worker_data = [{'matrix': entry, 'pipeline': process_data.pipeline,
'model': process_data.model, 'options': process_data.options,
'hooks': process_data.hooks} for entry in... |
Process the pipeline per matrix item. | def process(self, process_data):
"""Process the pipeline per matrix item."""
if self.parallel and not process_data.options.dry_run:
return self.run_matrix_in_parallel(process_data)
return self.run_matrix_ordered(process_data) |
Takes a SQL string containing 0 or more statements and returns a
list of individual statements as strings. Comments and
empty statements are ignored. | def _sqlfile_to_statements(sql):
"""
Takes a SQL string containing 0 or more statements and returns a
list of individual statements as strings. Comments and
empty statements are ignored.
"""
statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql))
re... |
Returns a name of a new migration. It will usually be a filename with
a valid and unique name.
:param name: human-readable name of a migration
:param suffix: file suffix (extension) - eg. 'sql' | def generate_migration_name(self, name, suffix):
"""Returns a name of a new migration. It will usually be a filename with
a valid and unique name.
:param name: human-readable name of a migration
:param suffix: file suffix (extension) - eg. 'sql'
"""
return os.path.join(s... |
Subclasses should call this method instead of `module.migrate` directly,
to support `db_config` optional argument. | def _call_migrate(self, module, connection_param):
"""Subclasses should call this method instead of `module.migrate` directly,
to support `db_config` optional argument.
"""
args = [connection_param]
spec = inspect.getargspec(module.migrate)
if len(spec.args) == 2:
... |
This recognizes migration type and executes either
:method:`execute_python_migration` or :method:`execute_native_migration` | def execute_migration(self, migration_file_relative):
"""This recognizes migration type and executes either
:method:`execute_python_migration` or :method:`execute_native_migration`
"""
migration_file = os.path.join(self.db_config['migrations_dir'], migration_file_relative)
m_type... |
uses the input data, which may be a string, list, number
or file to work out how to load the data (this can be
overridden by passing the data_type on the command line | def _identify_datatype(self, input_data):
"""
uses the input data, which may be a string, list, number
or file to work out how to load the data (this can be
overridden by passing the data_type on the command line
"""
if isinstance(input_data, (int, float)) :
... |
create a standard data object based on CSV file | def _create_from_csv(self):
"""
create a standard data object based on CSV file
"""
import aikif.dataTools.cls_datatable as cl
fle = cl.DataTable(self.input_data, ',')
fle.load_to_array()
self.content['data'] = fle.arr
lg.record_p... |
create a standard data object based on CSV file | def _create_from_owl(self):
"""
create a standard data object based on CSV file
"""
self.content['data'] = 'TODO - read OWL from ' + self.input_data
lg.record_process('_create_from_owl', 'read ' + self._calc_size_stats() + ' from ' + self.input_data) |
create a standard data object based on CSV file | def _create_from_url(self):
"""
create a standard data object based on CSV file
"""
import aikif.toolbox.network_tools as mod_net
mod_net.download_file_no_logon(self.input_data, 'temp_file.htm')
with open('temp_file.htm', 'r') as f:
self.content['data'] = f.re... |
get the size in bytes and num records of the content | def _calc_size_stats(self):
"""
get the size in bytes and num records of the content
"""
self.total_records = 0
self.total_length = 0
self.total_nodes = 0
if type(self.content['data']) is dict:
self.total_length += len(str(self.content['data']))
... |
recursively walk through a data set or json file
to get the total number of nodes | def _get_size_recursive(self, dat):
"""
recursively walk through a data set or json file
to get the total number of nodes
"""
self.total_records += 1
#self.total_nodes += 1
for rec in dat:
if hasattr(rec, '__iter__') and type(rec) is not str:
... |
Create a readable version string from version_info tuple components. | def _make_version(major, minor, micro, releaselevel, serial):
"""Create a readable version string from version_info tuple components."""
assert releaselevel in ['alpha', 'beta', 'candidate', 'final']
version = "%d.%d" % (major, minor)
if micro:
version += ".%d" % (micro,)
if releaselevel != ... |
Make the URL people should start at for this version of coverage.py. | def _make_url(major, minor, micro, releaselevel, serial):
"""Make the URL people should start at for this version of coverage.py."""
url = "https://django-pagination-bootstrap.readthedocs.io"
if releaselevel != 'final':
# For pre-releases, use a version-specific URL.
url += "/en/" + _make_ve... |
return a list of unique paths in the file list | def get_list_of_paths(self):
"""
return a list of unique paths in the file list
"""
all_paths = []
for p in self.fl_metadata:
try:
all_paths.append(p['path'])
except:
try:
print('cls_filelist - ... |
builds a list of files and returns as a list | def get_file_list(self, lstPaths, lstXtn, lstExcluded, VERBOSE = False):
"""
builds a list of files and returns as a list
"""
if VERBOSE:
print("Generating list of Files...")
print("Paths = ", lstPaths)
print("Xtns = ", lstXtn)
pri... |
collects the files metadata - note that this will fail
with strange errors if network connection drops out to
shared folder, but it is better to stop the program
rather than do a try except otherwise you will get an
incomplete set of files. | def add_file_metadata(self, fname):
"""
collects the files metadata - note that this will fail
with strange errors if network connection drops out to
shared folder, but it is better to stop the program
rather than do a try except otherwise you will get an
incomplete... |
makes a nice display of filename for printing based on columns passed
print('{:<30}'.format(f["name"]), '{:,}'.format(f["size"])) | def print_file_details_in_line(self, fname, col_headers):
"""
makes a nice display of filename for printing based on columns passed
print('{:<30}'.format(f["name"]), '{:,}'.format(f["size"]))
"""
line = ''
try:
sze = os.path.getsize(fname)
exce... |
saves as csv format | def print_file_details_as_csv(self, fname, col_headers):
""" saves as csv format """
line = ''
qu = '"'
d = ','
for fld in col_headers:
if fld == "fullfilename":
line = line + qu + fname + qu + d
if fld == "name":
l... |
uses a List of files and collects meta data on them and saves
to an text file as a list or with metadata depending on opFormat. | def save_filelist(self, opFile, opFormat, delim=',', qu='"'):
"""
uses a List of files and collects meta data on them and saves
to an text file as a list or with metadata depending on opFormat.
"""
op_folder = os.path.dirname(opFile)
if op_folder is not None: # ... |
connect here - use the other classes cls_oracle, cls_mysql, etc
otherwise this has the credentials used to access a share folder | def login(self, schema, username, password):
"""
connect here - use the other classes cls_oracle, cls_mysql, etc
otherwise this has the credentials used to access a share folder
"""
self.schema = schema
self.username = username
self.password = password
sel... |
Types a collection of genes returning the most likely gene version
in the collection with it's genotype | def type(self, sequence_coverage_collection,
min_gene_percent_covg_threshold=99):
"""Types a collection of genes returning the most likely gene version
in the collection with it's genotype"""
best_versions = self.get_best_version(
sequence_coverage_collection.values(... |
collects a filelist of all .py programs | def list_all_python_programs(self):
"""
collects a filelist of all .py programs
"""
self.tot_lines = 0
self.tot_bytes = 0
self.tot_files = 0
self.tot_loc = 0
self.lstPrograms = []
fl = mod_fl.FileList([self.fldr], ['*.py'], ["__pycache__", "/venv/"... |
Adds a comment to the existing program in the list,
logs the reference and TODO - adds core link to processes | def comment(self, nme, desc):
"""
Adds a comment to the existing program in the list,
logs the reference and TODO - adds core link to processes
"""
if nme != '':
program_exists = False
for i in self.lstPrograms:
print(i)
... |
Save the list of items to AIKIF core and optionally to local file fname | def save(self, fname=''):
"""
Save the list of items to AIKIF core and optionally to local file fname
"""
if fname != '':
with open(fname, 'w') as f:
for i in self.lstPrograms:
f.write(self.get_file_info_line(i, ','))
# sa... |
gathers info on a python program in list and formats as string | def get_file_info_line(self, fname, delim):
"""
gathers info on a python program in list and formats as string
"""
txt = ''
f = mod_file.File(fname[0])
txt += '"' + f.fullname + '"' + delim
txt += '"' + f.name + '"' + delim
txt += '"' + f.path + '"' + de... |
gathers info on a python program in list and formats as string | def get_file_info_web(self, fname, delim='<BR>\n'):
"""
gathers info on a python program in list and formats as string
"""
txt = ''
f = mod_file.File(fname[0])
txt += '<sup>' + f.name + '</sup>' + delim
txt += '<sup>' + fname[1] + '</sup>' + delim
txt +=... |
gets details on the program, size, date, list of functions
and produces a Markdown file for documentation | def collect_program_info(self, fname):
"""
gets details on the program, size, date, list of functions
and produces a Markdown file for documentation
"""
md = '#AIKIF Technical details\n'
md += 'Autogenerated list of programs with comments and progress\n'
md += '\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.