content stringlengths 42 6.51k |
|---|
def get_unique_elements_as_dict(list_):
"""
Given a list, obtain a dictionary with unique elements as keys and integer as values.
Parameters
----------
list_: list
A generic list of strings.
Returns
-------
dict
Unique elements of the sorted list with assigned integer.
... |
def check_crc(data):
"""
Check CRC Value of received data.
Parameters
----------
data : bytes
received data
Returns
-------
bool
crc correct?
"""
if data != 0:
crc = 0
for i in data[2:81]:
crc += i
return data[81] == (crc & 2... |
def try_get_model_prop(m, key, default=None):
""" The todoist models don't seem to have the `get()` method and throw KeyErrors """
try:
return m[key]
except KeyError:
return default |
def parse_string_time_to_seconds(strtime):
"""
String like 1h 52m 55s to seconds
:param strtime:
:return:
"""
strlist = strtime.strip().split(' ')
secs = float(0)
for strk in strlist:
if strk.endswith('h'):
num = int(float(strk[:-1]))
secs += 60 * 60 * nu... |
def reverse_list(head):
"""
:param head: head
:return: new head
"""
node = head
pre = None
while node:
node.next, pre, node = pre, node, node.next
return pre |
def factorialTrailingZeros(n):
"""
Function to count the number of trailing 0s in a factorial number.
Parameters:
n (int); the number for which the factorial and trailing 0s are to be calculated.
Returns:
trailingZeros (int); the number of 0s in the calculated factorial number.
... |
def list_xor(list1, list2):
"""
returns list1 elements (xor) list2 elements
"""
list3 = []
for i in range(len(list1)):
list3.append(list1[i] ^ list2[i])
return list3 |
def dict_merge(*dicts):
"""
Merge all provided dicts into 1 dict.
"""
merged = {}
for d in dicts:
if not isinstance(d, dict):
raise ValueError('Value should be of dict type')
else:
merged.update(d)
return merged |
def escape(s, quote=None):
"""
SGML/XML escape an unicode object.
"""
s = s.replace("&", "&").replace("<", "<").replace(">", ">")
if not quote:
return s
return s.replace('"', """) |
def add_line_to_csv(file_path, line, linebreak="\n"):
"""Add a line to a CSV file."""
try:
with open(file_path, "a") as file:
file.write(line + linebreak)
return 1
except:
return 0 |
def unflatten_verifications(old_verifications):
""" Convert verifications from v2 to v1 """
new_verifications = {}
for verification in old_verifications:
key = verification['key']
del verification['key']
new_verifications[key] = verification
return new_verifications |
def liouville_avg(n):
"""
Returns the average order of liouville function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return liouville function average
"""
if(n!=int(n) or n<1):
raise ValueError(
"... |
def gf2_rank(rows):
"""
Find rank of a matrix over GF(2)
The rows of the matrix are given as nonnegative integers, thought
of as bit-strings.
This function modifies the input list. Use gf2_rank(rows.copy())
instead of gf2_rank(rows) to avoid modifying rows.
Source: https://stackoverfl... |
def encode(nickname, message):
"""Encodes a message as a comma separated list to be sent to the chat server"""
# Construct the payload
payload = '%s,%s' % (nickname, message)
# Encode the payload as utf-8 byte stream, so it can be sent to the chat server
return str.encode(payload, 'utf-8') |
def fibonacci(n):
"""
- recursie approach
- return the fibonacci number
at the given index
"""
# Check if n is valid
if n < 0:
print("Enter a positive number")
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1)... |
def _flatten(orig):
"""
Converts the contents of list containing strings, lists of strings *(,lists of lists of strings,...)* to a flat
list of strings.
:param orig: the list to flatten
:return: the flattened list
"""
if isinstance(orig, str):
return [orig, ]
elif not hasattr(o... |
def find_in_dict(string, dictionary):
"""
Returns True if the key is in the dictionary, False if not
"""
if string in dictionary:
return True
return False |
def get_total_numbers(items: dict):
"""
return the total number of keys and values per key in `items` as pair (n_keys, n_values).
"""
# Count values of each key.
total_values = 0
for _, v in items.items():
total_values += len(v)
return (len(items), total_values) |
def point(dataset, lon, lat, nchar):
"""This function puts lon,lat and datasetID into a GeoJSON feature"""
geojsonFeature = {
"type": "Feature",
"properties": {"datasetID": dataset, "short_dataset_name": dataset[:nchar]},
"geometry": {"type": "Point", "coordinates": [lon, lat]},
}
... |
def _PrepareContainerMods(mods, private_fn):
"""Prepares a list of container modifications by adding a private data field.
@type mods: list of tuples; (operation, index, parameters)
@param mods: List of modifications
@type private_fn: callable or None
@param private_fn: Callable for constructing a private da... |
def finalize_node(node, nodes, min_cluster_size):
"""Post-process nodes to sort children by descending weight,
get full list of leaves in the sub-tree, and direct links
to the cildren nodes, then recurses to all children.
Nodes with fewer than `min_cluster_size` descendants are collapsed
into a sin... |
def rk4(rho, fun, dt, *args):
"""
Runge-Kutta method
"""
dt2 = dt/2.0
k1 = fun(rho, *args )
k2 = fun(rho + k1*dt2, *args)
k3 = fun(rho + k2*dt2, *args)
k4 = fun(rho + k3*dt, *args)
rho += (k1 + 2*k2 + 2*k3 + k4)/6. * dt
return rho |
def cloudfront_cache_header_behavior(header_behavior):
"""
Property: CacheHeadersConfig.HeaderBehavior
"""
valid_values = ["none", "whitelist"]
if header_behavior not in valid_values:
raise ValueError(
'HeaderBehavior must be one of: "%s"' % (", ".join(valid_values))
)
... |
def transformStandar(value, mean, std):
"""
===========================================================================
Transform numerical input data using
Xnormalized = (X - Xmean) / Xstd
===========================================================================
**Args**:
**Ret... |
def powerlaw_model(energy_gev, k0, index, E0=1.0):
"""
Compute a PowerLaw spectrum
Parameters
----------
- energy_GeV: scalar or vector
- k0 : normalization
- E0 : pivot energy (GeV)
- index : spectral index
Outputs
--------
- spectrum
"""
return k0 * (energy_gev/E... |
def _family_name(set_id, name):
"""
Return the FAM object name corresponding to the unique set id and a list of subset
names
"""
return "FAM" + "_" + str(set_id) + "_" + "_".join(name) |
def create_output(name, mrn, ecg_filename, img_filename, mean_hr_bpm):
"""Interface between GUI and server
This function is called by the GUI command function attached to the "Ok"
button of the GUI. As input, it takes the data entered into the GUI.
It creates an output string that is sent back to the G... |
def dms_to_decimal(degree: int, minute: int, second: float) -> float:
"""Converts a degree-minute-second coordinate to a decimal-degree coordinate."""
return degree + ((minute + (second / 60)) / 60) |
def day_to_full_date(d:str):
"""
Convert a day str 'yyyy-mm-dd' to a full date str 'yyyy-mm-dd 00:00:00'
:param d: 'yyyy-mm-dd'
:return: 'yyyy-mm-dd 00:00:00'
"""
return "{} 00:00:00".format(d) |
def decorator_wrapper(f, *args, **kwargs):
"""Wrapper needed by decorator.decorate to pass through args, kwargs"""
return f(*args, **kwargs) |
def binsearch(array, target):
"""Use binary search to find target in array.
Args:
array: A sequence of data.
target:
If target is callable, it's expected to accept a comparison
function that it uses to check it an element is a match.
If target is... |
def non_binary_search(data, item):
"""Return the position of query if in data."""
for index, val in enumerate(data):
if val == item:
return index
return None |
def __parse_region_from_url(url):
"""Parses the region from the appsync url so we call the correct region regardless of the session or the argument"""
# Example URL: https://xxxxxxx.appsync-api.us-east-2.amazonaws.com/graphql
split = url.split('.')
if 2 < len(split):
return split[2]
return N... |
def extract_properties_values_from_json(data, keys):
"""Extracts properties values from the JSON data.
.. note::
Each of key/value pairs into JSON conventionally referred
to as a "property". More information about this convention follow
`JSON Schema documentation <https://json-schema.o... |
def get_match_quality_here(response):
"""
Returns the quality level from 0 to 1
:param response: dict - The full response from Here
:return: float
"""
try:
return response["Response"]["View"][0]["Result"][0]["Relevance"]
except:
return 0 |
def stringify(sub):
"""Returns python string versions ('' and "") of original substring"""
check_str_s = "'" + sub + "'"
check_str_d = '"' + sub + '"'
return check_str_s, check_str_d |
def acceleration(force, mass):
"""
Calculates the acceleration through force devided by mass.
@param force: force as a vector
@param mass: mass as a numeric value. This should be not 0.
@return: acc the acceleration
>>> acceleration(300, 30)
10.0
"""
#print "mass: ", mass
#p... |
def _Int(s):
"""Try to convert s to an int. If we can't, just return s."""
try:
return int(s)
except ValueError:
assert '.' not in s # dots aren't allowed in individual element names
return s |
def stringify(iterable):
""" Convert tuple containing numbers to string
Input: iterable with numbers as values
Output: tuple with strings as values
"""
return tuple([str(i) for i in iterable]) |
def intDictToStringDict(dictionary):
"""
Converts dictionary keys into strings.
:param dictionary:
:return:
"""
result = {}
for k in dictionary:
result[str(k)] = dictionary[k]
return result |
def evaluate_poly(poly, x):
"""
Computes the polynomial function for a given value x. Returns that value.
Example:
# >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2
# >>> x = -13
# >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2
180339.9
... |
def getFilterQscale(Sw, Sx, Sy):
"""
Sx: threshold_x/127
Sy: threshold_y/127
Qscale = Sw * Sx / Sy
"""
return (Sw * Sx) / Sy |
def testProbDataSumsTo1(y):
"""
prob dist must add to 1
:param y:
:return:
"""
s = sum(y)
print(s)
return s == 1 |
def metadataWhereClause(metadataIds):
"""metadataWhereClause.
Args:
metadataIds:
"""
inClause = ','.join(['%s' for s in metadataIds])
return 'where id in (' + inClause +') ' |
def get_torsscan_info(s):
"""
Returns electronic prog/method/basis as a string and energy as a float in hartree units.
Sample torsscan output
Optimized at : g09/b3lyp/sto-3g
Prog : gaussian
Method: b3lyp
Basis: sto-3g
Energy: -114.179051157 A.U.
Rotational Constants:120.49000, 23.49807, 22.51838 GHz
"... |
def remove_substr(comp_str, str_list):
"""Remove substring."""
ret_list = []
for s in str_list:
if s in comp_str:
continue
ret_list.append(s)
return ret_list |
def _coords_to_region(tile_size, target_mpp, key, coords):
"""Return the necessary tuple that represents a region."""
return (*coords, *tile_size, target_mpp) |
def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
"""
Convert any integer to a Base-N string representation.
Shamelessly stolen from http://stackoverflow.com/a/2267428/1399279
"""
neg = num < 0
num = abs(num)
val = ((num == 0) and numerals[0]) or (baseN(num // b, b, numeral... |
def tags_update(tags_to_add, tags_to_remove):
"""Serializes the given tag updates to a JSON string.
:param set[str] tags_to_add: list of tags
:param str[str] tags_to_remove: list of tags
:return: a dictionary suitable for JSON serialization
:rtype: dict
"""
return {
'add': sorted(... |
def list_compare(original_list, new_list):
""" Compares 'original_list' to 'new_list' and returns two new lists,
the first of which is a list of additions to 'original_list and and the
second is a list of items to be removed from 'original_list'. """
add = []
for item in new_list:
if item n... |
def generate_dest_name(src_repo, name):
""" generate dest repo image name
:param src_repo: one of
- k8s.gcr.io
- gcr.io/ml-pipeline
- quay.io/metallb
- gcr.io/knative-releases/knative.dev/eventing/cmd
:param name: image name
:return dest_image_name
"""
if src_rep... |
def mL2indx(m, L, lmax, lmin=0):
"""convert mL to column index
Used for slicing the Kernel elements K.mLl (see tutorial)
*lmin is always zero. It is merely presented in the args for clarity
Usage example:
m = 0
L = 10
lmax=100
indx = cb.mL2indx(m, L, lmax)
K_mL_slice = kernel.mL... |
def str2bool(v):
"""
Used to parse true/false values from the command line. E.g. "True" -> True
"""
return v.lower() in ("yes", "true", "t", "1") |
def get_rank(workers, scores):
"""
spam score -> rank
"""
a = zip(scores, workers)
b = sorted(a)
dic = {}
i = 0
for s, w in b:
dic[w] = i
i+= 1
return dic |
def get_route_ids(routes_data: dict) -> list:
"""Return list of route ids from routes resp.json() data."""
route_ids = list()
for route in routes_data['Routes']:
route_ids.append(route['RouteID'])
return route_ids |
def check_knot_vector(degree, knot_vector, num_ctrlpts):
""" Checks if the input knot vector follows the mathematical rules.
:param degree: degree of the curve or the surface
:type degree: int
:param knot_vector: knot vector to be checked
:type knot_vector: list, tuple
:param num_ctrlpts: numbe... |
def _audiocomp(P:dict) -> list:
"""select audio codec"""
return ['-c:a','aac','-b:a','160k','-ar','44100' ] |
def createSpiral(number):
"""
Create a spiral position array.
"""
number = number * number
positions = []
if (number > 1):
# spiral outwards
tile_x = 0.0
tile_y = 0.0
tile_count = 1
spiral_count = 1
while(tile_count < number):
i = 0
... |
def volCuboid(length: float, breadth: float, height: float) -> float:
"""Finds volume of a cuboid"""
volume: float = length * breadth * height
return volume |
def get_shortest_api(api_list):
"""
find the shortest api name (suggested name) in list.
Problems:
1. fuild - if there is any apis don't contain 'fluid' in name, use them.
2. core vs core_avx - using the 'core'.
"""
if len(api_list) == 1:
return api_list[0]
# try to find shortes... |
def encode_tuple(tuple_to_encode):
"""Turn size tuple into string. """
return '%s/%s' % (tuple_to_encode[0], tuple_to_encode[1]) |
def form_assignment_string_from_dict(adict):
"""
Generate a parameter-equals-value string from the given dictionary. The
generated string has a leading blank.
"""
result = ""
for aparameter in adict.keys():
result += " {}={}".format(aparameter, adict[aparameter])
return resul... |
def _isqrt(n):
"""Integer square root of n > 0
>>> _isqrt(1024**2)
1024
>>> _isqrt(10)
3
"""
assert n >= 0
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
def translate_db2api(namespace, alias):
"""
>>> translate_db2api("VMC", "GS_1234")
[('sha512t24u', '1234'), ('ga4gh', 'SQ.1234')]
"""
if namespace == "NCBI":
return [("refseq", alias)]
if namespace == "Ensembl":
return [("ensembl", alias)]
if namespace == "LRG":
ret... |
def normalizeTransformationScale(value):
"""
Normalizes transformation scale.
* **value** must be an :ref:`type-int-float`, ``tuple`` or ``list``.
* If **value** is a ``tuple`` or ``list``, it must have exactly two items.
These items must be instances of :ref:`type-int-float`.
* Returned valu... |
def strip_paths(paths):
"""
Remove edges which are sequentially repeated in a path, e.g. [a, b, c, d, c, d, e, f] -> [a, b, c, d, e, f]
"""
res_all = []
for path in paths:
res = []
for node in path:
if len(res) < 2:
res.append(node)
continu... |
def _maybe_add_password(command, password):
"""
Add sudo password to command if required. Else NOOP.
in: sudo apt-get install
out: echo 'password' | sudo -S apt-get install
"""
if not password or 'sudo' not in command: # or 'sudo -S' in command:
return command
# Handle commands tha... |
def parse_misplaced_character_inputs(misplaced_argument):
"""
example input from command line: __r__,___ac
this input would be used to show that two guesses had misplaced characters. The first guess has a misplaced
character at index 2, with a value of r. The second guess has two misplaced characters at... |
def convert_cookie_str(_str):
"""
convert cookie str to dict
"""
_list = [i.strip() for i in _str.split(';')]
cookie_dict = dict()
for i in _list:
k, v = i.split('=', 1)
cookie_dict[k] = v
return cookie_dict |
def read_last(file_name, n_lines=1):
"""
Reads the last line of a file.
Parameters
----------
:param file_name: string
Complete path of the file that you would like read.
:return last_line: string
Last line of the input file.
"""
try:
with open(file_name, mode='r... |
def ABCDFrequencyList_to_ZFrequencyList(ABCD_frequency_list):
""" Converts ABCD parameters into z-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,Z11,Z12,Z21,Z22],...],
inverse of ZFrequencyList_to_ABCDFrequencyList
"""
z_frequency_list=[]
for... |
def StretchContrast(pixlist, minmin=0, maxmax=0xff):
""" Stretch the current image row to the maximum dynamic range with
minmin mapped to black(0x00) and maxmax mapped to white(0xff) and
all other pixel values stretched accordingly."""
if minmin < 0: minmin = 0 # pixel minimum is 0
if maxm... |
def get_cmd_name(name=__name__):
"""Get command name from __name__ within a file"""
return name.split('.')[-1] |
def is_cell_markdown(cell):
"""
Is the ipynb cell Markdown?
"""
return cell['cell_type'].strip().lower().startswith('markdown') |
def sub(A,B):
"""
matrix subtraction functions which returns resultant matrix after subtracting two matrices
"""
n=len(A)
output=[]
result=[]
for i in range(n):
for j in range(n):
result.append(A[i][j]-B[i][j])
output.append(result)
result=[]
return o... |
def getSegsInMap(segMap, corpus):
"""Returns a list of the full text segments in the corpus indicated by the segmap"""
textSegs = []
for i in range(0, len(segMap)):
textSegs.append(corpus[segMap[i]])
return textSegs |
def non_overlapping_claims(claims):
""" Return a list of all claims that don't overlap with others. """
unique_claims = set()
non_unique_claims = set()
for v in claims.values():
if len(v) == 1:
unique_claims = unique_claims.union(v)
else:
non_unique_claims = non_u... |
def update_annotations(annotations, left_shifts):
"""Update deidentified annotations with appropriate left shifts
"""
deidentified_annotations = \
{annotation_type: [] for annotation_type in annotations.keys()}
for annotation_type, annotation_set in annotations.items():
for annotation in... |
def average_even_is_average_odd(hand):
"""
:param hand: list - cards in hand.
:return: bool - are even and odd averages equal?
"""
even_count = 0
even_average = 0
even_sum = 0
for i in range(0, len(hand), 2):
even_count += 1
even_sum += hand[i]
even_average = even_... |
def safe_split(indata, sepchar='|'):
"""
split string safely
"""
try:
return filter(lambda x: len(x.strip()), indata.split(sepchar))
except:
return [] |
def _normalized_coerce_fn(r):
"""
:rtype: str
"""
return r.lower().strip() |
def _get_cols_to_format(show_inference, confidence_intervals):
"""Get the list of names of columns that need to be formatted.
By default, formatting is applied to parameter values. If inference values
need to displayed, adds confidence intervals or standard erros to the list.
"""
cols = ["value"]... |
def multiply(*args):
"""
Helper function which multiplies the all numbers that are delivered in the function call
:param args: numbers
:return: product of all numbers
"""
product = 1
for arg in args:
product *= arg
return product |
def ngrams(word, n):
"""Creates n-grams for a string, returning a list.
:param word: str - A word or string to ngram.
:param n: - n-gram length
:returns: list of strings
"""
ans = []
word = word.split(' ')
for i in range(len(word) - n + 1):
ans.append(word[i:i + n])
return... |
def indexValue(i_array, target):
"""
Function Docstring
"""
if(len(i_array) <= 2):
return False
else:
for i in range(len(i_array)):
first_index = i
j = i + 1
for j in range(len(i_array)):
if i_array[i] + i_array[j] == target:
... |
def island_perimeter(grid):
"""returns the perimeter of the island described in grid"""
p = 0
for i in range(0, len(grid), 1):
for j in range(0, len(grid[0]), 1):
if grid[i][j] == 1:
p = p + 4
if j - 1 >= 0 and grid[i][j - 1] == 1:
p = ... |
def all_primes(limit):
""" Returns a list of primes < limit """
sieve = [True] * limit
for i in range(3, int(limit ** 0.5) + 1, 2):
if sieve[i]:
sieve[i * i::2 * i] = [False] * ((limit - i * i - 1) // (2 * i) + 1)
return [2] + [i for i in range(3, limit, 2) if sieve[i]] |
def get_python_exec(py_num: float) -> str:
""" Get python executable
Args:
py_num(float): Python version X.Y
Returns:
str: python executable
"""
if py_num < 3:
py_str = ""
else:
py_str = "3"
return f"python{py_str}" |
def te_exp_minus1(posy, nterm):
"""Taylor expansion of e^{posy} - 1
Arguments
---------
posy : gpkit.Posynomial
Variable or expression to exponentiate
nterm : int
Number of non-constant terms in resulting Taylor expansion
Returns
-------
gpkit.Posynomial
Taylor ... |
def remove_duplicates(iterable):
"""Removes duplicates of an iterable without meddling with the order"""
seen = set()
seen_add = seen.add # for efficiency, local variable avoids check of binds
return [x for x in iterable if not (x in seen or seen_add(x))] |
def mm_as_m(mm_value):
"""Turn a given mm value into a m value."""
if mm_value == 'None':
return None
return float(mm_value) / 1000 |
def __find(element, JSON):
"""
To find the content in elasticsearch's hits based on path in element.
Arguments:
- element: a path to the content, e.g. _source.item.keywords.keyword
- JSON: a dictionary as a result of elasticsearch query
"""
try:
paths = element.split(".")
... |
def positive_int_to_str(value):
""" Convert a PositiveInt to a string representation to display
in the text box.
"""
if value is None:
return ""
else:
return str(value) |
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return "{} {}{}".format(round(bytes), unit, suffix)
by... |
def getQuarter(side, point):
"""
Given a 2d point, returns the corresponding quarter ID.
The path of the robot is split in 4 segments, each segment corresponds
to one edge of the square. Since the robot is not exactly on the edge, we
need a way to map any point to one of the 4 edges. To do this we ... |
def yellowness_blueness_response(C, e_s, N_c, N_cb, F_t):
"""
Returns the yellowness / blueness response :math:`M_{yb}`.
Parameters
----------
C : array_like
Colour difference signals :math:`C`.
e_s : numeric
Eccentricity factor :math:`e_s`.
N_c : numeric
Chromatic ... |
def get_hue_fg_colour(h, s, v):
"""Returns the best foreground colour for a given background colour (black or white.)"""
if s > 0.6:
if h > 20 and h <= 200:
return "black"
elif s <= 0.6:
if v > 0.8:
return "black"
return "white" |
def _standardise_proc_param_keys(key: str) -> str:
"""Convert to lowercase, replace any spaces with underscore."""
return key.lower().replace(" ", "_") |
def remove_badges(text: str) -> str:
""" Remove Github badges.
:param text: Original text.
:return: Text with Github badges removed.
"""
new_text = "\n".join((line for line in text.splitlines() if "![" not in line))
return new_text |
def verify_heart_rate_info(in_dict):
"""Verifies post request was made with correct format
The input dictionary must have the appropriate data keys
and types, or be convertible to correct types, to be added
to the patient database.
Args:
in_dict (dict): input with patient ID and heart rate... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.