content stringlengths 42 6.51k |
|---|
def aggregate_section_totals(section_name, results_arr, daily):
"""Hackish function to do a summation of a section in the org_report"""
#go through the array and go to the index that my section name is
startindex = -1
endindex = -1
for itemarr in results_arr:
if itemarr[1] == section_nam... |
def _warmup_adjust_learning_rate(
init_lr, n_epochs, epoch, n_iter, iter=0, warmup_lr=0
):
"""adjust lr during warming-up. Changes linearly from `warmup_lr` to `init_lr`."""
T_cur = epoch * n_iter + iter + 1
t_total = n_epochs * n_iter
new_lr = T_cur / t_total * (init_lr - wa... |
def powerset(lst):
"""typically L=['one', 'two'] - return list of lists
"""
if lst == []:
return [[]] #return empty list of list
lose_it = powerset(lst[1:]) #lost the first element in the list
use_it = map(lambda x: [lst[0]] + x, lose_it) #add the first element to the lose_it
return... |
def dict_to_obj(our_dict):
"""
Function that takes in a dict and returns a custom object associated with
the dict. This function makes use of the "__module__" and "__class__"
metadata in the dictionary to know which object type to create.
"""
if "__class__" in our_dict:
# Pop ensures we... |
def clear_bits(val, offs, n):
""" Clear number of bits 'n' at specific offset 'offs' in value."""
return val & ~((2**n - 1) << offs) |
def join(sequence, separator):
"""
Return a string concatenation with separator between elements.
"""
string = ''
for letter in sequence:
string += letter + separator
if separator == '':
return string
return string[:-1] |
def whitespace_split(s, nrsplits=-1):
"""
Splits a string on whitespace. Very similar to Python's built-in
s.split(None, nrsplits), but pads the result with empty strings
so that it always returns (nrsplits+1) strings.
"""
splits = s.split(None, nrsplits)
if nrsplits >= 0 and len(splits) <... |
def quick_ratio(cash, investments, receivables, current_liabilities):
"""Computes quick ratio.
Parameters
----------
cash : int or float
Cash
investments : int or float
Short-term marketible investments
receivables : int or float
Receivables
current_liabilities : int... |
def get_table_name_schema(str_list):
"""returns string which represented table name including data base name,
schema name, table name"""
str_list_quotes = str_list[:-1] + ['"' + str_list[-1] + '"']
return '.'.join(filter(None, str_list_quotes)) |
def uniform_t_sequence(steps: int):
"""
Creates a sequence of t parameters whose values are equally
spaced and go from 0 to 1 using the given number of steps.
:param steps: number of steps
:return: sequence of t values
"""
return [t / steps for t in range(steps + 1)] |
def resolver_has_tag(f, tag):
"""
Checks to see if a function has a specific tag.
"""
if not hasattr(f, '_resolver_tags'):
return False
return tag in f._resolver_tags |
def file_allowed(filename, allowed_extensions):
"""Does filename have the right extension?"""
return "." in filename and filename.rsplit('.', 1)[1] in allowed_extensions |
def process_adp_tx_params(tx_params):
"""Takes the parameter text from ADP TX params section and converts to dictionary
:param tx_params: The parameter text from the ADP TX parameter section
:type tx_params: str
:return: Result dictionary with the keys and values
:rtype: dict
"""
# input is... |
def textstat(text, fp):
""" @text: decipher msg, return a dict of stat
@stat: dict with exact size of fingerprint dict: fp, value is integer frequency
"""
stat=fp # copy keys from fingerprint dict
#print stat
for k in fp: # for k,v in stat.iteritems()
stat[k]=sum([k==c for ... |
def sort(A):
"""Insertion sort."""
for i in range(1, len(A)):
e = A[i]
j = i - 1
while j >= 0 and A[j] > e:
A[j + 1] = A[j]
j -= 1
A[j + 1] = e
return A |
def first_argmax(input_list) -> int:
"""This function returns the index of the max value. If there are duplicate max values in input_list,
the index of the first maximum value found will be returned.
Args:
input_list (list): list for which we want to find the argmax
Returns:
idx_max (int... |
def is_valid_ur(ur):
""" Checks ur parameter """
values = ['rect', 'tric', 'compact']
return ur in values |
def IsTelemetryCommand(command):
"""Attempts to discern whether or not a given command is running telemetry."""
return ('tools/perf/run_' in command or 'tools\\perf\\run_' in command) |
def concat_dictionaries(a: dict, b: dict) -> dict:
"""
Append one dictionary below another. If duplicate keys exist, then the key-value pair of the second supplied
dictionary will be used.
"""
return {**a, **b} |
def get_speakers(items):
"""Returns a sorted, unique list of speakers in a given dataset."""
speakers = {e[2] for e in items}
return sorted(speakers) |
def prune_nones_dict(data):
"""Remove None key/value pairs from dict."""
return {k: v for k, v in data.items() if v is not None} |
def index_of(list, val):
"""Helper to get the 0 based index of `val` in the `list`
"""
found = [i for i, k in enumerate(list) if k == val]
if len(found) > 0:
return found[0]
return None |
def count_ones(a_byte):
"""
count_ones(a_byte) : Counts the number of 1 bits in the input byte a byte
returns number_of_ones which is the number of bytes in a_byte
"""
val = 0
# loop until there are no more 1s
while a_byte > 0:
# if a_byte is odd then there is a 1 in the 1st bit
if a_byte % 2 > 0:
val += ... |
def tuple_compare_lte(left, right):
"""Compare two 'TupleOf' instances by comparing their individual elements."""
for i in range(min(len(left), len(right))):
if left[i] > right[i]:
return False
if left[i] < right[i]:
return True
return len(left) <= len(right) |
def guess_type_value(x, none=None):
"""
Guessees the type of a value.
@param x type
@param none if True and all values are empty, return None
@return type
@warning if an integer starts with a zero, then it is a string
"""
try:
int(x)
... |
def get_longitudes(pnt, lon, rad=3.0):
"""
Selects longitudes from a list of pointings
Parameters
----------
pnt : list of dict
Pointings
lon : float
Galactic longitude (deg)
rad : float, optional
Selection radius (deg)
Returns
-------
pnt : list of dict... |
def median(xs):
"""Return median of sequence data."""
n = len(xs)
if n < 1:
return None
elif n % 2 == 1:
return sorted(xs)[n//2]
else:
return sum(sorted(xs)[n//2-1:n//2+1])/2.0 |
def flatten_results(results):
"""Results structures from nested Gibbs samplers sometimes
need flattening for writing out purposes.
"""
def recurse(r):
for i in iter(r):
if isinstance(i, list):
for j in flatten_results(i):
yield j
else:... |
def map_collection(collection, map_fn):
"""map takes a single element, or a collection of elements, and applies `map_fn` on the element (or each
element when `maybe_tuple` is a collection).
It returns the result of `map_fn` in the same data format as `collection` -- i.e. dicts are returned as dicts
Arg... |
def generate_environment_dependency_metadata( elem, valid_tool_dependencies_dict ):
"""
The value of env_var_name must match the value of the "set_environment" type in the tool config's <requirements> tag set, or the tool dependency
will be considered an orphan. Tool dependencies of type set_environment ar... |
def AdjustInputArrayForRemoval(inputString, removeFrom, removeTo, defaultValue=1.0):
"""
Return an adjusted array (vector) for the removal of stages going from:
removeFrom to removeTo. Return None if no change was required
"""
outputString = ''
if not inputString:
return None
if i... |
def key_has_dot_or_dollar(d):
"""Helper function to recursively determine if any key in a
dictionary contains a dot or a dollar sign.
"""
for k, v in d.items():
if ('.' in k or k.startswith('$')) or (isinstance(v, dict) and key_has_dot_or_dollar(v)):
return True |
def is_english_word(word, english_words):
"""
Changes all letters in word to lower chase and check if it exits in the set english words
"""
return word.lower() in english_words |
def remap(indices, mapping):
"""
Converts array of index values back into category values
"""
# values = []
# for i in range(0, len(indices)):
# values.append(mapping[indices[i]])
values = [mapping[indices[i]] for i in range(len(indices))]
return values |
def get_pycache(source, names):
"""
gets all `__pycache__` directories available in names.
:param str source: source directory of contents.
:param list[str] names: name of all contents in source.
:rtype: list[str]
"""
return [name for name in names if '__pycache__' in name] |
def add_suffix_to_feature(feat,suffix):
"""
Utility method, takes a feature as returned by read_pli
(name,
[ [x0,y0],[x1,y1],...],
{ [node_label0,node_label1,...] } # optional
)
and adds a suffix to the name of the feature and the
names of nodes if they exist
"""
name=fe... |
def vtable(title, headers, data_node):
"""
Returns a dictionary representing a new table element. Tables
are specified with two main pieces of information, the headers
and the data to put into the table. Rendering of the table is
the responsibility of the Javascript in the resources directory.
... |
def get_aap_exemptions(resource_props):
"""
Gets the list of parameters that the Heat author has exempted from following
the naming conventions associated with AAP.
:param resource_props: dict of properties under the resource ID
:return: list of all parameters to exempt or an empty list
"""
... |
def delta_qu(soil, H, D):
""" Displacement at Qu
"""
if "sand" in soil:
return min(0.01 * H, 0.1 * D)
elif "clay" in soil:
return min(0.1 * H, 0.2 * D)
else:
raise ValueError("Unknown soil type.") |
def compareTriplets(a, b):
"""Problem solution."""
ap, bp = 0, 0
for i in range(len(a)):
ap += 1 if a[i] > b[i] else 0
bp += 1 if b[i] > a[i] else 0
return [ap, bp] |
def lucky(number):
""" Returns True if number is lucky """
#odd numbers are unlucky
if number % 2 == 0:
return False
sequence = [1]*(number+1)
for i in range(len(sequence)):
#zero out all even numbers
if i % 2 == 0:
sequence[i] = 0
#print(sequence)
pos... |
def subplot_shape(size):
"""Get the most square shape for the plot axes values.
If only one factor, increase size and allow for empty slots.
"""
facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0]
# re-calc for prime numbers larger than 3 to get better shape
while len(... |
def add32(a, b):
""" Add two 32-bit words discarding carry above 32nd bit,
and without creating a Python long.
Timing shouldn't vary.
"""
lo = (a & 0xFFFF) + (b & 0xFFFF)
hi = (a >> 16) + (b >> 16) + (lo >> 16)
return (-(hi & 0x8000) | (hi & 0x7FFF)) << 16 | (lo & 0xFFFF) |
def apply_generalized_force(f):
"""Applies a generalized force (f) in a manner that is consistent with Newton's
3rd law.
Parameters
----------
f: generalized force
"""
n = len(f)
tau = []
for i in range(0, n):
if i == n - 1:
tau.append(f[i])
else:
... |
def mirror(pt: float, delta: float):
"""Mirrors a value in a numberline
Args:
pt : real value in numberline
delta: value to mirror
Returns:
pt - delta, pt + delta
"""
return pt - delta, pt + delta |
def bbox_to_string(bbox):
""" Store bbox coordinated to string"""
return ' '.join([str(int(float(coord))) for coord in bbox]) |
def tail_avg(timeseries, second_order_resolution_seconds):
"""
This is a utility function used to calculate the average of the last three
datapoints in the series as a measure, instead of just the last datapoint.
It reduces noise, but it also reduces sensitivity and increases the delay
to detection.... |
def evenify(n):
"""Ensure number is even by incrementing if odd
"""
return n if n % 2 == 0 else n + 1 |
def luhn(card):
""" Credit Card Validator with Mod 10, or Luhn algorithm
referring to it's creator 'Hans Peter Luhn' """
card = str(card).replace(' ', '')
return (sum(map(int, card[1::2])) + sum(sum(map(int, str(i * 2))) for i in map(int, card[0::2]))) % 10 == 0 |
def blanks(i):
"""
Return i number of blank spaces
Used in places where reading number of blanks is tough
"""
return ''.join(' ' * i) |
def _SetAsString(settojoin):
"""Convert the set to a ordered string"""
return "".join(sorted(settojoin)) |
def inter(mb1, mb2):
"""find the point of intersection between two lines"""
x = ((mb2[1] - mb1[1]) / (mb1[0] - mb2[0]))
y = ((mb1[0] * x) + mb1[1])
return x, y |
def get_job_name(contract_id: str) -> str:
"""Get the name of a kubernetes contract job
Args:
contract_id: Id of the contract
Return:
A string of the given contract's name.
"""
return f"contract-{contract_id}" |
def getRoleLevel(role_str):
"""
Helper function to calculate role level from the role string
:param role_str str: The role level string
:returns: the level of the role as a integer
"""
role_level = 0
if role_str == 'quests':
role_level = 1
elif role_str == 'default_users':
... |
def _validate_kv(kv):
"""
check for malformed data on split
Args:
kv (list): List of key value pair
Returns:
bool: True if list contained expected pair and False otherwise
"""
if len(kv) == 2 and '' not in kv:
return True
return False |
def is_valid_name(name):
"""Returns True if name is a valid package name, else False."""
if name != name.strip():
# Reject names with leading/trailing whitespace
return False
if name in ("package", "packages"):
return False
return True |
def daemon_file_name(base_name=None, host=None, instance=None):
#===============================================================================
"""
Build a daemon output file name using optional base name, host, and instance.
"""
names = []
if not base_name is None:
names.append(base_name)
... |
def _need_exponent_sign_bit_check(max_value):
"""Checks whether the sign bit of exponent is needed.
This is used by quantized_po2 and quantized_relu_po2.
Args:
max_value: the maximum value allowed.
Returns:
An integer. 1: sign_bit is needed. 0: sign_bit is not needed.
"""
if max_value is not Non... |
def get_mac(interface):
"""
Gets the MAC address for the supplied interface or None if the MAC could
not be read from the system.
:param interface: The network interface whose MAC should be returned
:return: The unique MAC address, or None otherwise.
"""
try:
result = open('/sys/cl... |
def strip_short(s, minsize=3):
"""
Remove words with length lesser than `minsize` from `s`.
"""
return " ".join(e for e in s.split() if len(e) >= minsize) |
def set_similarity_match(set_a, set_b, threshold=0.7):
"""Check if a and b are matches."""
# Calculate Jaccard similarity
if len(set_a.union(set_b)) > 0:
ratio = len(set_a.intersection(set_b)) / float(len(set_a.union(set_b)))
else:
ratio = 0.0
return ratio >= threshold, ratio |
def convert_decimal_to_binary(number):
"""
Parameters
----------
number: int
Returns
-------
out: str
>>> convert_decimal_to_binary(10)
'1010'
"""
return bin(number)[2:] |
def filler(fill_len, line_len=80):
"""Get fill lines"""
if fill_len > 0:
num_lines, rem = divmod(fill_len, line_len + 1)
lines = []
if num_lines:
fill_line = "#" * line_len
lines.extend(fill_line for _ in range(num_lines))
if rem:
lines.append(... |
def comma(N):
"""
Format positive integer-like N for display with
commas between digit groupings: "xxx,yyy,zzz".
"""
digits = str(N)
assert(digits.isdigit())
result = ''
while digits:
digits, last3 = digits[:-3], digits[-3:]
result = (last3 + ',' + result) if result else ... |
def fix_note_noted(json):
"""Ensure the 'noted' flag is set if and only if a note is given"""
if 'note' in json and json['note']:
json['noted'] = True
else:
del json['note']
json['noted'] = False
return json |
def comp(sequence):
""" complements a sequence, preserving case. Function imported from GemSim"""
d={'A':'T','T':'A','C':'G','G':'C','a':'t','t':'a','c':'g','g':'c','N':'N','n':'n'}
cSeq=''
for s in sequence:
if s in d.keys():
cSeq+=d[s]
else:
cSeq+='N'
return cSeq |
def _isQuoted(string, substring, idx):
"""returns True if position i of string is in a quoted region"""
bfr = string[:idx]
aft = string[idx + len(substring):]
if (bfr.count('"') % 2 or aft.count('"') % 2 or
bfr.count("'") % 2 or aft.count("'") % 2):
return True
else:
retu... |
def strip_extension(input_string: str, max_splits: int) -> str:
"""Strip the extension from a string, returning the file name"""
output = input_string.rsplit(".", max_splits)[0]
return output |
def height_gaussian(initial_velocity, t):
"""A more straightforward way of calculating height"""
n = t + 1
final_velocity = initial_velocity - t
return n * (initial_velocity + final_velocity) / 2 |
def which_bin(elem, bins):
"""Return the index of first intervals that element is in
Args:
elem(float): a number.
bins: an array of intervals in the format of (lower, upper]
Returns:
int: an index of the first interval the element is in. -1 if not found.
"""
for idx, bound... |
def format_issue_key(issue_key_str: str):
"""
returns formatted issueKey according to <CAPTIAL_LETTERS>-<NUMBERS>
with capital letters, dash, numbers, no spaces
Args:
issue_key_str(str): issue key that caught by RE
Returns:
issue_key(str): formatted issue_key
"""
issue_ke... |
def calculate_similarity(a_fingerprint, another_fingerprint):
"""
Calculates the structural similarity score between two molecules.
Parameters
----------
a_fingerprint, another_fingerprint : list
Input molecular fingerprints of two molecules.
Returns
-------
float
The T... |
def as_list(value):
"""clever string spliting:
.. code-block:: python
>>> print(as_list('value'))
['value']
>>> print(as_list('v1 v2'))
['v1', 'v2']
>>> print(as_list(None))
[]
>>> print(as_list(['v1']))
['v1']
"""
if isinstance(value, (l... |
def sequence_to_codons(sequence):
"""
Given a sequence, split into a list of codons.
:param sequence: Sequence
:type sequence: str or unicode
:return: list of codons
:rtype: list(str or unicode)
"""
codons = [sequence[i:i+3] for i in range(0, len(sequence), 3)]
# Validate split was ... |
def error(v1, v2):
"""Returns the relative error with respect to the first value.
Positive error if program output is greater than AREMA table.
Negative error if program output is less than AREMA table.
"""
e = (v2 - v1)/v1
return e |
def is_blank(s: str) -> bool:
"""Checks if the given string is blank or not
Args:
s (str): string to check
Returns:
bool: self explanatory
"""
if not isinstance(s, str):
return False
return not (s and s.strip()) |
def reduce(combiner, seq):
"""Combines elements in seq using combiner.
>>> reduce(lambda x, y: x + y, [1, 2, 3, 4])
10
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
24
>>> reduce(lambda x, y: x * y, [4])
4
"""
result = seq[0]
for item in seq[1:]:
result = combiner(result,... |
def make_values(params, point):
"""Return a dictionary with the values replaced by the values in point,
where point is a list of the values corresponding to the sorted params."""
values = {}
for i, k in (enumerate)((sorted)(params)):
values[k] = point[i]
return values |
def getNumOrRowsForGrid(num_of_cols_for_rgb_grid, rgb_list):
"""
This is to get a number of rows using a predetermined number of columns.
This is to ensure that the images form a grid, so that multiple rgb images can be viewed at once.
Args:
num_of_cols_for_rgb_grid(integer): The number of co... |
def pad_batch(batch):
""" pad sequences in batch with 0s to obtain sequences of identical length """
seq_len = list(map(len, batch))
max_len = max(seq_len)
padded_batch = [seq + [0]*(max_len-len(seq)) for seq in batch]
return padded_batch, seq_len |
def normalize_wordtree(wtree):
"""Fold back every literal sequence (delimited with empty strings) into
parent sequence.
"""
def normalize(wtree):
result = []
for part in wtree[1:-1]:
if isinstance(part, list):
part = normalize(part)
if part[0]=... |
def application_error(e):
"""Return a custom 500 error."""
return 'Dang, something went wrong! Unexpected error: {}'.format(e), 500 |
def support(itemset, records):
"""
Calculates the itemset's support based on records.
Return the support.
Input:
itemset - set of items whose support will be calculated;
record - set of records containing items from itemset.
"""
support = 0 # itemset's support
for record in records:
items = iter(items... |
def _baseline_mapping(baseline):
"""
create a header mapping for one baseline
"""
return {
"id": baseline["id"],
"display_name": baseline["display_name"],
"updated": baseline["updated"],
} |
def _default_axis_units(n_dims):
"""Unit names for each axis.
Parameters
----------
n_dims : int
Number of spatial dimensions.
Returns
-------
tuple of str
Units of each axis.
Examples
--------
>>> from landlab.grid.base import _default_axis_units
>>> _defa... |
def slowness2speed(value):
"""invert function of speed2slowness"""
speed = (31 - value) / 30
return speed |
def convert(k: str) -> str:
"""Convert key of dictionary to valid BQ key.
:param k: Key
:return: The converted key
"""
if len(k.split(":")) > 1:
k = k.split(":")[1]
if k.startswith("@") or k.startswith("#"):
k = k[1:]
k = k.replace("-", "_")
return k |
def get_meta_value(meta, *keys, default=None):
"""
Return value from metadata.
Given keys can define a path in the document tree.
"""
try:
for key in keys:
if not meta:
raise KeyError(key)
meta = meta[key]
return meta
except KeyError:
... |
def sum_two_digits(x: int, y: int) -> int:
"""[summary]
Args:
x (int): [First Number]
y (int): [Seconed Number]
Returns:
int: [Return The Numbers Of Digits Of The Sum Value]
"""
result = x + y
return(len(str(result))) |
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
... |
def hull_of_intervals(intervals):
"""
Takes an interable of intervals and finds the hull of them. Will fail if they are not on the same chromosome
:param intervals: Iterable of ChromosomeIntervals
:return: List of new ChromosomeIntervals
"""
new_intervals = []
for interval in sorted(interval... |
def emptyNone(val):
"""Clean out None values.
val A Python object that may or may not have None values.
returns a Python object with all None values replaced by ''.
"""
for k in val.keys():
if type(val[k]) is dict:
emptyNone(val[k])
else:
if val[k] is None:
... |
def format_num(num):
"""
Convert a string with a number to a number by removing common mistakes
in Excel.
Converts ',' to '.'
Removes leading "'"
If resulting string can be converted to an int, it is returned as an int,
if not, it is returned as a float. If it can not be converted to a float... |
def route_error_404(error):
""" Handle 404 (HTTP Not Found) errors."""
return 'Not found', 404 |
def scrapeints(string):
"""Extract a series of integers from a string. Slow but robust.
readints('[124, 56|abcdsfad4589.2]')
will return:
[124, 56, 4589, 2]
"""
# 2012-08-28 16:19 IJMC: Created
numbers = []
nchar = len(string)
thisnumber = ''
for n, char in enumerate(string)... |
def nullstrip(s):
"""Return a string truncated at the first null character"""
try:
# Remove any junk data and before decoding
# to avoid Unicode Decode errors
s = s[:s.index(b'\x00')]
except ValueError:
pass
try:
# Decode bytes object using UTF-8 encoding scheme
... |
def get_output_dir(direct="default"):
"""
Gets the output directory
"""
result = ""
if(direct == "default"):
result = ""
else:
result = direct
return result |
def get_bond_type_counts(bond_types):
""" Returns a count on the number of bonds of each type. """
count = {}
for bt in bond_types:
if bt in count.keys():
count[bt] += 1
else:
count[bt] = 1
return count |
def constructProcessOutput(outputText, errorText, executionTime=None):
""" A Simple convenience function to construct a ProcessOutput object to be returned to the dispatcher. """
processOutput = {
'outputText': outputText,
'outputErrorText': errorText,
'executionTime': executionTime
... |
def munge(str, **attribs):
"""Create an unparsable name.
"""
return '<*%s*>' % str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.