_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q57300 | ExploreAgent.lg_mv | train | 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)) | python | {
"resource": ""
} |
q57301 | ExploreAgent.get_intended_direction | train | 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... | python | {
"resource": ""
} |
q57302 | ExploreAgent.show_status | train | 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 += ... | python | {
"resource": ""
} |
q57303 | get_audio_metadata_old | train | 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... | python | {
"resource": ""
} |
q57304 | calculate_columns | train | 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... | python | {
"resource": ""
} |
q57305 | calculate_row_format | train | 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
"""... | python | {
"resource": ""
} |
q57306 | pprint | train | 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... | python | {
"resource": ""
} |
q57307 | matrix_worker | train | 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... | python | {
"resource": ""
} |
q57308 | Matrix.can_process_matrix | train | 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... | python | {
"resource": ""
} |
q57309 | Matrix.run_matrix_ordered | train | 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()
... | python | {
"resource": ""
} |
q57310 | Matrix.run_matrix_in_parallel | train | 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... | python | {
"resource": ""
} |
q57311 | Matrix.process | train | 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) | python | {
"resource": ""
} |
q57312 | _sqlfile_to_statements | train | 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... | python | {
"resource": ""
} |
q57313 | MigrationsRepository.generate_migration_name | train | 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... | python | {
"resource": ""
} |
q57314 | MigrationsExecutor._call_migrate | train | 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:
... | python | {
"resource": ""
} |
q57315 | Data._identify_datatype | train | 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)) :
... | python | {
"resource": ""
} |
q57316 | Data._calc_size_stats | train | 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']))
... | python | {
"resource": ""
} |
q57317 | Data._get_size_recursive | train | 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:
... | python | {
"resource": ""
} |
q57318 | _make_version | train | 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 != ... | python | {
"resource": ""
} |
q57319 | _make_url | train | 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... | python | {
"resource": ""
} |
q57320 | FileList.get_list_of_paths | train | 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 - ... | python | {
"resource": ""
} |
q57321 | FileList.add_file_metadata | train | 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... | python | {
"resource": ""
} |
q57322 | FileList.print_file_details_as_csv | train | 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... | python | {
"resource": ""
} |
q57323 | FileList.save_filelist | train | 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: # ... | python | {
"resource": ""
} |
q57324 | DataSet.login | train | 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... | python | {
"resource": ""
} |
q57325 | GeneCollectionTyper.type | train | 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(... | python | {
"resource": ""
} |
q57326 | Programs.list_all_python_programs | train | 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/"... | python | {
"resource": ""
} |
q57327 | Programs.save | train | 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... | python | {
"resource": ""
} |
q57328 | Programs.collect_program_info | train | 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... | python | {
"resource": ""
} |
q57329 | id_nameDAVID | train | def id_nameDAVID(df,GTF=None,name_id=None):
"""
Given a DAVIDenrich output it converts ensembl gene ids to genes names and adds this column to the output
:param df: a dataframe output from DAVIDenrich
:param GTF: a GTF dataframe from readGTF()
:param name_id: instead of a gtf dataframe a dataframe ... | python | {
"resource": ""
} |
q57330 | DAVIDgetGeneAttribute | train | def DAVIDgetGeneAttribute(x,df,refCol="ensembl_gene_id",fieldTOretrieve="gene_name"):
"""
Returns a list of gene names for given gene ids.
:param x: a string with the list of IDs separated by ', '
:param df: a dataframe with the reference column and a the column to retrieve
:param refCol: the heade... | python | {
"resource": ""
} |
q57331 | main | train | def main(**options):
"""Spline loc tool."""
application = Application(**options)
# fails application when your defined threshold is higher than your ratio of com/loc.
if not application.run():
sys.exit(1)
return application | python | {
"resource": ""
} |
q57332 | Application.load_configuration | train | def load_configuration(self):
"""Loading configuration."""
filename = os.path.join(os.path.dirname(__file__), 'templates/spline-loc.yml.j2')
with open(filename) as handle:
return Adapter(safe_load(handle)).configuration | python | {
"resource": ""
} |
q57333 | Application.ignore_path | train | def ignore_path(path):
"""
Verify whether to ignore a path.
Args:
path (str): path to check.
Returns:
bool: True when to ignore given path.
"""
ignore = False
for name in ['.tox', 'dist', 'build', 'node_modules', 'htmlcov']:
i... | python | {
"resource": ""
} |
q57334 | Application.walk_files_for | train | def walk_files_for(paths, supported_extensions):
"""
Iterating files for given extensions.
Args:
supported_extensions (list): supported file extentsion for which to check loc and com.
Returns:
str: yield each full path and filename found.
"""
for... | python | {
"resource": ""
} |
q57335 | Application.analyse | train | def analyse(self, path_and_filename, pattern):
"""
Find out lines of code and lines of comments.
Args:
path_and_filename (str): path and filename to parse for loc and com.
pattern (str): regex to search for line commens and block comments
Returns:
i... | python | {
"resource": ""
} |
q57336 | datasetsBM | train | def datasetsBM(host=biomart_host):
"""
Lists BioMart datasets.
:param host: address of the host server, default='http://www.ensembl.org/biomart'
:returns: nothing
"""
stdout_ = sys.stdout #Keep track of the previous value.
stream = StringIO()
sys.stdout = stream
server = Biomar... | python | {
"resource": ""
} |
q57337 | filtersBM | train | def filtersBM(dataset,host=biomart_host):
"""
Lists BioMart filters for a specific dataset.
:param dataset: dataset to list filters of.
:param host: address of the host server, default='http://www.ensembl.org/biomart'
:returns: nothing
"""
stdout_ = sys.stdout #Keep track of the previous ... | python | {
"resource": ""
} |
q57338 | CoreData.format_csv | train | def format_csv(self, delim=',', qu='"'):
"""
Prepares the data in CSV format
"""
res = qu + self.name + qu + delim
if self.data:
for d in self.data:
res += qu + str(d) + qu + delim
return res + '\n' | python | {
"resource": ""
} |
q57339 | CoreData.format_all | train | def format_all(self):
"""
return a trace of parents and children of the obect
"""
res = '\n--- Format all : ' + str(self.name) + ' -------------\n'
res += ' parent = ' + str(self.parent) + '\n'
res += self._get_all_children()
res += self._get_links()
... | python | {
"resource": ""
} |
q57340 | CoreData._get_all_children | train | def _get_all_children(self,):
"""
return the list of children of a node
"""
res = ''
if self.child_nodes:
for c in self.child_nodes:
res += ' child = ' + str(c) + '\n'
if c.child_nodes:
for grandchild in c.child_nod... | python | {
"resource": ""
} |
q57341 | CoreData._get_links | train | def _get_links(self,):
"""
return the list of links of a node
"""
res = ''
if self.links:
for l in self.links:
res += ' links = ' + str(l[0]) + '\n'
if l[0].child_nodes:
for chld in l[0].child_nodes:
... | python | {
"resource": ""
} |
q57342 | CoreData.get_child_by_name | train | def get_child_by_name(self, name):
"""
find the child object by name and return the object
"""
for c in self.child_nodes:
if c.name == name:
return c
return None | python | {
"resource": ""
} |
q57343 | CoreTable.get_filename | train | def get_filename(self, year):
"""
returns the filename
"""
res = self.fldr + os.sep + self.type + year + '.' + self.user
return res | python | {
"resource": ""
} |
q57344 | CoreTable.save | train | def save(self, file_tag='2016', add_header='N'):
"""
save table to folder in appropriate files
NOTE - ONLY APPEND AT THIS STAGE - THEN USE DATABASE
"""
fname = self.get_filename(file_tag)
with open(fname, 'a') as f:
if add_header == 'Y':
f.writ... | python | {
"resource": ""
} |
q57345 | CoreTable.format_hdr | train | def format_hdr(self, delim=',', qu='"'):
"""
Prepares the header in CSV format
"""
res = ''
if self.header:
for d in self.header:
res += qu + str(d) + qu + delim
return res + '\n' | python | {
"resource": ""
} |
q57346 | CoreTable.generate_diary | train | def generate_diary(self):
"""
extracts event information from core tables into diary files
"""
print('Generate diary files from Event rows only')
for r in self.table:
print(str(type(r)) + ' = ', r) | python | {
"resource": ""
} |
q57347 | VariantTyper.type | train | def type(self, variant_probe_coverages, variant=None):
"""
Takes a list of VariantProbeCoverages and returns a Call for the Variant.
Note, in the simplest case the list will be of length one. However, we may be typing the
Variant on multiple backgrouds leading to multiple Var... | python | {
"resource": ""
} |
q57348 | Ansible.creator | train | def creator(entry, config):
"""Creator function for creating an instance of an Ansible script."""
ansible_playbook = "ansible.playbook.dry.run.see.comment"
ansible_inventory = "ansible.inventory.dry.run.see.comment"
ansible_playbook_content = render(config.script, model=config.model, en... | python | {
"resource": ""
} |
q57349 | GameOfLife.update_gol | train | def update_gol(self):
"""
Function that performs one step of the Game of Life
"""
updated_grid = [[self.update_cell(row, col) \
for col in range(self.get_grid_width())] \
for row in range(self.get_grid_height())]
... | python | {
"resource": ""
} |
q57350 | GameOfLife.update_cell | train | def update_cell(self, row, col):
"""
Function that computes the update for one cell in the Game of Life
"""
# compute number of living neighbors
neighbors = self.eight_neighbors(row, col)
living_neighbors = 0
for neighbor in neighbors:
if not self.is_e... | python | {
"resource": ""
} |
q57351 | GameOfLifePatterns.random_offset | train | def random_offset(self, lst):
"""
offsets a pattern list generated below to a random
position in the grid
"""
res = []
x = random.randint(4,self.max_x - 42)
y = random.randint(4,self.max_y - 10)
for itm in lst:
res.append([itm[0] + y, itm[1] +... | python | {
"resource": ""
} |
q57352 | Hist1d.get_random | train | def get_random(self, size=10):
"""Returns random variates from the histogram.
Note this assumes the histogram is an 'events per bin', not a pdf.
Inside the bins, a uniform distribution is assumed.
"""
bin_i = np.random.choice(np.arange(len(self.bin_centers)), size=size, p=self.no... | python | {
"resource": ""
} |
q57353 | Hist1d.std | train | def std(self, bessel_correction=True):
"""Estimates std of underlying data, assuming each datapoint was exactly in the center of its bin."""
if bessel_correction:
n = self.n
bc = n / (n - 1)
else:
bc = 1
return np.sqrt(np.average((self.bin_centers - se... | python | {
"resource": ""
} |
q57354 | Hist1d.percentile | train | def percentile(self, percentile):
"""Return bin center nearest to percentile"""
return self.bin_centers[np.argmin(np.abs(self.cumulative_density * 100 - percentile))] | python | {
"resource": ""
} |
q57355 | Histdd._data_to_hist | train | def _data_to_hist(self, data, **kwargs):
"""Return bin_edges, histogram array"""
if hasattr(self, 'bin_edges'):
kwargs.setdefault('bins', self.bin_edges)
if len(data) == 1 and isinstance(data[0], COLUMNAR_DATA_SOURCES):
data = data[0]
if self.axis_names is N... | python | {
"resource": ""
} |
q57356 | Histdd.axis_names_without | train | def axis_names_without(self, axis):
"""Return axis names without axis, or None if axis_names is None"""
if self.axis_names is None:
return None
return itemgetter(*self.other_axes(axis))(self.axis_names) | python | {
"resource": ""
} |
q57357 | Histdd.bin_centers | train | def bin_centers(self, axis=None):
"""Return bin centers along an axis, or if axis=None, list of bin_centers along each axis"""
if axis is None:
return np.array([self.bin_centers(axis=i) for i in range(self.dimensions)])
axis = self.get_axis_number(axis)
return 0.5 * (self.bin... | python | {
"resource": ""
} |
q57358 | Histdd.get_axis_bin_index | train | def get_axis_bin_index(self, value, axis):
"""Returns index along axis of bin in histogram which contains value
Inclusive on both endpoints
"""
axis = self.get_axis_number(axis)
bin_edges = self.bin_edges[axis]
# The right bin edge of np.histogram is inclusive:
if... | python | {
"resource": ""
} |
q57359 | Histdd.get_bin_indices | train | def get_bin_indices(self, values):
"""Returns index tuple in histogram of bin which contains value"""
return tuple([self.get_axis_bin_index(values[ax_i], ax_i)
for ax_i in range(self.dimensions)]) | python | {
"resource": ""
} |
q57360 | Histdd.all_axis_bin_centers | train | def all_axis_bin_centers(self, axis):
"""Return ndarray of same shape as histogram containing bin center value along axis at each point"""
# Arcane hack that seems to work, at least in 3d... hope
axis = self.get_axis_number(axis)
return np.meshgrid(*self.bin_centers(), indexing='ij')[axi... | python | {
"resource": ""
} |
q57361 | Histdd.sum | train | def sum(self, axis):
"""Sums all data along axis, returns d-1 dimensional histogram"""
axis = self.get_axis_number(axis)
if self.dimensions == 2:
new_hist = Hist1d
else:
new_hist = Histdd
return new_hist.from_histogram(np.sum(self.histogram, axis=axis),
... | python | {
"resource": ""
} |
q57362 | Histdd.slicesum | train | def slicesum(self, start, stop=None, axis=0):
"""Slices the histogram along axis, then sums over that slice, returning a d-1 dimensional histogram"""
return self.slice(start, stop, axis).sum(axis) | python | {
"resource": ""
} |
q57363 | Histdd.projection | train | def projection(self, axis):
"""Sums all data along all other axes, then return Hist1D"""
axis = self.get_axis_number(axis)
projected_hist = np.sum(self.histogram, axis=self.other_axes(axis))
return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis]) | python | {
"resource": ""
} |
q57364 | Histdd.cumulate | train | def cumulate(self, axis):
"""Returns new histogram with all data cumulated along axis."""
axis = self.get_axis_number(axis)
return Histdd.from_histogram(np.cumsum(self.histogram, axis=axis),
bin_edges=self.bin_edges,
axis_... | python | {
"resource": ""
} |
q57365 | Histdd.central_likelihood | train | def central_likelihood(self, axis):
"""Returns new histogram with all values replaced by their central likelihoods along axis."""
result = self.cumulative_density(axis)
result.histogram = 1 - 2 * np.abs(result.histogram - 0.5)
return result | python | {
"resource": ""
} |
q57366 | Histdd.lookup_hist | train | def lookup_hist(self, mh):
"""Return histogram within binning of Histdd mh, with values looked up in this histogram.
This is not rebinning: no interpolation /renormalization is performed.
It's just a lookup.
"""
result = mh.similar_blank_histogram()
points = np.stack([mh... | python | {
"resource": ""
} |
q57367 | create_roadmap_doc | train | def create_roadmap_doc(dat, opFile):
"""
takes a dictionary read from a yaml file and converts
it to the roadmap documentation
"""
op = format_title('Roadmap for AIKIF')
for h1 in dat['projects']:
op += format_h1(h1)
if dat[h1] is None:
op += '(No details)\n'
... | python | {
"resource": ""
} |
q57368 | Grid.clear | train | def clear(self):
"""
Clears grid to be EMPTY
"""
self.grid = [[EMPTY for dummy_col in range(self.grid_width)] for dummy_row in range(self.grid_height)] | python | {
"resource": ""
} |
q57369 | Grid.save | train | def save(self, fname):
""" saves a grid to file as ASCII text """
try:
with open(fname, "w") as f:
f.write(str(self))
except Exception as ex:
print('ERROR = cant save grid results to ' + fname + str(ex)) | python | {
"resource": ""
} |
q57370 | Grid.load | train | def load(self, fname):
""" loads a ASCII text file grid to self """
# get height and width of grid from file
self.grid_width = 4
self.grid_height = 4
# re-read the file and load it
self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in ra... | python | {
"resource": ""
} |
q57371 | Grid.extract_col | train | def extract_col(self, col):
"""
get column number 'col'
"""
new_col = [row[col] for row in self.grid]
return new_col | python | {
"resource": ""
} |
q57372 | Grid.extract_row | train | def extract_row(self, row):
"""
get row number 'row'
"""
new_row = []
for col in range(self.get_grid_width()):
new_row.append(self.get_tile(row, col))
return new_row | python | {
"resource": ""
} |
q57373 | Grid.replace_row | train | def replace_row(self, line, ndx):
"""
replace a grids row at index 'ndx' with 'line'
"""
for col in range(len(line)):
self.set_tile(ndx, col, line[col]) | python | {
"resource": ""
} |
q57374 | Grid.replace_col | train | def replace_col(self, line, ndx):
"""
replace a grids column at index 'ndx' with 'line'
"""
for row in range(len(line)):
self.set_tile(row, ndx, line[row]) | python | {
"resource": ""
} |
q57375 | Grid.new_tile | train | def new_tile(self, num=1):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
for _ in range(num):
if random.random() > .5:
new_tile = self.pieces[0]
... | python | {
"resource": ""
} |
q57376 | Grid.set_tile | train | def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
"""
#print('set_tile: y=', row, 'x=', col)
if col < 0:
print("ERROR - x less than zero", col)
col = 0
#return
if col > s... | python | {
"resource": ""
} |
q57377 | Grid.replace_grid | train | def replace_grid(self, updated_grid):
"""
replace all cells in current grid with updated grid
"""
for col in range(self.get_grid_width()):
for row in range(self.get_grid_height()):
if updated_grid[row][col] == EMPTY:
self.set_empty(row, col... | python | {
"resource": ""
} |
q57378 | Grid.find_safe_starting_point | train | def find_safe_starting_point(self):
"""
finds a place on the grid which is clear on all sides
to avoid starting in the middle of a blockage
"""
y = random.randint(2,self.grid_height-4)
x = random.randint(2,self.grid_width-4)
return y, x | python | {
"resource": ""
} |
q57379 | resize | train | def resize(fname, basewidth, opFilename):
""" resize an image to basewidth """
if basewidth == 0:
basewidth = 300
img = Image.open(fname)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
i... | python | {
"resource": ""
} |
q57380 | print_stats | train | def print_stats(img):
""" prints stats, remember that img should already have been loaded """
stat = ImageStat.Stat(img)
print("extrema : ", stat.extrema)
print("count : ", stat.count)
print("sum : ", stat.sum)
print("sum2 : ", stat.sum2)
print("mean : ", stat.mean... | python | {
"resource": ""
} |
q57381 | print_all_metadata | train | def print_all_metadata(fname):
""" high level that prints all as long list """
print("Filename :", fname )
print("Basename :", os.path.basename(fname))
print("Path :", os.path.dirname(fname))
print("Size :", os.path.getsize(fname))
img = Image.open(fname)
# get the image's wi... | python | {
"resource": ""
} |
q57382 | get_metadata_as_dict | train | def get_metadata_as_dict(fname):
""" Gets all metadata and puts into dictionary """
imgdict = {}
try:
imgdict['filename'] = fname
imgdict['size'] = str(os.path.getsize(fname))
imgdict['basename'] = os.path.basename(fname)
imgdict['path'] = os.path.dirname(fname)
img ... | python | {
"resource": ""
} |
q57383 | get_metadata_as_csv | train | def get_metadata_as_csv(fname):
""" Gets all metadata and puts into CSV format """
q = chr(34)
d = ","
res = q + fname + q + d
res = res + q + os.path.basename(fname) + q + d
res = res + q + os.path.dirname(fname) + q + d
try:
res = res + q + str(os.path.getsize(fname)) + q + d
... | python | {
"resource": ""
} |
q57384 | add_text_to_image | train | def add_text_to_image(fname, txt, opFilename):
""" convert an image by adding text """
ft = ImageFont.load("T://user//dev//src//python//_AS_LIB//timR24.pil")
#wh = ft.getsize(txt)
print("Adding text ", txt, " to ", fname, " pixels wide to file " , opFilename)
im = Image.open(fname)
draw = ImageD... | python | {
"resource": ""
} |
q57385 | add_crosshair_to_image | train | def add_crosshair_to_image(fname, opFilename):
""" convert an image by adding a cross hair """
im = Image.open(fname)
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=(255, 255, 255))
draw.line((0, im.size[1], im.size[0], 0), fill=(255, 255, 255))
del draw
im.save(opFilename) | python | {
"resource": ""
} |
q57386 | filter_contour | train | def filter_contour(imageFile, opFile):
""" convert an image by applying a contour """
im = Image.open(imageFile)
im1 = im.filter(ImageFilter.CONTOUR)
im1.save(opFile) | python | {
"resource": ""
} |
q57387 | get_img_hash | train | def get_img_hash(image, hash_size = 8):
""" Grayscale and shrink the image in one step """
image = image.resize((hash_size + 1, hash_size), Image.ANTIALIAS, )
pixels = list(image.getdata())
#print('get_img_hash: pixels=', pixels)
# Compare adjacent pixels.
difference = []
for row in range... | python | {
"resource": ""
} |
q57388 | load_image | train | def load_image(fname):
""" read an image from file - PIL doesnt close nicely """
with open(fname, "rb") as f:
i = Image.open(fname)
#i.load()
return i | python | {
"resource": ""
} |
q57389 | dump_img | train | def dump_img(fname):
""" output the image as text """
img = Image.open(fname)
width, _ = img.size
txt = ''
pixels = list(img.getdata())
for col in range(width):
txt += str(pixels[col:col+width])
return txt | python | {
"resource": ""
} |
q57390 | NormInt | train | def NormInt(df,sampleA,sampleB):
"""
Normalizes intensities of a gene in two samples
:param df: dataframe output of GetData()
:param sampleA: column header of sample A
:param sampleB: column header of sample B
:returns: normalized intensities
"""
c1=df[sampleA]
c2=df[sampleB]
... | python | {
"resource": ""
} |
q57391 | is_prime | train | def is_prime(number):
"""
Testing given number to be a prime.
>>> [n for n in range(100+1) if is_prime(n)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
if number < 2:
return False
if number % 2 == 0:
return number == 2
... | python | {
"resource": ""
} |
q57392 | QmedAnalysis.qmed_all_methods | train | def qmed_all_methods(self):
"""
Returns a dict of QMED methods using all available methods.
Available methods are defined in :attr:`qmed_methods`. The returned dict keys contain the method name, e.g.
`amax_record` with value representing the corresponding QMED estimate in m³/s.
... | python | {
"resource": ""
} |
q57393 | QmedAnalysis._qmed_from_amax_records | train | def _qmed_from_amax_records(self):
"""
Return QMED estimate based on annual maximum flow records.
:return: QMED in m³/s
:rtype: float
"""
valid_flows = valid_flows_array(self.catchment)
n = len(valid_flows)
if n < 2:
raise InsufficientDataErro... | python | {
"resource": ""
} |
q57394 | QmedAnalysis._pot_month_counts | train | def _pot_month_counts(self, pot_dataset):
"""
Return a list of 12 sets. Each sets contains the years included in the POT record period.
:param pot_dataset: POT dataset (records and meta data)
:type pot_dataset: :class:`floodestimation.entities.PotDataset`
"""
periods = p... | python | {
"resource": ""
} |
q57395 | QmedAnalysis._qmed_from_area | train | def _qmed_from_area(self):
"""
Return QMED estimate based on catchment area.
TODO: add source of method
:return: QMED in m³/s
:rtype: float
"""
try:
return 1.172 * self.catchment.descriptors.dtm_area ** self._area_exponent() # Area in km²
ex... | python | {
"resource": ""
} |
q57396 | QmedAnalysis._qmed_from_descriptors_1999 | train | def _qmed_from_descriptors_1999(self, as_rural=False):
"""
Return QMED estimation based on FEH catchment descriptors, 1999 methodology.
Methodology source: FEH, Vol. 3, p. 14
:param as_rural: assume catchment is fully rural. Default: false.
:type as_rural: bool
:return:... | python | {
"resource": ""
} |
q57397 | QmedAnalysis._qmed_from_descriptors_2008 | train | def _qmed_from_descriptors_2008(self, as_rural=False, donor_catchments=None):
"""
Return QMED estimation based on FEH catchment descriptors, 2008 methodology.
Methodology source: Science Report SC050050, p. 36
:param as_rural: assume catchment is fully rural. Default: false.
:t... | python | {
"resource": ""
} |
q57398 | QmedAnalysis._pruaf | train | def _pruaf(self):
"""
Return percentage runoff urban adjustment factor.
Methodology source: eqn. 6, Kjeldsen 2010
"""
return 1 + 0.47 * self.catchment.descriptors.urbext(self.year) \
* self.catchment.descriptors.bfihost / (1 - self.catchment.descriptors.bfihos... | python | {
"resource": ""
} |
q57399 | QmedAnalysis._dist_corr | train | def _dist_corr(dist, phi1, phi2, phi3):
"""
Generic distance-decaying correlation function
:param dist: Distance between catchment centrolds in km
:type dist: float
:param phi1: Decay function parameters 1
:type phi1: float
:param phi2: Decay function parameters ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.