_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q57500 | Store.get_stage | train | def get_stage(self, matrix_name, stage_name):
"""
Get Stage of a concrete matrix.
Attributes:
matrix_name (str): name of the matrix
stage_name (str): name of the stage.
Returns:
CollectorStage: when stage has been found or None.
"""
f... | python | {
"resource": ""
} |
q57501 | Store.get_duration | train | def get_duration(self, matrix_name):
"""
Get duration for a concrete matrix.
Args:
matrix_name (str): name of the Matrix.
Returns:
float: duration of concrete matrix in seconds.
"""
duration = 0.0
if matrix_name in self.data:
... | python | {
"resource": ""
} |
q57502 | Store.update | train | def update(self, item):
"""
Add a collector item.
Args:
item (CollectorUpdate): event data like stage, timestampe and status.
"""
if item.matrix not in self.data:
self.data[item.matrix] = []
result = Select(self.data[item.matrix]).where(
... | python | {
"resource": ""
} |
q57503 | Collector.run | train | def run(self):
"""Collector main loop."""
while True:
data = self.queue.get()
if data is None:
Logger.get_logger(__name__).info("Stopping collector process ...")
break
# updating the report data
self.store.update(data)
... | python | {
"resource": ""
} |
q57504 | read_map | train | def read_map(fname):
"""
reads a saved text file to list
"""
lst = []
with open(fname, "r") as f:
for line in f:
lst.append(line)
return lst | python | {
"resource": ""
} |
q57505 | gui_view_tk.show_grid_from_file | train | def show_grid_from_file(self, fname):
"""
reads a saved grid file and paints it on the canvas
"""
with open(fname, "r") as f:
for y, row in enumerate(f):
for x, val in enumerate(row):
self.draw_cell(y, x, val) | python | {
"resource": ""
} |
q57506 | gui_view_tk.draw_cell | train | def draw_cell(self, row, col, val):
"""
draw a cell as position row, col containing val
"""
if val == 'T':
self.paint_target(row,col)
elif val == '#':
self.paint_block(row,col)
elif val == 'X':
self.paint_hill(row,col)
elif val ... | python | {
"resource": ""
} |
q57507 | gui_view_tk.paint_agent_trail | train | def paint_agent_trail(self, y, x, val):
"""
paint an agent trail as ONE pixel to allow for multiple agent
trails to be seen in the same cell
"""
for j in range(1,self.cell_height-1):
for i in range(1,self.cell_width-1):
self.img.put(self.agent_color(va... | python | {
"resource": ""
} |
q57508 | gui_view_tk.agent_color | train | def agent_color(self, val):
"""
gets a colour for agent 0 - 9
"""
if val == '0':
colour = 'blue'
elif val == '1':
colour = 'navy'
elif val == '2':
colour = 'firebrick'
elif val == '3':
colour = 'blue'
elif v... | python | {
"resource": ""
} |
q57509 | create_random_population | train | def create_random_population(num=100):
"""
create a list of people with randomly generated names and stats
"""
people = []
for _ in range(num):
nme = 'blah'
tax_min = random.randint(1,40)/100
tax_max = tax_min + random.randint(1,40)/100
tradition = random.randint(1,10... | python | {
"resource": ""
} |
q57510 | Pipeline.cleanup | train | def cleanup(self):
"""Run cleanup script of pipeline when hook is configured."""
if self.data.hooks and len(self.data.hooks.cleanup) > 0:
env = self.data.env_list[0].copy()
env.update({'PIPELINE_RESULT': 'SUCCESS', 'PIPELINE_SHELL_EXIT_CODE': '0'})
config = ShellConfi... | python | {
"resource": ""
} |
q57511 | Pipeline.process | train | def process(self, pipeline):
"""Processing the whole pipeline definition."""
output = []
for entry in pipeline:
key = list(entry.keys())[0]
# an environment block can be repeated
if key == "env":
self.data.env_list[0].update(entry[key])
... | python | {
"resource": ""
} |
q57512 | AICLI.process | train | def process(self, txt, mode):
"""
Top level function to process the command, mainly
depending on mode.
This should work by using the function name defined
in all_commamnds
"""
result = ''
if mode == 'ADD': # already in add mode, so add data
if... | python | {
"resource": ""
} |
q57513 | AICLI.cmd_add | train | def cmd_add(self, txt):
"""
Enter add mode - all text entered now will be
processed as adding information until cancelled
"""
self.show_output('Adding ', txt)
self.raw.add(txt)
print(self.raw)
return 'Added ' + txt | python | {
"resource": ""
} |
q57514 | AICLI.cmd_query | train | def cmd_query(self, txt):
"""
search and query the AIKIF
"""
self.show_output('Searching for ', txt)
res = self.raw.find(txt)
for d in res:
self.show_output(d)
return str(len(res)) + ' results for ' + txt | python | {
"resource": ""
} |
q57515 | U2F.verify_integrity | train | def verify_integrity(self):
"""Verifies that all required functions been injected."""
if not self.__integrity_check:
if not self.__appid:
raise Exception('U2F_APPID was not defined! Please define it in configuration file.')
if self.__facets_enabled and not len(se... | python | {
"resource": ""
} |
q57516 | U2F.devices | train | def devices(self):
"""Manages users enrolled u2f devices"""
self.verify_integrity()
if session.get('u2f_device_management_authorized', False):
if request.method == 'GET':
return jsonify(self.get_devices()), 200
elif request.method == 'DELETE':
... | python | {
"resource": ""
} |
q57517 | U2F.facets | train | def facets(self):
"""Provides facets support. REQUIRES VALID HTTPS!"""
self.verify_integrity()
if self.__facets_enabled:
data = json.dumps({
'trustedFacets' : [{
'version': { 'major': 1, 'minor' : 0 },
'ids': self.__facets_list... | python | {
"resource": ""
} |
q57518 | U2F.get_enroll | train | def get_enroll(self):
"""Returns new enroll seed"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
enroll = start_register(self.__appid, devices)
enroll['status'] = 'ok'
session['_u2f_enroll_'] = enroll.json
return enroll | python | {
"resource": ""
} |
q57519 | U2F.verify_enroll | train | def verify_enroll(self, response):
"""Verifies and saves U2F enroll"""
seed = session.pop('_u2f_enroll_')
try:
new_device, cert = complete_register(seed, response, self.__facets_list)
except Exception as e:
if self.__call_fail_enroll:
self.__call_... | python | {
"resource": ""
} |
q57520 | U2F.get_signature_challenge | train | def get_signature_challenge(self):
"""Returns new signature challenge"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
if devices == []:
return {
'status' : 'failed',
'error' : 'No devices been associated with t... | python | {
"resource": ""
} |
q57521 | U2F.remove_device | train | def remove_device(self, request):
"""Removes device specified by id"""
devices = self.__get_u2f_devices()
for i in range(len(devices)):
if devices[i]['keyHandle'] == request['id']:
del devices[i]
self.__save_u2f_devices(devices)
... | python | {
"resource": ""
} |
q57522 | U2F.verify_counter | train | def verify_counter(self, signature, counter):
""" Verifies that counter value is greater than previous signature"""
devices = self.__get_u2f_devices()
for device in devices:
# Searching for specific keyhandle
if device['keyHandle'] == signature['keyHandle']:
... | python | {
"resource": ""
} |
q57523 | Validator.validate | train | def validate(data):
"""
Validate data against the schema.
Args:
data(dict): data structure to validate.
Returns:
dict: data as provided and defaults where defined in schema.
"""
try:
return Schema(Validator.SCHEMA).validate(data)
... | python | {
"resource": ""
} |
q57524 | Loader.include | train | def include(self, node):
"""Include the defined yaml file."""
result = None
if isinstance(node, ScalarNode):
result = Loader.include_file(self.construct_scalar(node))
else:
raise RuntimeError("Not supported !include on type %s" % type(node))
return result | python | {
"resource": ""
} |
q57525 | Loader.load | train | def load(filename):
""""Load yaml file with specific include loader."""
if os.path.isfile(filename):
with open(filename) as handle:
return yaml_load(handle, Loader=Loader) # nosec
raise RuntimeError("File %s doesn't exist!" % filename) | python | {
"resource": ""
} |
q57526 | Transpose.pivot | train | def pivot(self):
"""
transposes rows and columns
"""
self.op_data = [list(i) for i in zip(*self.ip_data)] | python | {
"resource": ""
} |
q57527 | Transpose.key_value_pairs | train | 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... | python | {
"resource": ""
} |
q57528 | Transpose.links_to_data | train | 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... | python | {
"resource": ""
} |
q57529 | GoalFriendly.find_best_plan | train | 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) | python | {
"resource": ""
} |
q57530 | load_data | train | 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('') != '':
... | python | {
"resource": ""
} |
q57531 | parse_n3 | train | 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... | python | {
"resource": ""
} |
q57532 | summarise_file_as_html | train | 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:
... | python | {
"resource": ""
} |
q57533 | main | train | 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
... | python | {
"resource": ""
} |
q57534 | run_game_of_life | train | 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'... | python | {
"resource": ""
} |
q57535 | print_there | train | 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() | python | {
"resource": ""
} |
q57536 | identify_col_pos | train | 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... | python | {
"resource": ""
} |
q57537 | load_tbl_from_csv | train | 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 ... | python | {
"resource": ""
} |
q57538 | _get_dict_char_count | train | 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 | python | {
"resource": ""
} |
q57539 | Container.creator | train | 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... | python | {
"resource": ""
} |
q57540 | Image.creator | train | 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... | python | {
"resource": ""
} |
q57541 | stdout_redirector | train | 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... | python | {
"resource": ""
} |
q57542 | write_temporary_file | train | 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 ... | python | {
"resource": ""
} |
q57543 | print_new | train | def print_new(ctx, name, migration_type):
"""Prints filename of a new migration"""
click.echo(ctx.obj.repository.generate_migration_name(name, migration_type)) | python | {
"resource": ""
} |
q57544 | Agent.start | train | def start(self):
"""
Starts an agent with standard logging
"""
self.running = True
self.status = 'RUNNING'
self.mylog.record_process('agent', self.name + ' - starting') | python | {
"resource": ""
} |
q57545 | Agent.set_coords | train | 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 | python | {
"resource": ""
} |
q57546 | from_file | train | 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... | python | {
"resource": ""
} |
q57547 | to_db | train | 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.... | python | {
"resource": ""
} |
q57548 | userdata_to_db | train | 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... | python | {
"resource": ""
} |
q57549 | send_text | train | 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... | python | {
"resource": ""
} |
q57550 | launch_app | train | 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... | python | {
"resource": ""
} |
q57551 | app_activate | train | 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)') | python | {
"resource": ""
} |
q57552 | CatchmentCollections.most_similar_catchments | train | 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... | python | {
"resource": ""
} |
q57553 | readSAM | train | 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'... | python | {
"resource": ""
} |
q57554 | SAMflags | train | 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: ... | python | {
"resource": ""
} |
q57555 | Bias.get_bias_details | train | 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... | python | {
"resource": ""
} |
q57556 | Bias._read_bias_rating | train | 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)
... | python | {
"resource": ""
} |
q57557 | get_root_folder | train | 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.... | python | {
"resource": ""
} |
q57558 | read_credentials | train | 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 | python | {
"resource": ""
} |
q57559 | show_config | train | 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) + ' ... | python | {
"resource": ""
} |
q57560 | filterMotifs | train | 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
"""... | python | {
"resource": ""
} |
q57561 | Parse._read_file | train | 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
... | python | {
"resource": ""
} |
q57562 | Config.reset | train | 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... | python | {
"resource": ""
} |
q57563 | Config.save | train | def save(self):
"""
Write data to user config file.
"""
with open(self._user_config_file, 'w', encoding='utf-8') as f:
self.write(f) | python | {
"resource": ""
} |
q57564 | _magic_data | train | 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 | python | {
"resource": ""
} |
q57565 | _max_lengths | train | 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]... | python | {
"resource": ""
} |
q57566 | _confidence | train | 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
... | python | {
"resource": ""
} |
q57567 | _identify_all | train | 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... | python | {
"resource": ""
} |
q57568 | _magic | train | 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... | python | {
"resource": ""
} |
q57569 | _file_details | train | 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()
... | python | {
"resource": ""
} |
q57570 | ext_from_filename | train | 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 = ".{... | python | {
"resource": ""
} |
q57571 | from_file | train | 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 ... | python | {
"resource": ""
} |
q57572 | from_string | train | 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... | python | {
"resource": ""
} |
q57573 | retrieve_GTF_field | train | 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... | python | {
"resource": ""
} |
q57574 | attributesGTF | train | 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... | python | {
"resource": ""
} |
q57575 | parseGTF | train | 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.
... | python | {
"resource": ""
} |
q57576 | writeGTF | train | 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... | python | {
"resource": ""
} |
q57577 | GTFtoBED | train | 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... | python | {
"resource": ""
} |
q57578 | MAPGenoToTrans | train | 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... | python | {
"resource": ""
} |
q57579 | GetTransPosition | train | 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... | python | {
"resource": ""
} |
q57580 | get_protected_page | train | 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:
... | python | {
"resource": ""
} |
q57581 | read_rawFilesTable | train | 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_... | python | {
"resource": ""
} |
q57582 | WeakMethodContainer.add_method | train | 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... | python | {
"resource": ""
} |
q57583 | WeakMethodContainer.del_method | train | 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... | python | {
"resource": ""
} |
q57584 | WeakMethodContainer.del_instance | train | 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)
... | python | {
"resource": ""
} |
q57585 | WeakMethodContainer.iter_instances | train | 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:
... | python | {
"resource": ""
} |
q57586 | WeakMethodContainer.iter_methods | train | 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]
... | python | {
"resource": ""
} |
q57587 | load_data_subject_areas | train | 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... | python | {
"resource": ""
} |
q57588 | check_ontology | train | 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) | python | {
"resource": ""
} |
q57589 | FileMap.find_type | train | 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... | python | {
"resource": ""
} |
q57590 | FileMap.get_full_filename | train | 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' | python | {
"resource": ""
} |
q57591 | Plan_BDI.load_plan | train | 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)
... | python | {
"resource": ""
} |
q57592 | Plan_BDI.add_constraint | train | def add_constraint(self, name, tpe, val):
"""
adds a constraint for the plan
"""
self.constraint.append([name, tpe, val]) | python | {
"resource": ""
} |
q57593 | Mapper.get_maps_stats | train | 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... | python | {
"resource": ""
} |
q57594 | Mapper.save_rules | train | 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()) | python | {
"resource": ""
} |
q57595 | Mapper.process_rule | train | def process_rule(self, m, dct, tpe):
"""
uses the MapRule 'm' to run through the 'dict'
and extract data based on the rule
"""
print('TODO - ' + tpe + ' + applying rule ' + str(m).replace('\n', '') ) | python | {
"resource": ""
} |
q57596 | Mapper.format_raw_data | train | def format_raw_data(self, tpe, raw_data):
"""
uses type to format the raw information to a dictionary
usable by the mapper
"""
if tpe == 'text':
formatted_raw_data = self.parse_text_to_dict(raw_data)
elif tpe == 'file':
formatted_raw_data ... | python | {
"resource": ""
} |
q57597 | Mapper.parse_text_to_dict | train | def parse_text_to_dict(self, txt):
"""
takes a string and parses via NLP, ready for mapping
"""
op = {}
print('TODO - import NLP, split into verbs / nouns')
op['nouns'] = txt
op['verbs'] = txt
return op | python | {
"resource": ""
} |
q57598 | Mapper.parse_file_to_dict | train | def parse_file_to_dict(self, fname):
"""
process the file according to the mapping rules.
The cols list must match the columns in the filename
"""
print('TODO - parse_file_to_dict' + fname)
for m in self.maps:
if m.tpe == 'file':
if m.key[0:3] ... | python | {
"resource": ""
} |
q57599 | Mapper.create_map_from_file | train | def create_map_from_file(self, data_filename):
"""
reads the data_filename into a matrix and calls the main
function '' to generate a .rule file based on the data in the map
For all datafiles mapped, there exists a .rule file to define it
"""
o... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.