content stringlengths 42 6.51k |
|---|
def adapt_impedance_params(Z, sign=1, adaption=1e-15):
"""
In some extreme cases, the created admittance matrix of the
zpbn network is singular. The routine is unsolvalbe with it.
In response, an impedance adaption is created and added.
"""
rft_pu = Z.real + sign*adaption
xft_pu = Z.imag + sign*adaption
return rft_pu, xft_pu |
def hex_to_rgb(x):
"""Turns a color hex representation into a tuple representation."""
return tuple([int(x[i:i + 2], 16) for i in (0, 2, 4)]) |
def _correct_quandl_request_stock_name(names):
"""If given input argument is of type string,
this function converts it to a list, assuming the input argument
is only one stock name.
"""
# make sure names is a list of names:
if isinstance(names, str):
names = [names]
return names |
def unique(source):
"""
Returns unique values from the list preserving order of initial list.
:param source: An iterable.
:type source: list
:returns: List with unique values.
:rtype: list
"""
seen = set()
return [seen.add(x) or x for x in source if x not in seen] |
def collect_psi4_options(options):
"""Is meant to look through the dictionary of psi4 options being passed in and
pick out the basis set and QM method used (Calcname)
which are appened to the list of psi4 options
"""
keywords = {}
for opt in options['PSI4']:
keywords[opt] = options['PSI4'][opt]
basis = keywords['BASIS']
del keywords['BASIS']
QM_method = keywords['CALCNAME']
del keywords['CALCNAME']
return QM_method, basis, keywords |
def obj_dist_from_EFL_and_m(f,m):
"""Calculate object distance (z) from focal length (f) and magnification (m)
"""
obj_dist = -1*((1-m)/m)*f
return obj_dist
# todo: clarify assumptions in terms of +/- distances. |
def eh_peca(arg):
"""
eh_peca: universal -> booleano
Devolve True caso o seu argumento seja um TAD peca
ou False em caso contrario.
"""
return type(arg) == dict and \
len(arg) == 1 and \
'peca' in arg and \
type(arg['peca']) == str and \
len(arg['peca']) == 1 and \
arg['peca'] in 'XO ' |
def s_and(*args):
"""Logical and."""
result = True
for i in args:
result = result and i
if not result:
break
return result |
def getxy(a, b):
"""x*a + y*b = gcd(a,b)"""
""" input requirement: a > b """
""" get x for a and y for b"""
remainder = a % b
k = a // b
if b % remainder == 0:
return 1, -k
else:
x1, y1 = getxy(b, remainder)
return y1, y1 * (-k) + x1 |
def locationSlice(lmA, prefix):
"""Recovers locations with a given prefix
Keyword arguments:
lmA -- Location map to recover location from
prefix -- Key or part of key in location map dictionary
Creates a copy of provided location map lmA
Copy contains all key-value pairs from lmA in which the key does start with the given prefix
"""
lmCopy = dict()
for key, value in lmA.items():
keyStartsWithPrefix = key.rfind(prefix, 0)
if(keyStartsWithPrefix == 0):
newKey = key[len(prefix):]
if(newKey == ""):
lmCopy["."] = value
else:
lmCopy[newKey[1:]] = value
return lmCopy |
def _merge_opts(opts, new_opts):
"""Helper function to merge options"""
if isinstance(new_opts, str):
new_opts = new_opts.split()
if new_opts:
opt_set = set(opts)
new_opts = [opt for opt in new_opts if opt not in opt_set]
return opts + new_opts
return opts |
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.
>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 3+2, 3-2)
1
>>> if_function(3>2, 3+2, 3-2)
5
"""
if condition:
return true_result
else:
return false_result |
def is_constant(s: str) -> bool:
"""Checks if the given string is a constant.
Parameters:
s: string to check.
Returns:
``True`` if the given string is a constant, ``False`` otherwise.
"""
return s == 'T' or s == 'F' |
def is_power_of_2(num):
"""
Returns whether num is a power of two or not
:param num: an integer positive number
:return: True if num is a power of 2, False otherwise
"""
return num != 0 and ((num & (num - 1)) == 0) |
def sol_1(ar: list) -> list:
"""using count (not inplace)"""
return [0]*ar.count(0) + [1]*ar.count(1) + [2]*ar.count(2) |
def _normalize_deps(deps, more_deps = None):
""" Create a single list of deps from one or 2 provided lists of deps.
Additionally exclude any deps that have `/facebook` in the path as these
are internal and require internal FB infra.
"""
_deps = deps or []
_more_deps = more_deps or []
_deps = _deps + _more_deps
derps = []
for dep in _deps:
if dep.find("facebook") < 0:
derps.append(dep)
return derps |
def vector_subtract(first: tuple, second: tuple) -> tuple:
""" 2-D simple vector subtraction w/o numpy overhead. Tuples must be of the same size"""
return first[0] - second[0], first[1] - second[1] |
def _useBotoApi(storage_schema):
"""Decides if the caller should use the boto api given a storage schema.
Args:
storage_schema: The schema represents the storage provider.
Returns:
A boolean indicates whether or not to use boto API.
"""
if storage_schema == 'gs' or storage_schema == 's3':
return True
else:
return False |
def single_quote(name: str) -> str:
"""Represent a string constants in SQL."""
if name.startswith("'") and name.endswith("'"):
return name
return "'%s'" % name |
def recursive_knapsack(profits, profits_length, weights, capacity):
"""
Parameters
----------
profits : list
integer list containing profits
profits_length : int
number of profits in profit list
weights : list
integer list of weights
capacity : int
capacity of the bag
Returns
-------
int
maximum profit
>>> profits = [60, 100, 120]
>>> profits_length = 3
>>> weights = [10, 20, 30]
>>> capacity = 50
>>> recursive_knapsack(profits, profits_length, weights, capacity)
220
"""
def ks(remaining_capacity, profits_so_far, current_item):
if remaining_capacity == 0: # the bag is full
return profits_so_far
if remaining_capacity < 0: # the bag is over full
return float("-inf")
if current_item >= profits_length:
return profits_so_far
including = ks(remaining_capacity - weights[current_item], profits_so_far + profits[current_item],
current_item + 1)
excluding = ks(remaining_capacity, profits_so_far, current_item + 1)
return max(including, excluding)
return ks(capacity, 0, 0) |
def validate_required_fields(metadata):
"""Check if the metadata can be used on analysis. This is evolving"""
required = ['RESULTS-BALANCED_ACCURACY']
val = True
for field in required:
val = val & (field in metadata)
return val |
def trim_proximal_primer(primer_list, seq):
"""Doc string here.."""
p_primer_found = "";
offset = 0;
for primer in primer_list:
#print primer
prim_len = len(primer)
idx = seq.find(primer)
if(idx != -1):
if(idx == 0):
p_primer_found = primer
seq = seq[prim_len:]
break
elif(idx == 1):
# sometimes get a stray base between runkey and proximal primer
# kind of close??
p_primer_found = primer
offset = idx
seq = seq[idx + prim_len:]
break
return p_primer_found, offset, seq |
def parse_comma_separated_list(s):
"""
Parse comma-separated list.
"""
return [word.strip() for word in s.split(',')] |
def odd_check(number: int) -> bool:
"""[summary]
Args:
number (int): [positive number]
Returns:
bool: [Return True If The Number Is Odd And False If The Number Is Even]
"""
if number % 2 == 0:
return False
else:
return True |
def iob1_iob2(tags):
"""
Check that tags have a valid IOB format.
Tags in IOB1 format are converted to IOB2.
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == 'O':
new_tags.append(tag)
else:
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
raise Exception('Invalid IOB format!')
elif split[0] == 'B':
new_tags.append(tag)
elif i == 0 or tags[i - 1] == 'O': # conversion IOB1 to IOB2
new_tags.append('B' + tag[1:])
elif tags[i - 1][1:] == tag[1:]:
new_tags.append(tag)
else: # conversion IOB1 to IOB2
new_tags.append('B' + tag[1:])
return new_tags |
def get_average(img, u, v, n):
"""img as a square matrix of numbers"""
s = 0
for i in range(-n, n+1):
for j in range(-n, n+1):
s += img[u+i][v+j]
return float(s)/(2*n+1)**2 |
def h2(text):
"""h2 tag
>>> h2('my subheading')
'<h2>my subheading</h2>'
"""
return '<h2>{}</h2>'.format(text) |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
L = len(seq)
for _ in range(L):
for n in range(1, L):
if seq[n] < seq[n - 1]:
seq[n - 1], seq[n] = seq[n], seq[n - 1]
return seq |
def make_counter_summary(counter_element, covered_adjustment=0):
"""Turns a JaCoCo <counter> element into an llvm-cov totals entry."""
summary = {}
covered = covered_adjustment
missed = 0
if counter_element is not None:
covered += int(counter_element.attrib['covered'])
missed += int(counter_element.attrib['missed'])
summary['covered'] = covered
summary['notcovered'] = missed
summary['count'] = summary['covered'] + summary['notcovered']
if summary['count'] != 0:
summary['percent'] = (100.0 * summary['covered']) / summary['count']
else:
summary['percent'] = 0
return summary |
def get_disk_label_no(drive_partitions, ip_label):
"""
Returns the swift disk number of a partition that has already been
labelled
"""
partitions = drive_partitions.split()
num = "-1"
for part in partitions:
if (ip_label + "h") in part:
_, num = part.strip("]'").split("h")
return num |
def fp_boyer_freqs(ups_r, ups_theta, ups_phi, gamma, aa, slr, ecc, x, M=1):
"""
Boyer frequency calculation
Parameters:
ups_r (float): radial frequency
ups_theta (float): theta frequency
ups_phi (float): phi frequency
gamma (float): time frequency
aa (float): spin parameter (0, 1)
slr (float): semi-latus rectum [6, inf)
ecc (float): eccentricity [0, 1)
x (float): inclination value given by cos(theta_inc) (0, 1]
negative x -> retrograde
positive x -> prograde
Keyword Args:
M (float): mass of large body
Returns:
omega_r (float): radial boyer lindquist frequency
omega_theta (float): theta boyer lindquist frequency
omega_phi (float): phi boyer lindquist frequency
"""
omega_r = ups_r / gamma
omega_theta = ups_theta / gamma
omega_phi = ups_phi / gamma
return omega_r, omega_theta, omega_phi |
def human2bytes(s):
""" convert human readable size string to int """
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
letter = s[-1:].strip().upper()
num = s[:-1]
assert num.isdigit() and letter in symbols
num = float(num)
prefix = {symbols[0]:1}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i+1)*10
return int(num * prefix[letter]) |
def getAllReachable1Step(original_nodes):
"""
return all node, value pairs reachable from any of the pairs in the original nodes in a single step
:param original_nodes: a set of node, value, complete_path pairs from which we check what they can reach in 1 step
:return: a set of node, value pairs that can be reached from any of original_nodes in a single step
"""
reachable = set()
for node in original_nodes: # for each node in our set, we gather it's reachable states and add them to our result
lis = node[0].get_edges()
for new_node in lis: # a newly reachable node is only reachable by another node, each node can only have V-1 O(V) outgoing edges
if node[1] + new_node[1] >= 0 and node[1] + new_node[1] not in new_node[0].get_disequalities():
# check if this node does not infringe upon any disequalities or other rules
tup = (new_node[0], node[1] + new_node[1])
reachable.add(tup)
return reachable |
def summarizeBeatInfo(note_centers_list):
"""
Convert list of note centers to map of note centers for each beat.
"""
x_positions = list(map(lambda center: center[0], note_centers_list))
return max(set(x_positions), key=x_positions.count) |
def colored(fmt, fg=None, bg=None, style=None):
"""
Return colored string.
List of colours (for fg and bg):
k black
r red
g green
y yellow
b blue
m magenta
c cyan
w white
List of styles:
b bold
i italic
u underline
s strike through
x blinking
r reverse
y fast blinking
f faint
h hide
Args:
fmt (str): string to be colored
fg (str): foreground color
bg (str): background color
style (str): text style
"""
colcode = {
'k': 0, # black
'r': 1, # red
'g': 2, # green
'y': 3, # yellow
'b': 4, # blue
'm': 5, # magenta
'c': 6, # cyan
'w': 7 # white
}
fmtcode = {
'b': 1, # bold
'f': 2, # faint
'i': 3, # italic
'u': 4, # underline
'x': 5, # blinking
'y': 6, # fast blinking
'r': 7, # reverse
'h': 8, # hide
's': 9, # strike through
}
# properties
props = []
if isinstance(style, str):
props = [fmtcode[s] for s in style]
if isinstance(fg, str):
props.append(30 + colcode[fg])
if isinstance(bg, str):
props.append(40 + colcode[bg])
# display
props = ';'.join([str(x) for x in props])
if props:
return '\x1b[%sm%s\x1b[0m' % (props, fmt)
else:
return fmt |
def list2dict(L, value=None):
"""creates dict using elements of list, all assigned to same value"""
return dict([(k, value) for k in L]) |
def convert_energy_unit(energy_val, current_unit, new_unit):
"""
Convert `energy_val` from the `current_unit` to `new_unit`.
Only support kJ/mol, kcal/mol, and J/mol.
"""
if current_unit == 'kJ/mol' and new_unit == 'kcal/mol':
return energy_val / 4.184
elif current_unit == 'kJ/mol' and new_unit == 'J/mol':
return energy_val * 1000
elif current_unit == 'J/mol' and new_unit == 'kJ/mol':
return energy_val / 1000
elif current_unit == 'J/mol' and new_unit == 'kcal/mol':
return energy_val / 4184
elif current_unit == 'kcal/mol' and new_unit == 'kJ/mol':
return energy_val * 4.184
elif current_unit == 'kcal/mol' and new_unit == 'J/mol':
return energy_val * 4184
else:
raise ValueError("Unsupported units") |
def unescape_text(text):
"""Replace HTML escape codes with special characters.
Args:
text: The text to unescape.
Returns:
The unescaped text.
"""
if text:
text = text.replace(""", "\"")
text = text.replace("'", "'")
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace(" ", " ")
text = text.replace("&", "&")
return text |
def S_crop_values(_data_list, _max, _min):
"""
Returns a filtered data where values are discarded according to max, min limits.
"""
f_data = []
ds = len(_data_list)
i = 0
while i < ds:
if _data_list[i] >= _max:
f_data.append(_max)
elif _data_list[i] <= _min:
f_data.append(_min)
else:
f_data.append(_data_list[i])
i += 1
return f_data |
def str2bool(s):
"""
Converts an on/off, yes/no, true/false string to True/False.
Booleans will be returned as they are, as will non-boolean False-y values.
Anything else must be a string.
"""
if type(s) == bool:
return s
if s and s.upper() in [ 'ON', 'YES', 'Y', 'TRUE', '1' ]:
return True
else:
return False |
def specificHumidity(qv):
"""
specificHumidity()
Purpose: Calculate the specific humidity from mixing ratio
Parameters: qv - Water vapor mixing ratio in kg/kg
Returns: Specific humidity in kg/kg
"""
return qv/(1 + qv) |
def time_setting_dict(time_str):
"""Convert a time string like 90s, 3h, 1d, to a dictionary with a
single keyword-value pair appropriate for keyword value settings to
the python datetime.timedelta function. For example, input of "3h"
should return {"hours": 3}.
Args:
time_str: Time string with units (e.g., 90s, 3h, 1d)
Returns:
dict: Keyword-value pair indicating command line arguments
"""
time_unit_dict = {"s": "seconds",
"m": "minutes",
"h": "hours",
"d": "days",
"w": "weeks"}
return {time_unit_dict[time_str[-1]]: int(time_str[:-1])} |
def htheta_function(x1, x2, theta_0, theta_1, theta_2):
"""
Linear function that is to optimized
"""
return theta_0 + theta_1 * x1 + theta_2 * x2 |
def nbsp(text):
"""
Replace spaces in the input text with non-breaking spaces.
"""
return str(text).replace(' ', '\N{NO-BREAK SPACE}') |
def pairs_sort(k, arr):
"""
Runtime: O(n^2)
By sorting, we can avoid some unnecessary comparisons.
"""
if len(arr) < 2:
return []
pairs = []
arr.sort()
for i, n1 in enumerate(arr):
for n2 in arr[i+1:]:
if n1 + n2 > k:
# All other pairs will
# be bigger than k. Stop.
break
if n1 + n2 == k:
pairs.append([n1,n2])
return pairs |
def quad_BACT_to_gradient(bact, l):
"""Convert a SLAC quad BACT (kG) into BMAD b1_gradient T/m units"""
return -bact/(10.0*l) |
def show_hidden(str,show_all=False):
"""Return true for strings starting with single _ if show_all is true."""
return show_all or str.startswith("__") or not str.startswith("_") |
def text_reformat(text):
"""lowercase without punctuation"""
import re
return re.sub(r'[^\w\s]', '', text.lower()) |
def split_composites(old_composites):
"""
Split the old composites in 5 equal parts.
:param old_composites: The old composites that need to be split.
:return: returns a list of composite lists. Where each composite list has count ~= len(old_composites) // 5.
"""
new_composites = []
if len(old_composites) <= 5:
for composite in old_composites:
new_composites.append([composite])
return new_composites
pieces = 5
count = len(old_composites) // pieces
increments = [count] * pieces
rest = len(old_composites) % pieces
for i in range(rest):
increments[i] += 1
offset = 0
for i in range(len(increments)):
temp_composites = []
for j in range(increments[i]):
temp_composites.append(old_composites[offset + j])
new_composites.append(temp_composites)
offset += increments[i]
return new_composites |
def to_hex(b, sep=''):
"""Converts bytes into a hex string."""
if isinstance(b, int):
return ("00" + hex(b)[2:])[-2:]
elif isinstance(b, (bytes, bytearray)):
s = b.hex()
if len(s) > 2 and sep and len(sep) > 0:
nlen = len(s) + (len(sep) * int(len(s) / 2))
for i in range(2, nlen - len(sep), 2 + len(sep)):
s = s[:i] + sep + s[i:]
return s
else:
raise TypeError("Unable to convert type '%s' to hex string." % type(b).__name__) |
def toFahrenheit(temp):
"""
A function to convert given celsius temperature to fahrenheit.
param number: intger or float
returns fahrenheit temperature
"""
fahrenheit = 1.8 * temp + 32
return fahrenheit |
def key_info_url(key: str) -> str:
"""
Get the URL for the key endpoint with the key parameter filled in.
:param key: The given key.
:return: The corresponding URL.
"""
return f'https://api.hypixel.net/key?key={key}' |
def _listify(x):
"""
If x is not a list, make it a list.
"""
return list(x) if isinstance(x, (list, tuple)) else [x] |
def _serializeOnce_eval(parentUnit, priv):
"""
Decide to serialize only first obj of it's class
:param priv: private data for this function
(first object with class == obj.__class__)
:return: tuple (do serialize this object, next priv, replacement unit)
where priv is private data for this function
(first object with class == obj.__class__)
"""
if priv is None:
priv = parentUnit
serialize = True
replacement = None
# use this :class:`hwt.synthesizer.unit.Unit` instance and store it for later use
else:
# use existing :class:`hwt.synthesizer.unit.Unit` instance
serialize = False
replacement = priv
return serialize, priv, replacement |
def process_test_result(passed, info, is_verbose, exit):
"""
Process and print test results to the console.
"""
# if the environment does not contain necessary programs, exit early.
if passed is False and "merlin: command not found" in info["stderr"]:
print(f"\nMissing from environment:\n\t{info['stderr']}")
return None
elif passed is False:
print("FAIL")
if exit is True:
return None
else:
print("pass")
if info["violated_condition"] is not None:
msg: str = str(info["violated_condition"][0])
condition_id: str = info["violated_condition"][1] + 1
n_conditions: str = info["violated_condition"][2]
print(f"\tCondition {condition_id} of {n_conditions}: {msg}")
if is_verbose is True:
print(f"\tcommand: {info['command']}")
print(f"\telapsed time: {round(info['total_time'], 2)} s")
if info["return_code"] != 0:
print(f"\treturn code: {info['return_code']}")
if info["stderr"] != "":
print(f"\tstderr:\n{info['stderr']}")
return passed |
def msToPlayTime(ms):
""" Convert milliseconds to play time"""
secs = int(ms / 1000)
mins = int(secs / 60)
if mins < 60:
return "{}:{:02d}".format(mins, secs % 60)
else:
hrs = int(mins / 60)
mins = int(mins % 60)
return "{}:{:02d}:{:02d}".format(hrs, mins, secs % 60) |
def get_short_annotations(annotations):
"""
Converts full GATK annotation name to the shortened version
:param annotations:
:return:
"""
# Annotations need to match VCF header
short_name = {'QualByDepth': 'QD',
'FisherStrand': 'FS',
'StrandOddsRatio': 'SOR',
'ReadPosRankSumTest': 'ReadPosRankSum',
'MappingQualityRankSumTest': 'MQRankSum',
'RMSMappingQuality': 'MQ',
'InbreedingCoeff': 'ID'}
short_annotations = []
for annotation in annotations:
if annotation in short_name:
annotation = short_name[annotation]
short_annotations.append(annotation)
return short_annotations |
def doubleStuff(a_list):
""" Return a new list in which contains doubles of the elements in a_list. """
new_list = []
for value in a_list:
new_elem = 2 * value
new_list.append(new_elem)
return new_list |
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (green << 16)| (red << 8) | blue |
def check_syntax(code):
"""Return True if syntax is okay."""
try:
return compile(code, '<string>', 'exec')
except (SyntaxError, TypeError, UnicodeDecodeError):
return False |
def nmap(value, fr=(0, 1), to=(0, 1)):
"""
Map a value from a two-value interval into another two-value interval.
Both intervals are `(0, 1)` by default. Values outside the `fr` interval
are still mapped proportionately.
"""
value = (value - fr[0]) / (fr[1] - fr[0])
return to[0] + value * (to[1] - to[0]) |
def cheap_factor(x):
"""
Cheap prime factors without repetition
>>> cheap_factor(91)
[7, 13]
>>> cheap_factor(12)
[2, 3]
"""
ret = list()
i = 2
while i <= x:
if x % i == 0:
ret.append(i)
while x % i == 0:
x //= i
i += 1
return ret |
def find(item, collection, keys):
"""Find the item in the specified collection whose keys/values match those in the specified item"""
for other_item in collection:
is_match = True
for key in keys:
if other_item[key] != item[key]:
is_match = False
break
if is_match:
return other_item |
def hasShapeType(items, sort):
"""
Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`.
:param shape: :class:`list`
:param sort: type of shape
"""
return any([getattr(item, sort) for item in items]) |
def base2str(value):
"""Produces the binary string representation of an integer value"""
return "{:032b}".format(value) |
def extract_pdf_links(urls):
"""Filters the input list of urls to look for PDF files. Also removes the rest of the path after the filename
Parameters
----------
urls : [string]
A list of urls
Returns
-------
[string]
A filtered list of input urls
"""
pdfs = []
for url in urls:
u, sep, tail = url.lower().partition('.pdf')
url = u + sep
if ".pdf" in url or ".PDF" in url:
pdfs.append(url)
return pdfs |
def _ones_at(*bits):
"""Number with all bits zero except at the given positions ones"""
assert len(bits) == len(set(bits))
value = 0
for b in bits:
value += 1 << b
return value |
def adjust_coordinates(regtype, start, end, strand):
"""
:param regtype:
:param start:
:param end:
:param strand:
:return:
"""
norm = 1 if strand in ['+', '.'] else -1
if regtype == 'reg5p':
if norm > 0:
s, e = start - 1000, start + 500
else:
s, e = end - 500, end + 1000
elif regtype == 'body':
s, e = start, end
elif regtype == 'uprr':
if norm > 0:
s, e = start - 4000, start - 1000
else:
s, e = end + 1000, end + 4000
else:
raise ValueError('Unknown region type: {}'.format(regtype))
return s, e |
def dotProduct(x, y):
"""
Gets the dot product between the two given vectors.
Args:
x (list): First vector.
y (list): Second vector.
Returns:
(float): Dot product result, scalar.
"""
return sum([x[i] * y[i] for i in range(len(x))]) |
def get_auth_header(token):
"""Get authorization header."""
return {"Authorization": f"Bearer {token}"} |
def ignore(name):
"""
Files to ignore when diffing
These are packages that we're already diffing elsewhere,
or files that we expect to be different for every build,
or known problems.
"""
# We're looking at the files that make the images, so no need to search them
if name in ['IMAGES']:
return True
# These are packages of the recovery partition, which we're already diffing
if name in ['SYSTEM/etc/recovery-resource.dat',
'SYSTEM/recovery-from-boot.p']:
return True
# These files are just the BUILD_NUMBER, and will always be different
if name in ['BOOT/RAMDISK/selinux_version',
'RECOVERY/RAMDISK/selinux_version']:
return True
# b/26956807 .odex files are not deterministic
if name.endswith('.odex'):
return True
return False |
def dot(p1, p2):
"""
Dot product for 4-vectors of the form (E, px, py, pz).
Returns: E1*E2 - p1*p2
"""
return p1[0] * p2[0] - p1[1] * p2[1] - p1[2] * p2[2] - p1[3] * p2[3] |
def convert_to_iris(dict_):
"""Change all appearances of ``short_name`` to ``var_name``.
Parameters
----------
dict_ : dict
Dictionary to convert.
Returns
-------
dict
Converted dictionary.
Raises
------
KeyError
:obj:`dict` contains keys``'short_name'`` **and** ``'var_name'``.
"""
dict_ = dict(dict_)
if 'short_name' in dict_:
if 'var_name' in dict_:
raise KeyError(
f"Cannot replace 'short_name' by 'var_name', dictionary "
f"already contains 'var_name' (short_name = "
f"'{dict_['short_name']}', var_name = '{dict_['var_name']}')")
dict_['var_name'] = dict_.pop('short_name')
return dict_ |
def check_if_prime(number):
"""checks if number is prime
Args:
number (int):
Raises:
TypeError: if number of type float
Returns:
[bool]: if number prime returns ,True else returns False
"""
if type(number) == float:
raise TypeError("TypeError: entered float type")
if number > 1 :
for i in range( 2, int(number / 2) + 1 ):
if number % i == 0:
return False
return True
else:
return False |
def thresholdOutput(bInt, yInt):
"""
returns an output of 1 if the intensity is greater than 1% of the sum of the intensities, 0 if not.
"""
# Where does 0.005 come from???
if bInt > 0.005:
bOutput = 1
else:
bOutput = 0
if yInt > 0.005:
yOutput = 1
else:
yOutput = 0
return [bOutput, yOutput] |
def error_to_win(r):
"""Change one's error to other's win"""
flip = lambda c: c == 'x' and 'o' or 'x'
if r[0] == 'error':
return flip(r[1])
elif r[0] == 'ok':
return r[1]
else:
raise RuntimeError("Invalid r[0]: %s", str(r[0])) |
def embed(information:dict) -> str:
"""
input: item:dict ={"url":str,"text":str}
"""
embed_link = information["url"]
block_md =f"""<p><div class="res_emb_block">
<iframe width="640" height="480" src="{embed_link}" frameborder="0" allowfullscreen></iframe>
</div></p>"""
return block_md |
def numericalize(sequence):
"""Convert the dtype of sequence to int"""
return [int(i) for i in sequence] |
def extract_lists (phrase):
"""IF <phrase> = [ITEM1,ITEM2,[LIST1,LIST2]] yields
[ITEM1,ITEM2,LIST1,LIST2]"""
def list_of_lists (phrase):
# TRUE if every element of <phrase> is a list
for x in phrase:
if not isinstance(x,list):
return False
return True
def some_lists (phrase):
# True if some elements of <phrase> are lists.
for x in phrase:
if isinstance(x,list):
return True
return False
def extract (x):
# Recursive function to extract lists.
returnlist = []
if not isinstance(x,list):
returnlist = x
elif not some_lists(x):
returnlist = x
elif not list_of_lists(x):
returnlist = x
else:
# For a list composed of lists
for y in x:
if isinstance(y,list) and not list_of_lists(y):
returnlist.append(extract(y))
else:
for z in y:
# Extracts elements of a list of lists into the containing list
returnlist.append((extract(z)))
return returnlist
return extract(phrase) |
def valid_sample(sample):
"""Check whether a sample is valid.
:param sample: sample to be checked
"""
return (sample is not None and
isinstance(sample, dict) and
len(list(sample.keys())) > 0 and
not sample.get("__bad__", False)) |
def depth(obj):
""" Calculate the depth of a list object obj.
Return 0 if obj is a non-list, or 1 + maximum
depth of elements of obj, a possibly nested
list of objects.
Assume: obj has finite nesting depth
@param int|list[int|list[...]] obj: possibly nested list of objects
@rtype: int
>>> depth(3)
0
>>> depth([])
1
>>> depth([1, 2, 3])
1
>>> depth([1, [2, 3], 4])
2
>>> depth([[], [[]]])
3
"""
if not isinstance(obj, list):
# obj is not a list
return 0
elif obj == []:
return 1
else:
# obj is a list
return 1 + max([depth(elem) for elem in obj]) |
def to_fahrenheit(x):
"""
Returns: x converted to fahrenheit
The value returned has type float.
Parameter x: the temperature in centigrade
Precondition: x is a float
"""
assert type(x) == float, repr(x)+' is not a float'
return 9*x/5.0+32 |
def bbox_for_points(points):
"""Finds bounding box for provided points.
:type points: list or tuple
:param points: sequince of coordinate points
:rtype: list
:return: bounding box
"""
xmin = xmax = points[0][0]
ymin = ymax = points[0][1]
for point in points:
xmin = min(xmin, point[0])
xmax = max(xmax, point[0])
ymin = min(ymin, point[1])
ymax = max(ymax, point[1])
return [xmin, ymin, xmax, ymax] |
def org_enwiki(orgname, url_map):
"""
"""
lst = url_map.get(orgname, [])
for d in lst:
if "enwiki_url" in d:
return d["enwiki_url"]
return "" |
def calculateXVertice(termA, termB):
"""
Calculates the value of the vertice X.
"""
vertice = ((-termB)/(2*termA))
return vertice |
def quote(s, always=False):
"""Adds double-quotes to string if it contains spaces.
:Parameters:
s : str or unicode
String to add double-quotes to.
always : bool
If True, adds quotes even if the input string contains no spaces.
:return: If the given string contains spaces or <always> is True, returns the string enclosed in
double-quotes. Otherwise returns the string unchanged.
:rtype: str or unicode
"""
if always or ' ' in s:
return '"%s"' % s.replace('"', '""') # VisualBasic double-quote escaping.
return s |
def maskbits(x: int, n:int) -> int:
"""Mask x & bitmask(n)"""
if n >= 0:
return x & ((1 << n) - 1)
else:
return x & (-1 << -n) |
def prepare_row(row):
"""Formats CSV so commas within quotes are not split upon."""
row = row.split(",")
st = None
proc_row = []
for i in range(len(row)):
if st is None:
if row[i][0] == "\"" and row[i][-1] != "\"":
st = i
else:
proc_row += [row[i]]
elif row[i][-1] == "\"":
proc_row += [",".join(row[st:i+1])]
st = None
return proc_row |
def dict_from_dotted_key(key, value):
"""
Make a dict from a dotted key::
>>> dict_from_dotted_key('foo.bar.baz', 1)
{'foo': {'bar': {'baz': 1}}}
Args:
key (str): dotted key
value: value
Returns:
dict
"""
d = {}
if '.' not in key:
d[key] = value
return d
components = key.split('.')
last = components.pop()
leaf = d
for c in components:
leaf[c] = {}
leaf = leaf[c]
leaf[last] = value
return d |
def escapeAndJoin(strList):
"""
.. deprecated:: 3.0
Do not use, will be removed in QGIS 4.0
"""
from warnings import warn
warn("processing.escapeAndJoin is deprecated and will be removed in QGIS 4.0", DeprecationWarning)
joined = ''
for s in strList:
if s[0] != '-' and ' ' in s:
escaped = '"' + s.replace('\\', '\\\\').replace('"', '\\"') \
+ '"'
else:
escaped = s
joined += escaped + ' '
return joined.strip() |
def w_fct(stim, color_control):
"""function for word_task, to modulate strength of word reading based on 1-strength of color_naming ControlSignal"""
print('color control: ', color_control)
return stim * (1 - color_control) |
def rayTracingFileName(
site,
telescopeModelName,
sourceDistance,
zenithAngle,
offAxisAngle,
mirrorNumber,
label,
base,
):
"""
File name for files required at the RayTracing class.
Parameters
----------
site: str
South or North.
telescopeModelName: str
LST-1, MST-FlashCam, ...
sourceDistance: float
Source distance (km).
zenithAngle: float
Zenith angle (deg).
offAxisAngle: float
Off-axis angle (deg).
mirrorNumber: int
Mirror number. None if not single mirror case.
label: str
Instance label.
base: str
Photons, stars or log.
Returns
-------
str
File name.
"""
name = "{}-{}-{}-d{:.1f}-za{:.1f}-off{:.3f}".format(
base, site, telescopeModelName, sourceDistance, zenithAngle, offAxisAngle
)
name += "_mirror{}".format(mirrorNumber) if mirrorNumber is not None else ""
name += "_{}".format(label) if label is not None else ""
name += ".log" if base == "log" else ".lis"
return name |
def make_tuple(tuple_like):
"""
Creates a tuple if given ``tuple_like`` value isn't list or tuple
Returns:
tuple or list
"""
tuple_like = (
tuple_like if isinstance(tuple_like, (list, tuple)) else
(tuple_like, tuple_like)
)
return tuple_like |
def neighbor_char(c, r):
"""
This function will return all the neighboring alphabet position by taking
the point we needed and then ignoring the point outside the zone.
----------------------------------------------------------------------------
:param c: (int) the columns index position in the grid(list) (c, r)
:param r: (int) the row index position in the grid(list) (c, r)
:return: neighbor_lst (list) the point around that alphabet and showed by (c, r)
"""
# Create a list to store needed point
neighbor_lst = []
# Create all the point we needed
grid = [(c - 1, r - 1), (c, r - 1), (c + 1, r - 1),
(c - 1, r), (c + 1, r),
(c - 1, r + 1), (c, r + 1), (c + 1, r + 1)]
# Loop over each point and Set the condition to control the point we needed
for i in range(len(grid)):
if grid[i][0] == -1 or grid[i][0] == 4 or grid[i][1] == -1 or grid[i][1] == 4:
pass
else:
neighbor_lst.append(grid[i])
return neighbor_lst |
def is_pandigital(*args):
""" Check numbers is pandigital through 9. """
return '123456789'.startswith(
''.join(sorted(x for arg in args for x in str(arg)))) |
def make_fraud(seed, card, user, latlon):
""" return a fraudulent transaction """
amount = (seed+1)*1000
payload = {"userid": user,
"amount": amount,
"lat": latlon[0],
"lon": latlon[1],
"card": card
}
return payload |
def bits_str(bits):
"""Convert a set into canonical form"""
return ' '.join(sorted(list(bits))) |
def round_up(x, r):
"""
Round x up to the nearest multiple of r.
Always rounds up, even if x is already divisible by r.
"""
return x + r - x % r |
def hash_shard(word):
"""Assign data to servers using Python's built-in hash() function."""
return 'server%d' % (hash(word) % 4) |
def countChoices(matrix, i, j):
"""Gives the possible Numbers at a position on a sudoku grid. """
canPick = [True for _ in range(10)]
# canPick[0] = False
for k in range(9):
canPick[matrix[i][k]] = False
for k in range(9):
canPick[matrix[k][j]] = False
r = i//3
c = j//3
for row in range(r*3,(r+1)*3):
for col in range(c*3,(c+1)*3):
canPick[matrix[row][col]] = False
count = 0
outlist = []
for k in range(1,10):
if canPick[k]:
count+=1
outlist.append(k)
# print(outlist)
return count, outlist
# out=[]
# for num, value in enumerate(canPick):
# if value:
# out.append(num)
# return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.