content stringlengths 42 6.51k |
|---|
def parse_uint(data_obj, factor=1):
"""convert bytes (as unsigned integer) and factor to float"""
decimal_places = -int(f'{factor:e}'.split('e')[-1])
return round(int.from_bytes(data_obj, "little", signed=False) * factor, decimal_places) |
def noamwd_decay(step, warmup_steps,
model_size, rate, decay_steps, start_step=0):
"""Learning rate schedule optimized for huge batches
"""
return (
model_size ** (-0.5) *
min(step ** (-0.5), step * warmup_steps**(-1.5)) *
rate ** (max(step - start_step + decay_steps... |
def remove_suffix(text, suffix):
# type: (str, str) -> str
"""Remove suffix from text if any"""
if text.endswith(suffix):
return text[:len(text)-len(suffix)]
return text |
def process_vector_args(args):
"""
A helper function to process vector arguments so callables can take
vectors or individual components. Essentially unravels the arguments.
"""
new_args = []
for arg in args:
if hasattr(arg, 'shape') and len(arg.shape) > 0:
shape = arg.shape
... |
def is_palindrome(string):
"""Check if string is a Palindrome.
Args:
string (str): String.
Returns:
bool: Return True if string is a palindrome and False if not.
"""
string = string.strip()
if string == string[::-1]:
return True
else:
return False |
def split(container, count):
"""
split the jobs for parallel run
"""
return [container[_i::count] for _i in range(count)] |
def clamp(value, value_max=1, value_min=0):
"""Clamp between values."""
return max(min(value, value_max), value_min) |
def uniqify(s):
"""Remove duplicates and sort the result list."""
return sorted(set(s)) |
def func_x_a_p_kwargs(x, a=2, *, p="p", **kwargs):
"""func.
Parameters
----------
x: float
a: int
p: str
kwargs: dict
Returns
-------
x: float
a: int
p: str
kwargs: dict
"""
return x, None, a, None, None, p, None, kwargs |
def do_boxes_intersect(box, *other_boxes):
"""Whether the first box intersects with any of the others.
:param tuple box: box described by coordinates of upper left corner
and width, height by ((x,y),(w,h)) with x, y, w, h integers
:param list other_boxes: list of other boxes of the form ((x,y), (wi... |
def node_list_to_node_name_list(node_list):
"""Converts a node list into a list of the corresponding node names."""
node_name_list = []
for n in node_list:
node_name_list.append(n.get_name())
return node_name_list |
def f1(gt_s, gt_e, pr_s, pr_e):
"""
Evaluate F1 score of a predicted span over a ground truth span.
Args:
gt_s: index of the ground truth start position
gt_e: index of the ground truth end position
pr_s: index of the predicted start position
pr_e: index of the predicted end p... |
def decrypt_key(e1, modulus):
"""Works out the decryption key
Inputs - e and the modulus both integers
Outputs - The decryption key"""
d = 1 #Setting d to 1
finished = False #To check if we found a value for d
while finished != True: #We check to see if we ... |
def _fullname(o):
"""Return the fully-qualified name of a function."""
return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__ |
def qubits(circ):
"""
Args:
circ(list(list(tuple))): Circuit
Returns:
list: The list of qubits appearing in the circuit.
"""
qs = []
for c in circ:
for g in c:
qs += list(g)
qs = list(set(qs))
return qs |
def strip_quotes(value):
"""strip both single or double quotes"""
value = value.strip()
if "\"" in value:
return value.strip("\"")
elif "\'" in value:
return value.strip("\'")
else:
return value |
def GetAllCombinations(choices, noDups=1, which=0):
""" Does the combinatorial explosion of the possible combinations
of the elements of _choices_.
**Arguments**
- choices: sequence of sequences with the elements to be enumerated
- noDups: (optional) if this is nonzero, results with duplicates,
... |
def generate_payload(data_file):
"""
Generate a list of payloads to import into deep lynx
Args
data_file (string): location of file to read
Return
payload (dictionary): a dictionary of payloads to import into deep lynx e.g. {metatype: list(payload)}
"""
payload = dict()
... |
def humanReadable(n):
"""Given an int, e.g. 52071886 returns a human readable string 5.2M
ref: http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
#DROPPING the human readable part and just moving to millions
# for unit in ['','K','M','B','T','P... |
def definition_area(t, x):
"""
for the initial value x0 = 1 this ODE only has a solution for x in (-sqrt(2),sqrt(2)). Therefore the ode is only
defined in a certain area.
:param t: time
:param x: x value
:return: slope dx/dt
"""
dx = t * x ** 2
return dx |
def split_list(doc_list, n_groups):
"""
Args:
doc_list (list): is a list of documents to be split up
n_groups (int): is the number of groups to split the doc_list into
Returns:
split_lists (list): a list of n_groups which are approximately equal
in length, as a necessary step... |
def url_has(url, wordlist):
"""True iff wordlist intersect url is not empty."""
for word in wordlist:
if word in url:
return True
return False |
def calc_dh(eta):
"""Calculate the first derivative of the interpolation function
Args:
eta: the phase field
Returns:
the value of dh
"""
return 30 * eta ** 2 * (eta - 1) ** 2 |
def parse_secs_to_str(duration: int = 0) -> str:
"""
Do the reverse operation of :py:func:`parse_str_to_secs`.
Parse a number of seconds to a human-readable string.
The string has the form XdXhXmXs. 0 units are removed.
:param int duration: The duration, in seconds.
:return: A formatted string... |
def step_anneal(base_lr, global_step,
anneal_rate=0.98,
anneal_interval=30000):
"""
Annealing learning rate by steps
:param base_lr: base learning rate
:type base_lr: float
:param global_step: global training steps
:type global_step: int
:param anneal_rate: r... |
def shape_select(dict_sizes, max_size):
"""takes a dict in parameter, returns list of shapes\
of blocker of at most max size"""
shapes = []
for size in dict_sizes:
if size is not None and max_size is not None and size <= max_size:
for item in dict_sizes[size]:
shapes.appe... |
def gff3plsorting(gff_file, outgff_file):
""" """
inputs = [gff_file]
outputs = [outgff_file]
options = {
'cores': 1,
'memory': '4g',
'account': 'NChain',
'walltime': '01:00:00'
}
spec = '''
/home/marnit/bin/gff3sort.pl --chr_order natural {infile} > {outfile... |
def get_scores(data: dict) -> list:
"""Get a list of all scores."""
return data.get('scores', []) |
def set_attribute(t, key: str, data):
"""
Set an attribute on a callable.
Mainly used with decorators to allow the decorators to store data onto the callable
:param t: the callable to store data onto
:param key: the key of the data, the attributes name.
:param data: the data to set, the attrib... |
def find_interval(x,
partition,
endpoints=True):
""" find_interval -> i
If endpoints is True, "i" will be the index for which applies
partition[i] < x < partition[i+1], if such an index exists.
-1 otherwise
If endpoints is False, "i" wil... |
def _image_mode(backup_mode):
"""True if backup is image type."""
return backup_mode == 'image' |
def isblank(s):
"""Is this whitespace or an empty string?"""
if isinstance(s, str):
if not s:
return True
else:
return s.isspace()
else:
return False |
def strip_comments(content):
"""Manual striping of comments from file content.
Many localized content pages contain original English content in comments.
These comments have to be stripped out before analyzing the links.
Doing this using regular expression is difficult. Even the grep tool is
not su... |
def burn_in_scaling(cur_batch, burn_in, power):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Returns the darknet burn in scaling
- Designed to be used with torch.optim.LambdaLR
- Scaling formula is (cur_batch / burn_in)^power
----------
"""
return pow(cur_batch / bu... |
def login(i):
"""
Input: {
(sudo) - if 'yes', add sudo
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
import os
... |
def _parse_userinfo(userinfo):
"""Try to split the URL's userinfo (the part between :// and @) into fields
separated by :. If anything looks wrong, remind user to percent-encode values."""
if hasattr(userinfo, 'split'):
parts = userinfo.split(u':', 1)
if len(parts) == 2:
return ... |
def is_valid_interval(x):
"""
Returns true iff x is a well-shaped concrete time interval (i.e. has valid beginning and end).
"""
try:
return hasattr(x, "hasBeginning") and len(x.hasBeginning) > 0 and \
len(x.hasBeginning[0].inTimePosition) > 0 and \
len(x.hasBeginni... |
def find_duo_maps(dict_A, dict_B):
"""This function finds the maps that are to be combined. Expected inputs are:
dict_A and dict_B: dictionaries"""
maps_A = list(dict_A.keys())
maps_B = list(dict_B.keys())
maps_to_combine = list(set(maps_A) & set(maps_B))
maps_to_combine.remove('meta')
print... |
def deindented_source(src):
"""De-indent source if all lines indented.
This is necessary before parsing with ast.parse to avoid "unexpected
indent" syntax errors if the function is not module-scope in its
original implementation (e.g., staticmethods encapsulated in classes).
Parameters
-------... |
def is_suffix_of(suffix, trace) -> bool:
"""
Args:
suffix: target suffix
trace: trace in question
Returns:
True if suffix is the suffix of trace.
"""
if len(trace) < len(suffix):
return False
else:
return trace[-len(suffix):] == suffix |
def is_palindrome(word):
""" :returns: True if <word> is a palindrome
:param str word: a string
"""
return word == word[::-1] |
def day2k_to_date(day2k):
"""Convert integer day number since 2000-01-01 to date as (year, month, day)
tuple.
"""
# ref: https://en.wikipedia.org/wiki/Julian_day#Julian_or_Gregorian_calendar_from_Julian_day_number
# Gregorian date formula applied since 1582-10-15
# Julian date formula applied un... |
def _func_and(current, checks):
"""Implementation of And."""
return all(check(current) for check in checks) |
def evaluate_f1(tp: int, fp: int, fn: int) -> float:
"""F1-score.
*F1-score* $=\dfrac{2TP}{2TP + FP + FN}$
Args:
tp: True Positives
fp: False Positives
fn: False Negatives
"""
try:
return 2 * tp / (2 * tp + fp + fn)
except ZeroDivisionError:
return 0.0 |
def match_to_schema(_dict, requested_key):
"""
Match the schema supplied with the response to return the
data we requested.
:param _dict:
:param requested_key:
:return:
"""
if _dict.get(requested_key) is not None:
return _dict[requested_key]
for valid_key in _dict:
i... |
def get_metric(dataset_name):
"""tbd"""
if dataset_name in ['esol', 'freesolv', 'lipophilicity']:
return 'rmse'
elif dataset_name in ['qm7', 'qm8', 'qm9', 'qm9_gdb']:
return 'mae'
else:
raise ValueError(dataset_name) |
def hermiteInterpolate(v0, v1, v2, v3, alpha, tension, bias):
"""
Hermite interpolator. Allows better control of the bends in the spline by providing two
parameters to adjust them:
* tension: 1 for high tension, 0 for normal tension and -1 for low tension.
* bias: 1 for bias towards the next se... |
def is_ontology_metadata(convention, metadatum):
"""Check if metadata is ontology from metadata convention
"""
try:
return bool(convention["properties"][metadatum]["ontology"])
except KeyError:
return False |
def build_query_for_indicators(indicators):
"""Builds an Elasticsearch query for Yeti indicator patterns.
Prepends and appends .* to the regex to be able to search within a field.
Returns:
The resulting ES query string.
"""
query = []
for domain in indicators:
query.append('domai... |
def unitarity_fn(x, baseline, amplitude, unitarity):
"""
Fitting function for unitarity randomized benchmarking, equation (8) of [ECN]
:param numpy.ndarray x: Independent variable
:param float baseline: Offset value
:param float amplitude: Amplitude of exponential decay
:param float decay: Deca... |
def reverse_array(orig):
"""
Returns a list in reversed order
Mutable?
"""
new = []
while len(orig) > 1:
new.insert(0, orig[0])
orig.pop(0)
return new |
def is_part_of_group(settings_file, campaign_id):
"""Checks whether a campaign is part of a group.
Args:
settings_file (dict): Settings file for the project
campaign_id (int): Id of campaign which is to be checked
Returns:
bool: True if campaign part of any group else False
"""... |
def CreateNameToSymbolInfo(symbol_infos):
"""Create a dict {name: symbol_info, ...}.
Args:
symbol_infos: iterable of SymbolInfo instances
Returns:
a dict {name: symbol_info, ...}
"""
return {symbol_info.name: symbol_info for symbol_info in symbol_infos} |
def find_largest_digit_helper(n, largest_digit):
"""
This function helps find the largest digit in the number.
:param n: the number used to find the largest digit
:param largest_digit: stores the largest digit in the number, the default value is 0.
:return: the largest digit in the number
"""
if n == 0:
return... |
def filter_zones(item, correct_prefixes, wrong_prefixes, zone) -> bool:
"""Return true for item in zone."""
name, _ = item
for pre in wrong_prefixes:
if name.startswith(pre):
return False
for pre in correct_prefixes:
if name.startswith(pre):
return True
return... |
def cloudfront_restriction_type(restriction_type):
"""
Property: GeoRestriction.RestrictionType
"""
valid_values = ["none", "blacklist", "whitelist"]
if restriction_type not in valid_values:
raise ValueError(
'RestrictionType must be one of: "%s"' % (", ".join(valid_values))
... |
def check_percentages(percentages):
""" Check percentages for validity
percentages is an array where each array element is either a
percentage value or None. The percentage values must add up to
no more than 100.0. Negative values count as positive.
If there are no None-v... |
def get_cache_key(key):
"""
Generates a prefixed cache-key for ultimatethumb.
"""
return 'ultimatethumb:{0}'.format(key) |
def formActions(
primaryButton="",
button2=False,
button3=False,
button4=False,
button5=False,
inlineHelpText=False,
blockHelpText=False):
"""
*Generate a formActions - TBS style*
**Key Arguments:**
- ``primaryButton`` -- the primary button
... |
def test_inp(test_obj, test_if, name_inp, value=False):
"""
Test a value if it returns false raise an exception
:param: test_obj
Object to be tested.
:param:test_if
The input that is tested to be equal as. (in int, str, double etc)
:param: value
Bool, if True the exception also shows tes... |
def checker(wordlist, filename):
""" Return if the file matches all words in the word list """
content = open(filename).read().lower().split()
return all(word in content for word in wordlist) |
def getTags(src):
"""
It is a function to get sentence tags with {'B', 'M', 'E', 'S'}.
:param src:
:return: tags list
"""
tags = []
if len(src) == 1:
tags = ['S']
elif len(src) == 2:
tags = ['B', 'E']
else:
m_num = len(src) - 2
tags.append('B')
... |
def _collapse(values):
"""Collapse multiple values to a colon-separated list of values"""
if isinstance(values, str):
return values
if values is None:
return "all"
if isinstance(values, list):
return ";".join([_collapse(v) for v in values])
return str(values) |
def unknown_els(dim):
"""
The elements of the "unknown" basis. Just returns an empty list.
Parameters
----------
dim : int
The dimension of the basis (doesn't really matter).
Returns
-------
list
"""
assert(dim == 0), "Unknown basis must have dimension 0!"
return [... |
def pgcd(a, b):
"""
[description]
calculate the greatest common divisor of a and b
:param a: it is an Int
:param b: it is an Int
:return: a -> it is an Int
"""
while b != 0:
a, b = b, a % b
return a |
def sumSquares(upperLimit):
""" Returns the sum of squares from [1, upperLimit]
--param
upperLimit : integer
--return
sum of squares : integer
"""
squares = [x**2 for x in range(1,upperLimit+1)]
return sum(squares) |
def count_words(words):
"""You are given a string words.
Count the number of unique words that starts with lower letter.
Count the number of unique words that starts with Upper letter.
And return a list contains the two counts and the length of the string words.
If two words are same, count them as one.
If two w... |
def __format_float(value):
"""Format float in scientific notation, 6 decimal places.
:param value:
:return:
"""
return '{:.6e}'.format(float(value)) |
def _le_to_uint(val):
"""Returns the unsigned integer represented by the given byte array in little-endian format.
Args:
val: Byte array in little-endian format that represents an unsigned integer.
Returns:
The unsigned integer represented by the byte array ``val``.
"""
return int.from... |
def perfect_score(student_info):
"""
:param student_info: list of [<student name>, <score>] lists
:return: first `[<student name>, 100]` or `[]` if no student score of 100 is found.
"""
# for name, score in student_info:
# if score == 100:
for student in student_info:
# print("bo... |
def subexpr_before_unbalanced(expr, ltok, rtok):
"""Obtains the expression prior to last unbalanced left token."""
subexpr, _, post = expr.rpartition(ltok)
nrtoks_in_post = post.count(rtok)
while nrtoks_in_post != 0:
for i in range(nrtoks_in_post):
subexpr, _, post = subexpr.rpartiti... |
def get_slu_type(cfg):
"""
Reads the SLU type from the configuration.
"""
return cfg['SLU']['type'] |
def elvis_operator(operator, receiver, expr):
""":yaql:operator ?.
Evaluates expr on receiver if receiver isn't null and returns the result.
If receiver is null returns null.
:signature: receiver?.expr
:arg receiver: object to evaluate expression
:argType receiver: any
:arg expr: expressio... |
def roundup_16(x):
"""Rounds up the given value to the next multiple of 16."""
remainder = x % 16
if remainder != 0:
x += 16 - remainder
return x |
def relabel_prometheus(job_config):
"""Get some prometheus configuration labels."""
relabel = {
'path': '__metrics_path__',
'scheme': '__scheme__',
}
labels = {
relabel[key]: value
for key, value in job_config.items()
if key in relabel.keys()
}
# parse _... |
def find_header(blockquote):
"""Find attributes in a blockquote if they are defined on a
header that is the first thing in the block quote.
Returns the attributes, a list [id, classes, kvs]
where id = str, classes = list, kvs = list of key, value pairs
"""
if blockquote[0]['t'] == 'Header':
... |
def reader(start_sinogram=0, end_sinogram=0, step_sinogram=1, start_projection=0, end_projection=0, step_projection=1,
sinograms_per_chunk=0, projections_per_chunk=0):
"""
Function to expose input tomography array parameters in function pipeline GUI
Parameters
----------
start_sinogram ... |
def split_off_attrib(xpath):
"""
Splits off attribute of the given xpath (part after @)
:param xpath: str of the xpath to split up
"""
split_xpath = xpath.split('/@')
assert len(split_xpath) == 2, f"Splitting off attribute failed for: '{split_xpath}'"
return tuple(split_xpath) |
def _create_file_name_from_complex_index(complex_):
"""Create a file name from a complex index."""
choice = "".join([str(int(x)) for x in complex_[1]])
if len(complex_) == 3:
file_name = f"{complex_[0]}_{choice}_{complex_[2]}.parquet"
elif len(complex_) == 2:
file_name = f"{complex_[0]}_... |
def parseInt(value, ret=0):
"""
Parses a value as int.
This function works similar to its JavaScript-pendant, and performs
checks to parse most of a string value as integer.
:param value: The value that should be parsed as integer.
:param ret: The default return value if no integer could be pars... |
def fibonacci_smaller_than(limit):
"""Return Fibonacci series up to limit"""
result = []
previous_number, current_number = 0, 1
while previous_number < limit:
result.append(previous_number)
previous_number, current_number = current_number, previous_number + current_number
return resu... |
def math_map_list(values, toMin=0, toMax=1):
"""
Maps the values of a list from a minimum value to a maximum value.
----------
values : list to be mapped
----------
toMin : minimum value of the list's target range (default = 0)
toMax : maximum value of the list's target range (default = 1)
... |
def compare_listener(current_listener, new_listener):
"""
Compare two listeners.
:param current_listener:
:param new_listener:
:return:
"""
modified_listener = {}
# Port
if current_listener['Port'] != new_listener['Port']:
modified_listener['Port'] = new_listener['Port']
... |
def get_cluster_from_pattern(pattern, clusters):
"""
Helper function to return the cluster a pattern is in
Args:
pattern: A tuple of three values
clusters: A list of lists of patterns
Returns:
The list containing the pattern
"""
for cluster in clusters:
if pattern... |
def timestampToSubscribers(response):
"""
Create a dictionary that links a timestamp to subscribers. Makes it easier
to batch up messages to send to subscribers.
{123456789.123: [subA, ..., subN]}
:return:
"""
timestamp_to_subscribers = {} # matches subscribers to their current place in kin... |
def memdiff_search(bytes1, bytes2):
"""
Use binary searching to find the offset of the first difference
between two strings.
:param bytes1: The original sequence of bytes
:param bytes2: A sequence of bytes to compare with bytes1
:type bytes1: str
:type bytes2: str
:rtype: int offset of... |
def parse_block(block, metric=[], labels={}):
"""Parse_block.
Parse a 'block' of results (a level of a for example)
and transform into a suitable list with labels and all
"""
result = []
# Give a dict of lists of labels which will be concatenated into a single
# label per item. These co... |
def is_valid_address(address):
"""check ip-address is valid"""
if address.find('.') != -1:
addr_list = address.split('.')
if len(addr_list) != 4:
return False
for each_num in addr_list:
if not each_num.isdigit():
return False
if int(ea... |
def matrix_sum(matrix):
"""
Matrix_sum: has one required parameter of a matrix (an array of arrays). This function will then
sum the total of each row or each array within the matrix and return the results per row as a
single array.
"""
output = []
for i in range(len(matrix)):
counte... |
def cipher(word):
"""
:param word: the word to decipher to "ave"
:return: the number used for encryption
"""
word = word.lower()
return ord(word[0]) % 97 |
def populate_albums_table(db_session, artist_id, l):
"""Save the list of albums in the albums table."""
if not l: # list is empty
return False
#print list
c = db_session.cursor()
c.execute("""DELETE FROM albums WHERE artist_id = ?""", [artist_id])
for album_list in l:
c.execute("... |
def leap_year(year, calendar='standard'):
"""Determine if year is a leap year"""
leap = False
if ((calendar in ['standard', 'gregorian',
'proleptic_gregorian', 'julian']) and
(year % 4 == 0)):
leap = True
if ((calendar == 'proleptic_gregorian') and
(year % 100 == ... |
def _block_to_bed_line(block):
""" tchrom, trun, trun + size, tstrand, qchrom, qrun, qrun + size, qstrand, chain_id + '.' + str(bc), chain_score
:param block:
:return:
"""
return '{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(*block) |
def split_by_cleaning(value, split_by_char=','):
"""
The method returns elements from a string value by deleting extra spaces
:param value: A string value
:param split_by_char: A character in the value to split
:return: list of split elements
"""
elements = value.strip().strip(split_by_char)... |
def parse_by_suffix(input_string, suffix, start_char=" "):
"""searches through input_string until it finds the suffix. Walks backwards
from the suffix and returns everything in the string between suffix and
the end_char"""
end = input_string.find(suffix)
start = end
while input_string[start] !... |
def diR_calc(i,vt,v,winv,Rf,Lf,wbase):
"""Calcluate derivative of inverter branch current - real component - iR"""
diR = (1/Lf)*(-Rf*i.real - v.real + vt.real) + (winv/wbase)*i.imag
return diR |
def query_for_users_annotations(userid):
"""Return an Elasticsearch query for all the given user's annotations."""
return {
"query": {
"filtered": {
"filter": {
"bool": {
"must": [{"term": {"user": userid.lower()}}]
... |
def convertHLAToIEDB(h):
"""Takes format A*1234 or A_1234 and returns A*12:34"""
return 'HLA-' + h[:4].replace('_', '*') + ':' + h[4:] |
def add_suffix(event, fields, suffix, separator='_'):
""" Adds a suffix to a field or list of fields
:param event: A dict with the entire event
:param field_or_field_list: A single field or list of fields for which to add a suffix
:param suffix: The suffix to add to the fields
:param separator: The... |
def _get_severity_filter_value(severity_arg):
"""Converts single str to upper case. If given list of strs, converts all to upper case."""
if severity_arg:
return (
[severity_arg.upper()]
if isinstance(severity_arg, str)
else list(map(lambda x: x.upper(), severity_arg)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.