content stringlengths 42 6.51k |
|---|
def _get_list_feat_names(idx_feat_dict, num_pair):
"""Creates flattened list of (repeated) feature names.
The indexing corresponds with the flattened list of T values and the
flattened list of p-values obtained from _get_list_signif_scores().
Arguments:
idx_feat_dict: {int: string}
... |
def _number_channels(rgb: bool) -> int:
"""Determines the number of channels corresponding to a RGB flag."""
if rgb:
return 3
else:
return 1 |
def vector_add(vec1, vec2):
""" Returns the vector addition of the two vectors"""
(px1, py1), (px2, py2) = vec1, vec2
return (px1 + px2, py1 + py2) |
def parse_size(s):
"""
s: <number>[<k|m|g|t>]
Returns the number of bytes.
"""
try:
if s[-1].isdigit():
return int(s)
n, unit = float(s[0:-1]), s[-1].lower()
if unit == 'k':
return int(n * 1024)
if unit == 'm':
return int(n * 1024 *... |
def split(text, delimiter=','):
"""
Split a comma-separated list of strings.
:param text: The text to split (a string).
:param delimiter: The delimiter to split on (a string).
:returns: A list of zero or more nonempty strings.
Here's the default behavior of Python's built in :func:`str.split()... |
def Precipitation(prec, temp, tt, rfcf, sfcf):
"""
========================================================
Precipitation (temp, tt, prec, rfcf, sfcf)
========================================================
Precipitaiton routine of the HBV96 model.
If temperature is lower than TT [degree C], ... |
def get_key_value_from_line( string ):
"""Takes a string, splits by the FIRST equal sign and sets it equal to key, value
aws_session_token=1234ASDF=B returns ("aws_session_token", "1234ASDF=B") """
split_by_equal = string.split('=')
key = split_by_equal[0]
if len(split_by_equal) > 1:
valu... |
def is_archive(filepath):
"""Determines whether the given filepath has an archive extension from the
following list:
`.zip`, `.rar`, `.tar`, `.tar.gz`, `.tgz`, `.tar.bz`, `.tbz`.
Args:
filepath: a filepath
Returns:
True/False
"""
return filepath.endswith(
(".zip", ... |
def helper(x):
"""prints help"""
print(x)
return x |
def get_input_file_dictionary(indata):
"""
Return an input file dictionary.
Format: {'guid': 'pfn', ..}
Normally use_turl would be set to True if direct access is used.
:param indata: list of FileSpec objects.
:return: file dictionary.
"""
ret = {}
for fspec in indata:
ret... |
def get_log(name=None):
"""Return a console logger.
Output may be sent to the logger using the `debug`, `info`, `warning`,
`error` and `critical` methods.
Parameters
----------
name : str
Name of the log.
References
----------
.. [1] Logging facility for Python,
... |
def normalize(value):
"""
Function normalizes value by replacing periods, commas, semi-colons,
and colons.
:param value: Raw value
:rtype: String with punctuations removed
"""
if value:
return value.replace('.', '').strip(',:/; ') |
def limited(x, z, limit):
"""Logic that is common to invert and change."""
if x != 0:
return min(z, limit)
else:
return limit |
def cipher(text, shift, encrypt=True):
"""
Encrypts a given input alphabetical text string.
Parameters
----------
text : str
This is the input text data sent to be ciphered (should be English).
shift : int
This is the ficed number that each letter is replaced by a letter some fixed... |
def add_dicts(*args, **kwargs):
"""
Utility to "add" together zero or more dicts passed in as positional
arguments with kwargs. The positional argument dicts, if present, are not
mutated.
"""
result = {}
for d in args:
result.update(d)
result.update(kwargs)
return result |
def getDatasetName(token, channel_list, colors, slice_type):
"""Return a dataset name given the token, channel, colors and slice_type"""
if colors is not None:
channel_list = ["{}:{}".format(a,b) for a,b in zip(channel_list, colors)]
return "{}-{}-{}".format(token, ','.join(channel_list), slice_type) |
def format_tune_scores(results):
"""
Creates a tune_results dict from the output of get_tune_output_dol applied to the results output by fit_and_score.
This creates the proper score names e.g. train_score, test_score, etc. It also formats the tune parameter list.
Parameters
----------
results:... |
def galois_multiply(a, b):
"""Galois Field multiplicaiton for AES"""
p = 0
while b:
if b & 1:
p ^= a
a <<= 1
if a & 0x100:
a ^= 0x1b
b >>= 1
return p & 0xff |
def __insert_color(txt,s,c):
"""insert HTML span style into txt. The span will change the color of the
text located between s[0] and s[1]:
txt: txt to be modified
s: span of where to insert tag
c: color to set the span to"""
return txt[:s[0]]+'<span style="color: {0};">'.format(c)+\
t... |
def _UTMLetterDesignator(lat):
"""
This routine determines the correct UTM letter designator for the
given latitude returns 'Z' if latitude is outside the UTM limits of
84N to 80S.
Written by Chuck Gantz- chuck.gantz@globalstar.com
"""
if 84 >= lat >= 72: return 'X'
elif 72 > lat >= 64: ... |
def lcm(x, y):
"""
Compute the least common multiple of x and y. This function is used for running statistics.
"""
greater = max(x, y)
while True:
if (greater % x == 0) and (greater % y == 0):
lcm = greater
break
greater += 1
return lcm |
def _default_function(l, default, i):
"""
EXAMPLES::
sage: from sage.combinat.integer_vector import _default_function
sage: import functools
sage: f = functools.partial(_default_function, [1,2,3], 99)
sage: f(-1)
99
sage: f(0)
1
sage: f(1)
... |
def prime_sampler_state(n, exclude):
"""
Initialize state to be used in fast sampler. Helps ensure excluded items are
never sampled by placing them outside of sampling region.
"""
# initialize typed numba dicts
state = {n: n}
state.pop(n)
track = {n: n}
track.pop(n)
n_pos = n - ... |
def translate(num_list, transl_dict):
""" Translates integer list to number word list (no error handling!)
Args:
num_list: list with interger items.
transl_dict: dictionary with integer keys and number word values.
Returns:
list of strings which are the translated numbers into word... |
def snake_to_camel_case(snake_text):
"""
Converts snake case text into camel case
test_path --> testPath
:param snake_text:str
:return: str
"""
components = snake_text.split('_')
# We capitalize the first letter of each component except the first one with
# the 'title' method and j... |
def list_rar (archive, compression, cmd, verbosity, interactive):
"""List a RAR archive."""
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
if not interactive:
cmdlist.extend(['-p-', '-y'])
cmdlist.extend(['--', archive])
return cmdlist |
def get_free_residents(resident_prefs, matching):
""" Return a list of all residents who are currently unmatched but have a
non-empty preference list. """
return [
resident
for resident in resident_prefs
if resident_prefs[resident]
and not any([resident in match for match in... |
def qualify_raw_term(term):
"""Does some qualification on the unprocessed term.
"""
try:
if "__" in term:
return False
if "--" in term:
return False
except Exception:
return False
return True |
def ConfigName(deployment, name):
"""Returns the name of the config.
Args:
deployment: the name of the deployment.
name: the "tag" used to differentiate this config from others.
Returns:
The name of the config.
"""
return "{}-config-{}".format(deployment, name) |
def sem(e):
"""Church numbers semantics"""
return e(lambda x: x + 1)(0) |
def ishappy(n):
"""
Takes an input of a number to check if it is happy
Returns bool values True for a happy number and False for unhappy numbers
"""
cache=[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139,
167, 176, 188, 190, ... |
def josephus_survivor(n, k):
"""
Finds the last survivor given an integer of the sum of people and an integer for the amount of steps to take.
:param n: an integer of people.
:param k: an integer of steps.
:return: the lone survivor.
"""
r = 0
for x in range(1, n + 1):
r = (r + k... |
def find_journal(issn, journal_dictionary):
"""
Given an issn, and a journal_dictinary, find the journal in VIVO with that
UFID. Return True and URI if found. Return False and None if not found
"""
try:
uri = journal_dictionary[issn]
found = True
except:
uri = None
... |
def edges_intersect(a1, a2, b1, b2):
"""
The algorithm for determining whether two lines intersect or not:
https://www.geometrictools.com/Documentation/IntersectionLine2Circle2.pdf
This one is the same, with visualization: http://geomalgorithms.com/a05-_intersect-1.html
a and b are vector representa... |
def standard_time_display(cur_time):
"""Covert time with second format into hour:minute:second format.
Inputs:
cur_time: current time(s), type(int)
Returns:
stand_time: standard time(h:m:s), type(char)
"""
assert type(cur_time) is float
# ms
if cur_time < 1:
msecond =... |
def isNumber(s):
"""Checks if s is number"""
if s is None:
return False
try:
float(s)
return True
except ValueError:
return False |
def not_found_pretty(needle, lines):
"""
Returns a pretty-print assert message.
"""
return 'Not found in settings: %(needle)s\n' \
'---------------\n' \
'%(lines)s' % {
'needle': needle,
'lines': '\n'.join(lines)
} |
def merge_dicts(x, y):
"""A function to merge two dictionaries, making it easier for us to make modality specific queries
for dwi images (since they have variable extensions due to having an nii.gz, bval, and bvec file)
Parameters
----------
x : dict
dictionary you want merged with y
y ... |
def add_alpha_to_rgb(color_code: str) -> str:
"""
@brief Add the alpha part to a valid RGB color code (#RGB, #RRGGBB, #RRGGBBAA)
@param color_code The color code
@return The color code in the form of #RRGGBBAA
"""
if not color_code:
return ""
rgb = color_code[1:9] # strip "#" an... |
def FormatToMinDP(val, max_dp):
""" Format val as a string with the minimum number of required decimal places, up to a maximum of max_dp. """
num_dp = 0
while True:
pow = -1 * num_dp
if val % (10 ** pow) == 0.0 or num_dp == max_dp:
break
num_dp += 1
return "{{0:.... |
def _inject_args(sig, types):
"""
A function to inject arguments manually into a method signature before
it's been parsed. If using keyword arguments use 'kw=type' instead in
the types array.
sig the string signature
types a list of types to be inserted
Returns the altered signat... |
def _make_memoryview(size):
"""
Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
size.
"""
return memoryview(bytearray(size)) |
def requeue_list(obj, idx):
"""
Returns the element at index after moving it to the beginning of the queue.
:param obj: list
:param idx: index
:return: list
"""
obj.insert(0, obj.pop(idx))
return obj |
def is_single_bool(val):
"""
Checks whether a variable is a boolean.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a boolean. Otherwise False.
"""
return type(val) == type(True) |
def list_of_ints(st1, blk):
"""function to process a comma seperated list of ints."""
st1 = st1.split(',')
return st1 |
def get_wiki_arxiv_url(wiki_dump_url, href):
"""Return a full URL from the href of a .bz2 archive."""
return '{}/{}'.format(wiki_dump_url, href) |
def clean_ingredients(dish_name, dish_ingredients):
"""
:param dish_name: str
:param dish_ingredients: list
:return: tuple of (dish_name, ingredient set)
This function should return a `tuple` with the name of the dish as the first item,
followed by the de-duped `set` of ingredients as the secon... |
def get_last_names(_lst):
"""Return list of creator last names"""
names = [x.split(', ') for x in _lst]
_res = [n[0] for n in names]
return _res |
def list2dict(data):
"""
convert list to dict
:param data:
:return:
"""
data = {data[i]: i for i in range(len(data))}
return data |
def getPerson(replace=None, delete=None):
"""Generate valid Person."""
return {
'name': 'Teppo',
'email': 'email@example.com',
'identifier': 'person_identifier'
} |
def getChars( data ):
"""Generates a set of all characters in the data set."""
chars = set([])
for i in range( len(data) ):
chars.update( set( data["text"][i] ) )
return chars |
def _ag_checksum(data):
"""
Compute a telegram checksum.
"""
sum = 0
for c in data:
sum ^= c
return sum |
def split_era_year(galatic_date):
"""Separate the Galatic date into era (e.g., BBY, ABY) and year.
Parameters:
galatic_date (str): Galatic year and era (e.g., 19BBY)
Returns:
tuple: era, year
"""
return galatic_date[-3:], float(galatic_date[:-3]) |
def template_email_link(text_body, html_body, attachment_html, link):
""" Template text and html body text assumes that static
template placeholder {{link}} exists in attachment link
Args:
textBody: plain text version of email
htmlBody: html version of email
attachmentHtml: surr... |
def ship_size(data, coordinates):
"""
(data, tuple) -> (tuple)
A function based on read data and cell coordinates (for example ("J", 1) or
("A", 10)) defines the size of the ship, part of which is in this cell.
"""
size = 1
let_num = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, ... |
def _find_slice_interval(f, r, x, u, D, w=1.):
"""Given a point u between 0 and f(x), returns an approximated interval
under f(x) at height u.
"""
a = x - r*w
b = x + (1-r)*w
if a < D[0]:
a = D[0]
else:
while f(a) > u:
a -= w
if a < D[0]:
... |
def parse_dict(input_data):
"""Return a rules dict of the format:
{
'light red': [(1, 'bright white'), (2, 'muted yellow')],
'dark orange': [(3, bright white), (4, muted yellow)],
'faded blue': [(0, 'bags')]
}
"""
bags = dict()
for line in input_data.split('\n'):
outer, ... |
def shouldProcess(app):
""" Check if an app should be downloaded and analyzed. """
if not 'internet' in app:
return False
if not 'unchecked' in app:
return False
return app['internet'] and app['unchecked'] and app['price'] == u'Free' |
def get_repeated_labels(labels):
"""Get duplicate labels."""
seen = set()
rep = []
for x in labels:
if x in seen:
rep.append(x)
seen.add(x)
return rep |
def gcd(a, b):
"""
@brief Greatest common divisor: O(log(a + b))
"""
if a % b == 0:
return b
else:
return gcd(b, a % b) |
def _cmp(a, b):
"""
Port of Python 2's cmp function.
"""
# https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
return (a > b) - (a < b) |
def IsOwner(unused_action, user, entity):
"""An authorized_function that checks to see if user is an entity owner."""
return hasattr(entity, 'owner') and entity.owner == user.user_id() |
def flatten_dict(dct, old_k=str()):
"""Take nested dictionaries, combine it into one dictionary
:param dct: A dict
:param old_k: Previous key, for reduction
:returns: A dict, no nested dicts within
"""
out = dict()
for k, v in dct.items():
new_k = "{}.{}".format(old_k, k)
if... |
def gt(value, arg):
"""Returns a boolean of whether the value is greater than the argument."""
return value > int(arg) |
def hamilton_product(q1, q2):
"""
Performs composition of two quaternions by Hamilton product. This is equivalent
of a rotation descried by quaternion_1 (q1), followed by quaternion_2 (q2).
https://en.wikipedia.org/wiki/Quaternion#Hamilton_product
:param q1: 4-item iterable representing unit quaternion.
:... |
def _avg(count, avg, new_num):
"""Incremental average.
:param count: int -- The previous total.
:param avg: float -- The previous average.
:param new_num: int|float -- The new number.
:return: float -- The new average.
"""
if not count:
return float(new_num)
return (count * avg ... |
def create_ordered_list(data_dict, items):
"""Creates an ordered list from a dictionary.
Each dictionary key + value is added to a list, as a nested list.
The position of the nested item is determined by the position of the key
value in the items list. The returned list is the dictionary ordered on... |
def isint(value):
"""
Check if value can be converted to int
:param value: input value
:return: True/False
"""
try:
int(value)
return True
except ValueError:
return False |
def numel(shape):
"""Obtain total number of elements from a tensor (ndarray) shape.
Args:
shape: A list or tuple represenitng a tensor (ndarray) shape.
"""
output = 1
for dim in shape:
output *= dim
return output |
def get_palette(num_cls):
"""
Returns the color map for visualizing the segmentation mask.
Args:
num_cls: Number of classes
Returns:
The color map
"""
n = num_cls
palette = [0] * (n * 3)
for j in range(0, n):
lab = j
palette[j * 3 + 0] = 0
palette[... |
def check_vertical_win_conditions(board, player):
"""returns True if the given player has a vertical winning triple and False otherwise."""
# Your code starts here.
for col_index in range(len(board[0])):
char_count = 0
for row_index in range(len(board)):
if board[row_index][col_i... |
def eps2chi(eps):
"""Calculate chi ellipticity from epsilon.
Args:
eps: a real or complex number, or a numpy array thereof.
Returns:
The chi ellipticity in the same shape as the input.
"""
return 2*eps/(1 + abs(eps)**2) |
def getIntersections( intervals ):
"""combine intervals.
Overlapping intervals are reduced to their intersection.
"""
if not intervals: return []
intervals.sort()
max_to = intervals[0][1]
all_sections = []
sections = [ intervals[0][0], intervals[0][1] ]
for this_from, this_to in i... |
def GetPlistValue(plist, value):
"""Returns the value of a plist dictionary, or False."""
try:
return plist[value]
except KeyError:
return False |
def find_min(L: list, b: int) -> int:
"""Precondition: L[b:] is not empty.
Return the index of the smallest value in L[b:].
>>> find_min([3, -1, 7, 5], 0)
1
>>> find_min([3, -1, 7, 5], 1)
1
>>> find_min([3, -1, 7, 5], 2)
3
"""
smallest = b # The index of the smallest so far
... |
def check_primitive_type(stmt):
"""i_type_spec appears to indicate primitive type.
"""
return True if getattr(stmt, "i_type_spec", None) else False |
def is_empty(inp):
"""
True if none or empty
:param inp:
:return:
"""
return inp is None or len(inp) == 0 |
def sort_rows_for_csv(part):
"""this is the sort function that is used to determine the order of the
lines of the csv"""
if part['NAME'].find(','):
stri = part['NAME'].split(',')[0]
else:
stri = part['NAME']
if 'DO_NOT_PLACE' in part:
return '0'
if 'PROVIDED_BY' in part:
... |
def float2str(flt, separator=".", precision=None, prefix=None, suffix=None):
"""
Converts a floating point number into a string.
Contains numberous options on how the output string should be
returned including prefixes, suffixes, floating point precision,
and alternative decimal separators.
P... |
def abbe_number(nd, nF, nC):
""" Compute the Abbe number (reciprocal dispersion). Using the visible F,
d, and C lines:
F(H): 486.1 nm
d(He): 587.6 nm
C(H): 656.3 nm
nd, nF, and nC are the refractive indicies at each of these three lines.
Todo: Alternate... |
def average(values):
"""Calculates an unweighted average
Args:
values (Iterable): The values to find the average of
Returns:
The average of the inputs
Example:
>>> average([1, 2, 3])
2
"""
res = sum(values) / len(values)
if res == int(res):
return... |
def is_compatible_data_type(expected_data_type, actual_data_type):
"""
Returns boolean value indicating whether the actual_data_type argument is compatible
with the expected_data_type, from a data typing perspective
:param expected_data_type:
:param actual_data_type:
:return:
"""
retval... |
def normalize_sequence(value, rank):
"""For scalar input, duplicate it into a sequence of rank length. For
sequence input, check for correct length.
"""
# Like e.g. scipy.ndimage.zoom() -> _ni_support._normalize_sequence().
try:
lst = list(value)
except TypeError:
lst = [value] *... |
def resource_filename(lang_code: str, resource_type: str, resource_code: str) -> str:
"""
Return the formatted resource_filename given lang_code,
resource_type, and resource_code.
"""
return "{}_{}_{}".format(lang_code, resource_type, resource_code) |
def decode(to_decode):
"""
Moves all the uppercase character to the beginning of the
string and case the lowercase characters to uppercase.
Parameters:
to_decode: A string that is not all lowercase
Returns:
A decoded string.
>>> decode(" neHAw yePParY")
'HAPPY NEW YEAR'
>... |
def arg_xor_dict(args_array, opt_xor_dict):
"""Function: arg_xor_dict
Description: Does a Xor check between a key in opt_xor_dict and its values
using args_array for the check. Therefore, the key can be in
args_array or one or more of its values can be in arg_array, but both
can not... |
def _find_argument_unquoted(pos: int, text: str) -> int:
"""
Get the number of the argument at position pos in
a string without interpreting quotes.
"""
ret = text.split()
search = 0
argnum = 0
for i, elem in enumerate(ret):
elem_start = text.find(elem, search)
elem_end =... |
def bfsAllPaths(graph, start, goal):
"""Finds all paths between 2 nodes in a graph using BFS
Args:
graph (dict): Search space represented by a graph
start (str): Starting state
goal (str): Goal state
Returns:
solutions (list): List of the paths that bring you from the start... |
def squeeze(data):
"""Squeeze a sequence."""
count = [1]
values = [data[0]]
for value in data[1:]:
if value == values[-1]:
count[-1] += 1
else:
values.append(value)
count.append(1)
return count, values |
def filter_user(user_ref):
"""Filter out private items in a user dict.
'password', 'tenants' and 'groups' are never returned.
:returns: user_ref
"""
if user_ref:
user_ref = user_ref.copy()
user_ref.pop('password', None)
user_ref.pop('tenants', None)
user_ref.pop('g... |
def frequencies(word_list):
"""
Takes a list of words and returns a dictionary associating
words with frequencies of occurrence
"""
word_freqs = {}
for word in word_list:
if word in word_freqs:
word_freqs[word] += 1
else:
word_freqs[word] = 1
return wo... |
def get_wstart(ref, wave_ref, wave_per_pixel):
"""
Obtain the starting wavelength of a spectrum.
Parameters
----------
ref: int,
Reference pixel.
wave_ref: float,
Coordinate at reference pixel.
wave_per_pixel: float,
Coordinate increase per pixel.
Returns
... |
def maxProfitB(prices):
"""
:type prices: List[int]
:rtype: int
"""
maxCur=0
maxSoFar=0
for i in range(1,len(prices)):
maxCur+=prices[i]-prices[i-1]
maxCur=max(0,maxCur)
maxSoFar=max(maxCur,maxSoFar)
return maxSoFar |
def make_players(player_data, match_id):
"""Make player structures."""
return [
dict(
player,
user=dict(
id=player['user_id'],
name=player['name'],
platform_id=player['platform_id'],
person=dict(
... |
def process_line(line):
"""Return the structure frequencies for a line of STRIDE data."""
result = {}
for structure in line.split():
result[structure] = result.get(structure, 0) + 1
return result |
def _sanity_check_kwargs(args):
"""Sanity check after setting up input arguments, handling back compatibility
"""
if not args.get("workflow") and not args.get("run_info_yaml"):
return ("Require a sample YAML file describing inputs: "
"https://bcbio-nextgen.readthedocs.org/en/latest/c... |
def get_slice(index):
"""Returns a slice converted from index."""
if index == -1:
return slice(0, None)
if isinstance(index, int):
# return slice(index, index+1)
return index
if isinstance(index, tuple):
return slice(index[0], index[1])
if isinstance(index, slice)... |
def subset_sum(x, R):
"""Subsetsum
:param x: table of non negative values
:param R: target value
:returns bool: True if a subset of x sums to R
:complexity: O(n*R)
"""
b = [False] * (R + 1)
b[0] = True
for xi in x:
for s in range(R, xi - 1, -1):
b[s] |= b[s - xi]... |
def get_variable_name_list(expressions):
"""Get variable names from a given expressions list"""
return sorted(list({symbol.name for expression in expressions for symbol in expression.free_symbols if "x" in symbol.name})) |
def ensure_list(name, value, item_type=None):
"""Raise an error if value is not a list or, optionally, contains elements
not of a specified type."""
if not isinstance(value, list):
raise TypeError("{} must be a list: {}".format(name, value))
if item_type:
for item in value:
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.