content stringlengths 42 6.51k |
|---|
def get_maximum_norm(p1, p2):
"""Return the inf norm between two points."""
return max(abs(p1[0]-p2[0]), abs(p1[1]-p2[1])) |
def _handle_string(val):
"""
Replace Comments: and any newline found.
Input is a cell of type 'string'.
"""
return str(val).replace('Comments: ', '').replace('\r\n', ' ') |
def merge_dicts(*dict_args):
""" Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
This is exactly taken from: http://stackoverflow.com/questions/38987
"""
result = {}
for dictionary in dict_args:
result.update(diction... |
def rotations(rows):
"""
>>> rotations(('...', '###', '#.#'))
[('...', '###', '#.#'), ('##.', '.#.', '##.'), ('#.#', '###', '...'), ('.##', '.#.', '.##')]
"""
rotations = []
for _ in range(4):
rotations.append(rows)
rows = tuple("".join(row) for row in zip(*rows[::-1]))
re... |
def _merge_conditions(*conds):
"""combines conditions as a choice in binary range, eg, 2 conds --> [0, 3]"""
return sum(int(bool(c)) << i for i, c in enumerate(conds)) |
def pad_with_length(max_length: int, seq: list, pad_val: float):
"""
:param max_length: max length of token
:param seq: token list with shape:(length, dim)
:param pad_val: padding value
:return:
"""
pad_length = max(max_length - len(seq), 0)
pad = [pad_val] * pad_length
return seq + ... |
def particle_number(particle_name):
"""
Return an integer coding the particle type
'gamma'=0
'proton'=1
'electron'=2
'muon'=3
Parameters
----------
particle_name: str
Returns
-------
int
"""
return {
'gamma': 0,
'proton': 1,
'electron': 2... |
def rename_ledgers(ledgers, winning_pool):
""" Renames ledgers based on the given outcome """
if winning_pool == 'aboveEq':
ledgers['winLedger'] = ledgers.pop('betsAboveEq')
ledgers['splitLedger'] = ledgers.pop('providedLiquidityBelow')
elif winning_pool == 'below':
ledgers['winLed... |
def get_more_than_x(numbers, value):
""" Get numbers more than x in a list
"""
ret = list()
for i in numbers:
if i >= value:
ret.append(i)
return ret |
def flatten(list_of_lists):
"""Takes a list of lists and turns it into a list of the sub-elements"""
return [item for sublist in list_of_lists for item in sublist] |
def capfirst(s):
"""Capitalize the first letter of a string without touching the others"""
return s[:1].upper() + s[1:] |
def is_chinese(x) -> bool:
"""Recognizes whether the server/uid is chinese."""
return str(x).startswith(('cn','1','5')) |
def _parse_disallowed_patterns(disallowed_patterns):
""" Parse disallowed patterns from flake8 options.
Parameters
----------
disallowed_patterns : str
Configuration that represents a pairing of filename pattern
and regular expression for disallowed import.
Multiple items should... |
def parse_output_parameters(params):
"""
Parse the test case output parameters.
Args:
params: res[0].tr.id
Example:
ret = parse_output_parameters('result.res.data[0].id')
e.g. Data.tr.id => Data['tr']['id']
res.tr.id => res['tr]['id]
res[0].tr.id => res... |
def _parity_set(index):
"""The bits whose parity stores the parity of the bits 0 .. `index`."""
indices = set()
# For bit manipulation we need to count from 1 rather than 0
index += 1
while index > 0:
indices.add(index - 1)
# Remove least significant one from index
# E.g. 0... |
def power(l, amp=0.1, alpha=2.0, beta=-2.0, l0=2):
"""A broken power law power spectrum."""
l0 = int(l0)
if hasattr(l, "__len__"):
p = amp * ((l + 1.0) / (l0 + 1.0)) ** alpha
p[l >= l0] = amp * ((l[l >= l0] + 1.0) / (l0 + 1.0)) ** beta
p[0] = 1.0
return p
else:
if... |
def target_name(target_id):
"""Returns the target name, 'KIC {target_id}' or 'EPIC {target_id}'."""
if int(target_id) < 2e8:
return "KIC {}".format(target_id)
return "EPIC {}".format(target_id) |
def clean_non_ascii(str):
"""
remove non ascii chars from a string
"""
str = ''.join([i if ord(i) < 128 else ' ' for i in str])
return str |
def rational(init, final, total_steps, step):
"""
Compute the rational interpolation between two given values
and return the required intermediate value.
Parameters
----------
init: float
First value.
final: float
Last value
total_steps: float.
Number of intermed... |
def int_to_bytes(num):
"""Convert the given integer to bytes.
For example, giving the int ``1`` would return the byte string ``b'1'``.
:param int num: The number to convert. Should be non-negative, but works
either way.
:return: The number as a byte string.
:rtype: bytes
"""
if num... |
def positions_to_gaps(positions):
"""helper"""
if len(positions) == 1:
return [positions[0][0], positions[0][1]]
else:
return [positions[0][0]] + [int(0.5 * (x[1] + y[0]))
for x, y in list(zip(positions[:-1], positions[1:]))] + [positions[-1][1]] |
def hide_link(url):
"""
Hide URL (HTML only)
Can be used for adding an image to a text message
:param url:
:return:
"""
return f'<a href="{url}">​</a>' |
def get_runner_image_url(experiment, benchmark, fuzzer, docker_registry):
"""Get the URL of the docker runner image for fuzzing the benchmark with
fuzzer."""
return '{docker_registry}/runners/{fuzzer}/{benchmark}:{experiment}'.format(
docker_registry=docker_registry,
fuzzer=fuzzer,
b... |
def IsJsFile(ref):
"""Returns true if the provided reference is a Javascript file."""
return ref.endswith('.js') |
def int_to_arr(txt, txt_size):
"""
Convert hex string into an array of 64-bit words
Args:
txt: a int
txt_size: The bit length
Returns:
arr: input as list of 64-bit words
"""
arr = []
displacement = txt_size
while displacement >= 64:
displacement ... |
def sanitize_float_for_api(float_val, precision=2):
"""Sanitizes a float value for use in the API."""
template = '%.' + str(precision) + 'f'
return template % float(float_val) |
def _get_mean_and_sigma_of_product_of_two_gaussians(mean1, mean2, var1, var2):
"""
product of two gaussian pdfs is a gaussian with mean = (var1 * mean2 + var2 * mean1) / (var1 + var2) and var = (1/var1 + 1/var2)^ -1
"""
return (mean2 * var1 + mean1 * var2) / (var1 + var2), ((1 / var1) + (1 / var2)) ** -... |
def twosComplement(value, bitSize):
"""compute the 2's complement of int value"""
if (value & (1 << (bitSize - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
value = value - (1 << bitSize) # compute negative value
return value # return positive value as is |
def list_to_infix(L,operator="+"):
"""Turns a list into a summation by some symbol"""
S = f" {operator} ".join(str(elem) for elem in L)
return S |
def _set_kwargs_quiet(kwargs, quiet=True):
"""
Enable quiet switch in keyword cmd_args
:param kwargs:
:param quiet:
:return:
"""
kwargs['quiet'] = quiet
return kwargs |
def find_continuous_k_naive(l, k):
"""
Naive solution
Iterate through elements of the list and build subarrays forward
Check the sum of which sub-array as you go
Complexity: O(n^2)
"""
results = []
for i in range(len(l)):
sum = 0
j = i
while j<len(l):
... |
def get_recommendation_string_from_parsed_exps(exp_list):
"""
Generate recommendation text we can display on a flask app
:param exp_list: array of dictionaries containing explanations
:return: HTML displayable recommendation text
"""
recommendations = []
for i, feature_exp in enumerate(exp_l... |
def get_url(entry):
""" Return URL from response if it was received otherwise requested URL. """
if 'response' in entry:
return entry['response']['url']
return entry['request']['url'] |
def renaming_xis_for_posting_to_xse(data):
"""Renaming XIS column names to match with XSE"""
data['_id'] = data.pop('metadata_key_hash')
data['metadata'] = data.pop('metadata')
return data |
def linear_map(i, i_min, i_max, o_min, o_max):
"""mapping function"""
if o_max > o_min:
out = (float((i - i_min)) / float(i_max - i_min)) * \
float(o_max - o_min) + o_min
else:
out = (1.0 - (float(i - i_min) / float(i_max - i_min))) * \
float(o_min - o_max) + o_max
... |
def unpack3(var, struct_var, buff):
"""
Create an unpack call on the ``struct.Struct`` object with the name
``struct_var``.
:param var: variable the stores the result of unpack call, ``str``
:param str struct_var: name of the struct variable used to unpack ``buff``
:param buff: buffer that the ... |
def generalized_check_balance(input_str):
"""
Generalization of balanced paranthesis to
also include '{}' and '[]'
"""
stack = list()
balanced = True
matches = {'}': '{', ')': '(', ']':'['}
for char_ in input_str:
if char_ in '[{(':
stack.append(char_)
elif ch... |
def set_in_samples(samples, fn, value):
"""
update a list of samples with a given value
"""
return [fn(x, value) for x in samples] |
def _get_downcast_field(class_reference):
"""Get the downcast field name if set, None otherwise."""
return getattr(class_reference, "__deserialize_downcast_field__", None) |
def power_of_two(x):
"""
Determines if a given non-negative integer is a power of two.
:param x: non-negative integer.
:return: True if x is a power of 2, otherwise False.
"""
return (x & (x-1) == 0) and x != 0 |
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
Args
... |
def is_callback(func):
"""Check if function is callback."""
return '_pyhap_callback' in getattr(func, '__dict__', {}) |
def make_path(came_from, start, goal):
""" retrace breadcrumbs to reconstruct path """
cp = goal
path = []
while cp != start:
path.append(cp)
if cp in came_from:
cp = came_from[cp]
else:
return []
path.append(start)
path.reverse()
return path |
def pretty_time_delta(seconds):
"""Returns time delta in easily readable format"""
output = '-' if seconds < 0 else ''
seconds = abs(int(seconds))
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
if days > 0:
output ... |
def hyperfactorial(k: int) -> int:
"""
Returns the hyperfactorial of the number, the product of all positive integers to the power of themselves smaller
or equal to the number.
By convention an empty product is considered 1, meaning hyperfactorial(0) will return 1.
:param k: A positive integer
... |
def new_entry(path, title, gen_title):
"""Make new entry in table."""
entry = """<tr>
<td><img src="{}"></td>
<td>
<p><b>Original:</b> {}</p>
<p><b>Generated:</b> {}</p>
</td>
</tr>""".format(
path, title, gen_title
)
return entry |
def unix_path(path):
"""
unix_path(path)
Convert a path to use forward slash (/) instead of double backslash (\\).
Needed when running script on windows.
"""
return path.replace("\\", "/") |
def sol(n):
"""
Get the last bit and build the number treating it as first from the left
and so on..
"""
p = 31
res = 0
while p >= 0:
bit = n&1
res = res + bit*(1<<p)
# 1<<p is like saying 2**p
p-=1
n=n>>1
return res |
def add_label(label, existing_label):
"""
Generate a leaf node of label hierarchy.
"""
new_label = None
if existing_label:
if existing_label in label:
new_label = label
else:
new_label = existing_label
else:
new_label = label
return new_label |
def format_choice_fields(value):
"""Convert the choice fields into human readable formats.
Note:
This will work with Datetime objects by returning them as is
or "-" where they are None
"""
options = {
'SLSE': 'Secondary School',
'SLPR': 'Primary School',
'SLNS': 'No Scho... |
def format_log(log: str):
"""
Postgres doesn't support indexing large text files.
Therefore we limit line length and count
"""
lines = log.splitlines(keepends=True)
lines = map(lambda line: f"{line[:400]}\n" if len(line) > 400 else line, lines)
remove_lines_marker = (
'/homeless-shel... |
def not_valid(peer_id, doc_id):
"""
There are some summaries full of dashes '-' which are not easy to be handled
:param peer_id: The peer id of the author
:param doc_id: The id of corresponding document
:return: Bool True or False whether or not the summary is valid
"""
return True if (peer... |
def absolute_deviation(simulated, observed, threshold):
"""Return the absolute deviation of a simulated value from an observed value."""
return abs(simulated - observed) > threshold |
def words_are_anagrams(word_list, debug):
"""Return whether words in list are anagrams of each other."""
letters = sorted(word_list[0])
return all(sorted(word) == letters for word in word_list) |
def parse_dhm_request(msg: str) -> int:
"""Parse client's DHM key exchange request
:param msg: client's DHMKE initial message
:return: number in the client's message
"""
return int(msg.split(':')[1]) |
def playlist_from_commands(comms):
"""
For development purposes only: creates a playlist with all the recorded audio files in the order
they should be played.
"""
playlist = []
for i in range(len(comms)):
for j in range(len(comms[i])):
command = comms[i][j]
if "PT... |
def is_permutation(xs, ys):
"""Returns True iff the two lists are permutations of eachother."""
return sorted(xs) == sorted(ys) |
def fcn_VR_FMM(r_div_R):
""" Transversal velocity factor of FMM in Eq. (31) in [2]
"""
return (1/2.)*(3.*r_div_R - r_div_R**3.0) |
def summable(number, preamble):
""" Checks if any given pair in the preamble sums up to the specified number.
:param number: int
:param preamble: numpy array
:return: boolean
"""
for i in range(len(preamble)):
for j in range(len(preamble)):
if i != j and preamble[i] + pream... |
def get_shas(output):
"""Returns a dict of CSS files and SHAs"""
output_lines = output.splitlines()
sha_dict = {}
for line in output_lines:
line = line.decode('utf-8').replace("\t","").split(" ")
sha = line[1]
css_file = [file for file in line[2].split("/") if "css" in fil... |
def tzip(*iterables):
"""
>>> tzip('ABCD', 'xy')
(('A', 'x'), ('B', 'y'))
"""
return tuple(zip(*iterables)) |
def readOS(seqTitle):
"""Extract OS tag from sequence description
Get the microorganism name from sequence title
Args:
seqTitle: SequenceObject.description
Return
Microorganism species name
"""
i = 0
x = seqTitle.find("=", i) + 1
i = x + 1
y = seqTitle.find("=", i... |
def mean(numbers):
"""Find the mean using an iterable of numbers
Return None if the iterable is empty
"""
if not numbers:
return None
total = 0
count = 0
for number in numbers:
total += number
count += 1
return total / count |
def sort_by_value(dict):
""" Returns the keys of dictionary d sorted by their values """
items=dict.items()
backitems=[ [v[1],v[0]] for v in items]
backitems.sort()
return [ backitems[i][1] for i in range(0,len(backitems))] |
def format_setting(setting):
"""
Return setting as string in the format needed for PolyChord's .ini files.
These use 'T' for True and 'F' for False, and require lists of numbers
written separated by spaces and without commas or brackets.
Parameters
----------
setting: (can be any type for w... |
def sri(b4, b8):
"""
Simple Ratio Index (Jordan, 1969).
.. math:: SRI = b8/b4
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
:returns SRI: Index value
.. Tip::
Jordan, C.F. 1969. Derivation of leaf-area index from quality... |
def deep_update(original, update):
"""Update dict without overwriting objects."""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deep_update(value, update[key])
return update |
def _ncpus_memory(length, loading=3, node_cpus=48, node_memory=192):
"""Determine the number of cpus for the MPI job."""
n_nodes = length // loading // node_cpus
if n_nodes == 0:
n_nodes = 1
n_cpus = n_nodes * node_cpus
memory = n_nodes * node_memory
if n_cpus > length:
n_cpus... |
def split(lower_bound, upper_bound, middle):
"""
Helper function to split the indices for BFS.
"""
if lower_bound == middle:
L = None
R = [middle + 1, upper_bound]
elif upper_bound == middle:
L = [lower_bound, middle - 1]
R = None
else:
L = [lower_bound, m... |
def first(iterable):
"""
Gets the first element from an iterable. If there are no items or there
are not enough items, then None will be returned.
:param iterable: Iterable
:return: First element from the iterable
"""
if iterable is None or len(iterable) == 0:
return None
return ... |
def formatWithComma (Field, x, xerr):
"""
Parameters
----------
Field : The name of the field
x : Value of the field
xerr : Error in the field
Returns
-------
Str
Field: x +/- xerr
"""
return str(Field) + ", " + str(x) + ", +/-, " + str(xerr) + "\n" |
def isNumber(val):
"""
Tests if this is a number in base python or sympy.
Parameters
----------
val: float/int/complex/sympy.expression
Returns
-------
bool
"""
try:
_ = complex(val)
return True
except TypeError:
return False |
def module_level_function(param1: int, param2: str, *args, **kwargs) -> bool:
"""Example function with PEP 484 type annotations.
Args:
param1: The first parameter.
param2: The second parameter.
Returns:
The return value. True for success, False otherwise.
Raises:
Attri... |
def adjust_reg(reg, epoch, total_epochs, max_reg=1.0):
"""Reconfigures the regularization strength"""
return min(reg * epoch / total_epochs, max_reg) |
def describe_text_changes(text_changes):
""" Return a textual description (str) for a list of text fields. """
return ', '.join([change['name'] for change in text_changes]) |
def _getResponseRates(results):
"""
Returns: (# Total events, # accepts, # dismisses)
"""
notificationEvents = [r for r in results if r['decision']]
numNotifications = len(notificationEvents)
numAcceptedNotifications = len([r for r in notificationEvents if r['reward'] > 0])
numDismissedNotif... |
def is_tty(stream):
"""Returns True if the given stream is a tty, else False
:param stream: object to be checked for being a tty
:returns: True if the given object is a tty, otherwise False
:rtype: bool
"""
return hasattr(stream, 'isatty') and stream.isatty() |
def iterate_cell(merged_cell):
"""Takes a cell and sum of neighbours and returns True/False if the cell is
alive/dead. """
cell = bool(merged_cell & 16)
sum_of_neighbours = merged_cell - 16 if cell else merged_cell
if 2 <= sum_of_neighbours <= 3 and cell:
# if between 2 and 3 nbrs, keep ali... |
def take_optional_field(field, obj):
"""
Get a field form an object, remove its value and remove the field form the object
"""
if field not in obj:
return None
value = obj[field]
del obj[field]
return value |
def selected(value, target):
"""Return 'selected' if `value` equals `target`."""
if value == target:
return 'selected'
return '' |
def monomer_from_anisotropy(a, Am, Ad, b):
"""
Calculate monomer fraction from anisotropy, monomer and dimer anisotropy
and brightness relation.
"""
return (b * a - Ad*b) / ((Am - b * Ad) - (1-b) * a) |
def prop_parse(props):
"""Given an input list of strings, for each string that has an = in it,
return a mapping of the left halves to the right halves. For a string to
end up in the map it must have format key=value, forming {key: value}"""
result = {}
for arg in props:
split = arg.split('... |
def next_or_none(cursor):
"""Tries to get the next(cursor) element but catches errors and returns none upon failure"""
try: return next(cursor)
except: return None |
def chunkstring(string, length):
"""
Convert a string to an n x length array
@param {string} string Input string to convert
@param {Integer} length Length of an array element
@return {Array} Intended layout of a rectangle
"""
return tuple(string[0+i:length+i] for i in range(0, len(s... |
def multiplication_tables_generator(times: int, min: int, max: int) -> list:
"""
>>> multiplication_tables_generator(2, 1, 10)
['1 x 2 = 2', '2 x 2 = 4', '3 x 2 = 6', '4 x 2 = 8', '5 x 2 = 10', '6 x 2 = 12', '7 x 2 = 14', '8 x 2 = 16', '9 x 2 = 18', '10 x 2 = 20']
"""
tables = []
for number in ... |
def inherit_config(child, parent, keys):
"""
If a key in keys does not exist in child, assigns the key-value in parent to
child.
"""
for key in keys:
if key not in child.keys():
child[key] = parent[key]
print(
"{} not found in io.yaml file, falling... |
def string_list_handler(option_value=None):
"""Split a comma-separated string into a list of strings."""
result = None
if option_value is not None:
result = option_value.split(',')
return result |
def set_bitfield_bit(bitfield, i):
"""
Set the bit in ``bitfield`` at position ``i`` to ``1``.
"""
byte_index = i // 8
bit_index = i % 8
return (
bitfield[:byte_index] +
bytes([bitfield[byte_index] | (1 << bit_index)]) +
bitfield[byte_index + 1:]
) |
def in_each(source, method):
"""
In each is a iterator function which you can employ the method
in every item in source.
:param source: a list of items
:param method: the method you want to employ to the items
:return: the new items
"""
return [method(x) for x in source] |
def remove_empty_keys(dirty_dict):
"""
Remove empty keys from a dictionary. This method is useful when passing jsons
in which a null field will update the value to null and you don't want that.
"""
clean_dict = {}
for k, v in dirty_dict.items():
if v:
clean_dict[k] = v
... |
def convert_github_url_into_raw_url(github_url:str) -> str:
"""Convert github url into raw github url.
Args
github_url: github url
Returns
raw github url
"""
github_url = github_url.split("#L")[0]
raw_github_url = github_url.replace("github.com", "raw.githubusercontent.com"). \
... |
def adresa_inceput(netmask, ip):
"""
Ia un netmask si un IP si determina adresa de inceput
a retelei
:param (str) netmask:
:param (str) ip:
:return adresa_inceput (str):
"""
netmask_nums = netmask.split(".")
ip_nums = ip.split(".")
adresa_inceput = ""
for i in ra... |
def shouldExcludeFile(filename, excludes):
"""
Determines whether a file is in an excluded directory.
Arguments:
- filename: filename being tested
- excludes: array of excluded directory names
Returns: True if should exclude, False if not.
"""
for exc in excludes:
if exc... |
def offsets( q_cont, u_cont, delta_q_cont, delta_u_cont, q_model, u_model):
"""
Offset between the target data continuum q and u and a given model.
This offset is applied to target data values before they are modelled.
"""
ksi_q = q_model - q_cont
ksi_u = u_model - u_cont
delta_ksi_q =... |
def less_uppers(one, two):
"""Return the string with less uppercase letters."""
one_count = sum(1 for c in one if c.islower())
two_count = sum(1 for c in two if c.islower())
return one if one_count >= two_count else two |
def all_unique(s):
"""
Returns a boolean which is True if each element in
iterable was used only once.
>>> all_unique('abcd')
True
>>> all_unique('ab')
False
"""
seen_it = {}
for c in s:
if c in seen_it:
return False
else:
seen_it[c] = Tru... |
def concatenated(lst, element):
"""
concatenates `element` to `lst` and
returns lst
"""
lst.append(element)
return lst |
def _unique_label(previous_labels, label):
"""Returns a unique name if label is already in previous_labels."""
while label in previous_labels:
label_split = label.split('.')
if label_split[-1].startswith('copy'):
copy_num = 1
if label_split[-1] != "copy":
... |
def asStr(val):
"""Returns val converted to a string (str object) if possible,
else returns a unicode string. Differs from str in that it
does not choke on unicode strings.
"""
try:
return str(val)
except ValueError:
return str(val) |
def escape_space(string: str):
"""
Returns a copy of `string` with all it's spaces prefixed with "\".
:param string: str
:return: str
"""
if not string or " " not in string:
return string
length = len(string)
if length == 1:
return r"\ " if string == " " else string
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.