content stringlengths 42 6.51k |
|---|
def add_params(default_params, extra_params):
""" Add params from extra_params to default_params
Parameters
----------
default_params : dict
Original parameters
extra_params : dict
Extra parameters to add
Returns
------
params : dict
Merged parameters, where ext... |
def get_iou(bboxes1, bboxes2):
"""
Adapted from https://gist.github.com/zacharybell/8d9b1b25749fe6494511f843361bb167
Calculates the intersection-over-union of two bounding boxes.
Args:
bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
bbox2 (numpy.array, list of f... |
def is_subdict(small, big):
"""
Check if one dict is a subset of another with matching keys and values.
Used for 'flat' dictionary comparisons such as in comparing interface
settings. This should work on both python 2 and 3.
See: https://docs.python.org/2/reference/expressions.html#value-compar... |
def average(num_list):
"""Return the average for a list of numbers
>>> average([1,2])
1.5
"""
return sum(num_list) / len(num_list) |
def mib(num):
"""Return number of bytes for num MiB"""
return int(num * 1024 * 1024) |
def c_string_arguments(encoding='UTF-8', *strings):
""" Convenience function intended to be passed to in_format which allows
easy arguments which are lists of null-terminated strings.
"""
payload = b""
# Add each string, followed by a null character.
for string in strings:
payload ... |
def is_unicode_list(value):
"""Checks if a value's type is a list of Unicode strings."""
if value and isinstance(value, list):
return isinstance(value[0], str)
return False |
def sdnv_decode(buffer):
"""Decodes a byte string (or any iterable over bytes) assumed to be a an
SDNV and returns the non-negative integer representing the numeric value
Args:
buffer (bytes): Encoded SDNV
Returns:
int: Decoded non-negative integer
Raises:
ValueError: If the... |
def get_wind_direction(degree):
"""Convert wind degree to direction."""
DEGREES = [-11.25, 11.25, 33.75, 56.25,
78.75, 101.25, 123.75, 146.25,
168.75, 191.25, 213.75, 236.25,
258.75, 281.25, 303.75, 326.25, 348.75]
DIRECTIONS = ['N', 'NNE', 'NE', 'ENE',
... |
def create_names(instances, Ns, str_format):
"""
Create a list of names for spectra loaded from task instances.
:param instances:
A list of task instances where spectra were loaded. This should
be length `N` long.
:param Ns:
A list containing the number of spectra loaded fr... |
def startsWith(str, prefix):
"""Return true iff _str_ starts with _prefix_.
>>> startsWith('unclear', 'un')
1
"""
return str[:len(prefix)] == prefix |
def pad_right_with(l: list, sz: int, pd) -> list:
"""
Return a new `sz`-sized list obtained by right padding `l` with `pd`.
If the starting list is of size `sz` or greater, no change is applyed.
@param l: The list to pad. No changes are made to this list.
@param sz: The final size of the list if it needs to b... |
def std2scatteringRange(std):
"""Convert a standard deviation into scattering range (`TS` or `TN` in DIN 50100:2016-12).
Parameters
----------
std : float
standard deviation
Returns
-------
T : float
inverted scattering range corresponding to `std` assuming a normal distrib... |
def kind(n, ranks):
"""Return the first rank that this hand has exactly n-of-a-kind of.
Return None if there is no n-of-a-kind in the hand."""
for r in ranks:
if ranks.count(r) == n:
return r
return None |
def filter_files(input, endings = [".js"]):
"""Filters a list of files for specific endings
Args:
input: The depset or list of files
endings: The list of endings that should be filtered for
Returns:
Returns the filtered list of files
"""
# Convert input into list regardles... |
def InstanceGroupName(deployment, zone):
"""Returns the name of the instance group.
A consistent name is required to define references and dependencies.
Assumes that only one instance group will be used for the entire deployment.
Args:
deployment: the name of this deployment.
zone: the zone for this p... |
def is_balanced(node):
"""Check if a BST is balanced; returns (True/False, height of tree)."""
# First we ensure the left subtree is balanced; then ensure the right subtree
# is balanced too; and ensure the diff betw heights of left & right subtree <=1
if node is None:
return True, 0
balanc... |
def convert_string_AE2BE(string, AE_to_BE):
"""convert a text from American English to British English
Parameters
----------
string: str
text to convert
Returns
-------
str
new text in British English
"""
string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() e... |
def user_id(uid):
"""Google user unique id to feedly ``:user_id`` format
:param uid: Google unique account UUID
:type uid: :class:`basestring`
:returns:
:rtype: :class:`basestring`
>>> user_id('00000000-0000-0000-0000-000000000000')
'user/00000000-0000-0000-0000-000000000000'
... |
def _parse_nonbon_line( line ):
"""Parse an AMBER frcmod nonbon line and return relevant parameters in a dictionary. AMBER uses rmin_half and epsilon in angstroms and kilocalories per mole."""
tmp = line.split()
params = {}
params['smirks'] = tmp[0]
params['rmin_half'] = tmp[1]
params['epsilon']... |
def is_palindrome_recursive(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.
>>> all(is_palindrome_recursive(key) is value for key, value in test_data.items())
True
"""
if len(s) <= 1:
return True
if s[0] == s[len(s) - 1]:
return is_palindrome_re... |
def get_max_coordination_of_elem(single_elem_environments):
""" For a given set of elemental environments, find the greatest
number of each element in a site.
Input:
| single_elem_environments: list(dict), list of voronoi substructures,
Returns:
| max_num_elem: dict(int), greatest nu... |
def input_block(config, section):
"""Return the input block as a string."""
block = ''
if section not in config:
return ''
for key in config[section]:
value = config[section][key].strip()
if value:
block += '{} {}\n'.format(key, value)
else:
blo... |
def round_to_mb(bts):
"""Returns Mb from b rounded to .xx"""
return round((int(bts) / 1024 / 1024), 2) |
def skeys(some_dict):
"""
Returns sorted keys
Useful for converting dicts to lists consistently
"""
return sorted([*some_dict]) |
def wf_sum(window, *args, **kwargs):
"""
Returns sum of values within window
:param window:
:return:
"""
return float(sum(w[1] for w in window)) |
def hexstr(barray):
"""Print a string of hex digits"""
return ":".join(f'{x:02x}' for x in barray) |
def as_hex(value, bit_width):
""" Creates a hexadecimal string of a given bit width from the value provided """
mask = (1 << bit_width) - 1
return "%x" % (value & mask) |
def maxHeightTry2(d1, d2, d3):
"""
A method that calculates largest possible tower height of given boxes (optimized, but bad approach 2/2).
Problem description: https://practice.geeksforgeeks.org/problems/box-stacking/1
time complexity: O(n*max(max_d1, max_d2, max_d3)^2)
space complexity: O(... |
def derive_end_activities_from_log(log, activity_key):
"""
Derive end activities from log
Parameters
-----------
log
Log object
activity_key
Activity key
Returns
-----------
e
End activities
"""
e = set()
for t in log:
if len(t) > 0:
... |
def Find_StemDensityGridPT(StemDensityTPHa, Dx, nxy, Dy):
"""
function [StemDensityGridPT]=Find_StemDensityGridPT(StemDensityTPHa,Dx,nxy,Dy)
Calculate a rounded coarse mesh resolution (in integer mesh-point number)
in which to place stems. 1 stem will be placed at each coarse mesh grid-cell
Copyrig... |
def calculate_score(s1, s2, l1, l2, startpoint):
"""calculate alignment score"""
matched = "" # to hold string displaying alignements
score = 0
for i in range(l2):
# import ipdb; ipdb.set_trace() ## debug breakpoint added
if (i + startpoint) < l1:
if s1[i + startpoint] == s2[i]: # ... |
def remove_copies(data: list) -> list:
"""Creates a unique list of arrays given a list of arrays containing
identical arrays.
Param:
data (list[list[float or int]]): a list of lists of comparable items
Return
arrays: the unique list with no repeated arrays
"""
arrays = []
f... |
def llen(x) -> int:
"""
Calculate the length of input if list, else give 1
:param x: list or non-container type
:return: length or 1
"""
return len(x) if type(x) is list else 1 |
def contains(collection, target, from_index=0):
"""Checks if a given value is present in a collection. If `from_index` is
negative, it is used as the offset from the end of the collection.
Args:
collection (list|dict): Collection to iterate over.
target (mixed): Target value to compare to.
... |
def get_ndim_first(x, ndim):
"""Return the first element from the ndim-nested list x.
"""
return (x if ndim == 0 else
get_ndim_first(x[0], ndim - 1)) |
def short(text):
""":short: Changeset hash. Returns the short form of a changeset hash,
i.e. a 12 hexadecimal digit string.
"""
return text[:12] |
def url_string(s: str) -> bool:
"""
Verify the given string (s) is a URL.
:param s: string
:return: bool
"""
# ToDo: Verify url pattern
return type(s) is str |
def sum_all(grid_values):
"""
Calculates the sum of all grid values.
Results in scores from
:param grid_values: values of grid
:return: metrics score
"""
score = sum(grid_values)
return score |
def get_correct(gold, guess):
"""
Args:
gold (Iterable[T]):
guess (Iterable[T]):
Returns:
Set[T]
"""
return set(gold) & set(guess) |
def rr_duplicates(input_list):
"""
Input:
list by list() type
Output:
list without duplicates by list() type
"""
return list(set(input_list)) |
def toJadenCase(string):
""" to_jaden_case == PEP8 (forced mixedCase by CodeWars) """
return ' '.join(a.capitalize() for a in string.split()) |
def msgs_human(messages, header):
"""
Return messages, with optional header row.
One pipe-delimited message per line in format:
date | from | to | text
Width of 'from' and 'to' columns is determined by widest column value
in messages, so columns align.
"""
output = ""
... |
def find_url_piecewise(mapping, symbol):
"""
Match the requested symbol reverse piecewise (split on ``::``) against the tag names to ensure they match exactly (modulo ambiguity)
So, if in the mapping there is ``PolyVox::Volume::FloatVolume`` and ``PolyVox::Volume`` they would be split into:
.. code-block:: python... |
def get_spans_in_offsets(spans, start, end):
"""Return the list of spans (nlplingo.text.text_span.Span) that are within (start, end) offsets
:type spans: list[nlplingo.text.text_span.Span]
Returns:
list[text.text_span.Span]
"""
ret = []
for span in spans:
if start <= span.start_c... |
def to_ordinal(number):
"""Return the "ordinal" representation of a number"""
assert isinstance(number, int)
sr = str(number) # string representation
ld = sr[-1] # last digit
try:
# Second to last digit
stld = sr[-2]
except IndexError:
stld = None
if stld != '1'... |
def format_date(date):
"""Formats the given date (`datetime` object).
:returns: `date` of the form ``'YYYY-MM-DD HH:MM:SS'``.
If `date` is ``None``, it returns ``'-'``.
"""
return date.strftime('%Y-%m-%d %H:%M:%S') if date is not None else '-' |
def judge_date_type(date: str) -> str:
"""judge_date_type.
Using "date"(str) length, judge date type.
Args:
date (str): date
Returns:
str:
"""
if len(date) == 8:
date_type = "day"
elif len(date) == 6:
date_type = "month"
elif len(date) == 4:
date_... |
def get_task_id_service_name(service_name):
"""Converts the provided service name to a sanitized name as used in task ids.
For example: /test/integration/foo => test.integration.foo"""
return service_name.lstrip("/").replace("/", ".") |
def _getind(x,x0):
"""Find the index of a point on a grid.
Find the index k of x0 in a real array x, such that
x[k] <= x0 < x[k+1].
To enable usage by the interpolation routine, the edge cases are
x0 <= x[0]: k = 0
x0 >= x[-1]: k = len(x) - 2
so that expressions such as (x[k... |
def compile_hierarchy_req_str_list(geo_list: dict, str_list: list) -> list:
"""Recursively go through geo config to get list ids and combine with their str.
An example of hierarchial required geo ids would be:
county subdivision:
{
'<state id>': {
'<county id>': {... |
def arbi_poly(x, *params):
"""
Parameters
----------
x : numpy.ndarray
takes the values of x where the value of polynomial is needed
*params: tuple, numpy.ndarray
values of coefficients of the polynomial
lowest degree first
----------
returns
----------
numpy.... |
def bitxor(a,b):
""" bitwise XOR: 110 ^ 101 eq 011 """
return int(a) ^ int(b) |
def check_peptide(peptide:str, AAs:set)->bool:
"""
Check if the peptide contains non-AA letters.
Args:
peptide (str): peptide sequence.
AAs (set): the set of legal amino acids. See alphapept.constants.AAs
Returns:
bool: True if all letters in the peptide is the subset of AAs, oth... |
def _tags_to_dict(tags):
"""
convert tags from list if dicts to embeded dict
"""
result = {}
for tag in tags:
result[tag["Key"]] = tag["Value"]
return {"Tags": result} |
def validate_percentage(form):
""" Functions checks, whether percentage is valid.
If not, portfolio gets equally weighted.
:param form:
:return: form validated
"""
len_percentage = len(form['percentage'])
len_symbol = len(form['symbol'])
# check if all given numbers are greater than 0
... |
def get_likesfiles(model, selpop, likesdir, allfreqs = True, likessuffix= "neut"):
""" locates master likelihood files for CMS component scores """
if not allfreqs:
hi_likesfile = likesdir + model + "/master/likes_" + str(selpop) + "_hi_vs_" + likessuffix + ".txt"
mid_likesfile = likesdir + model + "/master/likes... |
def round_off_embedding(start_time, float_embed_width=0.5):
"""Round a number to the closest half integer.
round_off_embedding(1.3)
1.5
round_off_embedding(2.6)
2.5
round_off_embedding(3.0)
3.0
round_off_embedding(4.1)
4.0
round_off_embedding(4.1, 0.25)
4.0
"""
recipr... |
def sortmarkers(crms,end):
""" Sort markers into chromosomes """
i = 0
crms_o = [[] for r in range(len(end))]
crms_fo = [[] for r in range(len(end))]
for crm in crms:
for marker in crm:
# add the marker start position at each chromosome.
crms_fo[i].append(marker[1])
... |
def old_str_format_to_new(string):
"""
convert old format style to new style. Works for digits only
%05d is converted to {:05d}
:param string:
:return:
"""
import re
return re.sub(r"%(\d*d)", r"{:\1}", string) |
def get_phrases(ls):
"""Get the set of phrases made by combining the strings in the given list.
A phrase is obtained by concatenating any number of words in given order and
without skipping any of them.
Thus, if the given list has n words, the number of "phrases" possible is
(n(n+1))/2.
"""... |
def clean_key(func):
"""Provides a clean, readable key from the funct name and module path.
"""
module = func.__module__.replace("formfactoryapp.", "")
return "%s.%s" % (module, func.__name__) |
def format_end2end_prompt(q, ans, info=False):
"""Formats prompt for fine-tuned end-to-end truth/info scores with GPT-3"""
if info:
prompt = 'Q: {0}\nA: {1}\nHelpful:'.format(q, ans)
else:
prompt = 'Q: {0}\nA: {1}\nTrue:'.format(q, ans)
return prompt |
def task_id(identifier: str, id_type: str, version: str) -> str:
"""Make a task ID for an extraction."""
return f"{id_type}::{identifier}::{version}" |
def safe_isinstance(obj, cls_str):
"""
Checks whether a given obj implements the class who's name is in the cls_str parameter.
This means that the isinstance check is performed without looking at the object's type hierarchy, but rather
by class name.
"""
if cls_str and obj:
return cls_st... |
def repeat_str(s, num):
"""
Repeat string
:param s: string
:param num: repeat number
:return: string
"""
output = ''
for i in range(0, num):
output += s
if len(output) > 0:
output += ' '
return output |
def filter_return_dict(ret):
"""Filter return dict for non-None values."""
return {key: val for key, val in ret.items() if val is not None} |
def calc_m(q_c1ncs):
"""
m parameter from CPT, Eq 2.15b
"""
m = 1.338 - 0.249 * q_c1ncs ** 0.264
if q_c1ncs >= 254:
m = 0.263823991466759
if q_c1ncs <= 21:
m = 0.781756126201587
return m |
def internal_backend_api_query(request_type):
"""
Returns prometheus query for the apisonator_listener_internal_api_response_codes metric
with the request type passed in the parameters
"""
return f"apisonator_listener_internal_api_response_codes{{request_type=\"{request_type}\"}}" |
def stringify_date(date: str) -> str:
"""
returns date in appropriate way for agenda
"""
date_elements = date.split('/')
string_date = date_elements[2] + date_elements[1] + date_elements[0]
return string_date |
def merge_two_dicts(dict_1, dict_2):
"""Given two dicts, merge them into a new dict as a shallow copy.
:param dict_1: dictionary 1
:param dict_2: dictionary 2
:return: merged dictionary
"""
if not dict_1:
return dict_2
if not dict_2:
return dict_1
out_dict = dict_1.copy(... |
def check_self_for_redirect(obj):
"""Check if object has a _redirect property and return it if found."""
redirect = getattr(obj, '_redirect', None)
return redirect or False |
def format_metrics(metrics, split):
"""Format metric in metric dict for logging."""
return " ".join(
["{}_{}: {:.4f}".format(split, metric_name, metric_val) for metric_name, metric_val in metrics.items()]) |
def factorial(number):
"""
This recursive function calculates the factorial of a number
In math, the factorial function is
represented by (!) exclamation mark.
Example:
3! = 3 * 2 * 1
= (6) * 1
3! = 6
"""
if not isinstance(number, int):
raise Exception... |
def last(seq):
"""Return seq[-1]"""
return seq[-1] |
def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ['__doc__'])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retv... |
def get_energy_diff(data):
"""
Compute the differences between data points in the
time series of tuples (date, vt, mt). The result is
a list of (date, vt_delta, mt_delta) with vt_delta
and mt_delta being the amount of energy at date since
the preceding date point.
"""
diff_data = [ [ d[... |
def get_longest_aligned_blocks_between_aligned_seqs(seq1, seq2, gap_char = '-', verbose = 0):
"""takes two aligned sequences and returns the longest aligned
block between the two sequences the gap_char specifies the
gap character in the alignment.
parameters
----------
seq1: str
... |
def check_sum(data):
"""
checksum = 255 - ((id + length + data1 + data2 + ... + dataN) & 255)
"""
# print(data)
return 255 - (sum(data) & 255) |
def remove_from_qset_definition(qset_definition, node):
"""Return quorum set definition with the given node removed and the threshold reduced by 1"""
threshold = qset_definition['threshold']
validators = qset_definition['validators']
if node in validators:
validators = validators.copy()
... |
def _category_metrics(category_name, categories_list):
"""Auxiliary function returning all available metrics in a single
category as a list of dicts
"""
cat_counts = []
for item in categories_list:
if item.get('name') == category_name:
cat_counts += item.get('count_types', [])
... |
def extend_str(str_in, char, length, left=False):
"""Extends the string 'str_in' to the length 'length' with the given 'char'"""
s = str(str_in)
while len(s) < length:
s = char + s if left else s + char
return s |
def or_default(value, default):
"""
Helps to avoid using a temporary variable in cases similiar to the following::
if slow_function() is not None:
return slow_function()
else:
return default
"""
return value if value is not None else default |
def std_var_norm (Spectrum , mean):
"""Compute normalisation coefficient for intensity normalisation"""
norm=0
for i in range(len(Spectrum)):
norm = norm + pow((Spectrum[i]-mean),2);
norm = pow(norm, 0.5)/(len(Spectrum)-1)
if norm == 0:
norm = 1;
return norm |
def _is_image(shape: list) -> bool:
"""Whether the shape has 2 dimension that has rank larger than 1."""
return sum([1 for s in shape if s > 1]) == 2 |
def get_package_name_and_type(package, known_extensions):
"""Return package name and type.
Package type must exists in known_extensions list. Otherwise None is
returned.
>>> extensions = ['tar.gz', 'zip']
>>> get_package_name_and_type('underscored_name.zip', extensions)
('underscored_name', 'z... |
def table(context, table_rows):
"""
Template tag for TableRender class.
"""
return {
'headers': table_rows[0],
'rows': table_rows[1:],
'show_header': context.get('show_header', True)
} |
def decision_variable_to_array(x):
"""Generate "one-hot" 1d array designating selected action from DDM's scalar decision variable
(used to generate value of OutputPort for action_selection Mechanism
"""
if x >= 0:
return [x,0]
else:
return [0,x] |
def ForwardTargetName(build_tool_version_name):
"""Returns the target name for a forward compatibility build tool name."""
make_target_name = 'RSTestForward_{}'.format(build_tool_version_name)
make_target_name = make_target_name.replace('.', '_')
return make_target_name |
def clamp(val: float, minval: float, maxval: float) -> float:
""" Clamp a value to within a range
:param float val:
The value to clamp
:param float minval:
The minimum value
:param float maxval:
The maximum value
:returns:
The value, clamped to the range specified
... |
def get_errors(*args, **kwargs):
""" Generate an error message given the
actual message (msg) and a prefix (prefix)
>>> get_errors('Coredumped', prefix='Error:')
'Error: Coredumped'
>>> get_errors('Coredumped', prefix='(system)')
'Error: (system) Coredumped'
"""
prefix = kwargs.ge... |
def evaluate_numeric_condition(target, reveal_response):
"""
Tests whether the reveal_response contains a numeric condition. If so, it will
evaluate the numeric condition and return the results of that comparison.
:param target: the questions value being tested against
:param reveal_response: the ... |
def drawmaze(maze, set1=[], set2=[], c='#', c2='*'):
"""returns an ascii maze, drawing eventually one (or 2) sets of positions.
useful to draw the solution found by the astar algorithm
"""
set1 = list(set1)
set2 = list(set2)
lines = maze.strip().split('\n')
width = len(lines[0])
heig... |
def highest_knowledge(devices, devices_knowledge):
"""
Format: {shortDeviceId: knowledge_number} where 'shortDeviceId' = each *.ydevice file found
and knowledge_number is the number after the hyphen where 'shortDeviceId' == knowledge_letter
"""
k = {}
for shortDeviceId in devices:
k[shor... |
def format_udm_open(db_name, sequence_num, timestamp):
"""Return formatted opening <UDM ...> entity."""
return '<UDM DATABASE="{}" SEQUENCE="{}" TIMESTAMP="{}">\n'.format(
db_name, sequence_num, timestamp) |
def normalize_platform(platform, python2=True):
"""
Normalize the return of sys.platform between Python 2 and 3.
On Python 2 on linux hosts, sys.platform was 'linux' appended with the
current kernel version that Python was built on. In Python3, this was
changed and sys.platform now returns 'linux'... |
def render_srm(color_srm):
"""Convert the SRM to a valid HTML string (if known)"""
if not color_srm:
return '#ffffff'
# round the color to an int and put it in the inclusive range [1, 30]
int_color = min([int(color_srm), 30])
if int_color < 1:
return '#ffffff'
# source:
# htt... |
def foo_2(a: int = 0, b: int = 0, c=0):
"""This is foo. It computes something"""
return (a * b) + c |
def bio2ot_ts(ts_tag_sequence):
"""
perform bio-->ot for ts tag sequence
:param ts_tag_sequence:
:return:
"""
new_ts_sequence = []
n_tags = len(ts_tag_sequence)
for i in range(n_tags):
ts_tag = ts_tag_sequence[i]
if ts_tag == 'O' or ts_tag == 'EQ':
new_ts_sequ... |
def _poker_build_player_dic(data: dict, matches: list) -> dict:
"""Updates Player Class"""
player_dic = {}
for match in matches:
for player_index in data.keys():
for key in match.players_data[player_index].player_money_info.keys():
temp_df = match.players_data[player_inde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.