content stringlengths 42 6.51k |
|---|
def utm_zone_to_epsg(zone):
"""
Convert UTM zone string to EPSG code.
56S -> 32756
55N -> 32655
"""
if len(zone) < 2:
raise ValueError(f'Not a valid zone: "{zone}", expect <int: 1-60><str:S|N>')
offset = dict(S=32700, N=32600).get(zone[-1].upper())
if offset is None:
r... |
def _patsplit(pattern, default):
"""Split a string into the optional pattern kind prefix and the actual
pattern."""
if ':' in pattern:
kind, pat = pattern.split(':', 1)
if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre',
'listfile', 'listfile0', 'set', 'inclu... |
def disease_descriptors(civic_did2, civic_did15, civic_did2950):
"""Create test fixture for disease descriptors."""
return [civic_did2, civic_did15, civic_did2950] |
def quote_item(item, pre='', post=''):
"""Format an string item with quotes.
"""
post = post or pre
return f'{pre}{item}{post}' |
def add_numbers(file: list, tel_numbers: set) -> set:
"""
Given a file adds all available numbers into a set
:param file: file containing telephone numbers
:param tel_numbers: variable used to contain the telephone numbers
:return: tel_numbers with file numbers extracted
"""
for column in [0... |
def NX(lengths, fraction):
""" Calculates the N50 for a given set of lengths
"""
lengths = sorted(lengths, reverse=True)
tot_length = sum(lengths)
cum_length = 0
for length in lengths:
cum_length += length
if cum_length >= fraction*tot_length:
return length |
def is_valid_output(ext):
""" Checks if output file format is compatible with Open Babel """
formats = ["ent", "fa", "fasta", "gro", "inp", "mcif", "mdl", "mmcif", "mol", "mol2", "pdb", "pdbqt", "png", "sdf", "smi", "smiles", "txt"]
return ext in formats |
def friend_second_besties(individual, bestie_dict):
"""generate the set of (strictly) second-order friends for
`individual`, based on the contents of `bestie_dict`"""
# extract out friends of friends for each individual in
# `individual_list`, by finding friends of each individual,
# and friends o... |
def xor_list(prim_list, sec_list):
"""
Returns the XOR of bits from the primary and secondary lists.
"""
ret_list = []
for (x_val, y_val) in zip(prim_list, sec_list):
ret_list.append(x_val ^ y_val)
return ret_list |
def flatten_dic(dic):
"""
Flatten dictionnary with nested keys into a single level : usable in a dataframe
Args:
dic -- a dictionnary
Returns:
out -- the flatenned dictionnary (df(out) is a Series)
"""
out = {}
def flatten(x, name=""):
"""
Rec... |
def fib2(n):
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a+b
return result |
def parse_flags(raw_flags):
"""Return a list of flags.
Concatenated flags will be split into individual flags
(eg. '-la' -> '-l', '-a'), but the concatenated flag will also be
returned, as some command use single dash names (e.g `clang` has
flags like "-nostdinc") and some even mix both.
"""
... |
def factorial(n):
"""
Computes the factorial using recursion
"""
if n == 1:
return 1
else:
return n * factorial(n-1) |
def house_url(path):
"""
Joins relative house url paths with stem or returns url if stem present.
:param path: String path to format.
:return: Full house URL.
"""
stem = "https://house.mo.gov"
# Replace insecure with secure
if "http://" in path:
path = path.replace("http://", "ht... |
def calcsurface_f(c1, c2):
"""
Helperfunction that calculates the desired surface for two xy-coordinates
"""
# step 1: calculate intersection (xs, ys) of straight line through coordinates with identity line (if slope (a) = 1, there is no intersection and surface of this parrellogram is equal to deltaY *... |
def get_ether_vendor(mac, lookup_path='nmap-mac-prefixes.txt'):
"""
Takes a MAC address and looks up and returns the vendor for it.
"""
mac = ''.join(mac.split(':'))[:6].upper()
try:
with open(lookup_path, 'r') as f:
for line in f:
if line.startswith(mac):
... |
def _copy_params(request, params=None):
"""
Return a copy of the given request's params.
If the request contains an empty 'q' param then it is omitted from the
returned copy of the params, to avoid redirecting the browser to a URL with
an empty trailing ?q=
"""
if params is None:
p... |
def decode_time(milliseconds):
"""Converts a time in milliseconds into a string with hours:minutes,"""
mins = int(milliseconds / (1000 * 60) % 60)
hrs = int(milliseconds / (1000 * 60 * 60) % 24)
return "{h:0>2}:{m:0>2}".format(h=hrs, m=mins) |
def clean_strings(lst):
"""Helper function to clean a list of string values for adding to NWB.
Parameters
----------
lst : list
A list of (mostly) strings to be prepped for adding to NWB.
Returns
-------
list of str
Cleaned list.
Notes
-----
Each element is che... |
def rpm(count, _, nb_read):
""" Return rpm value """
return (count / nb_read) * 10**6 |
def checkDebugOption(debugOptions):
"""
function to set the default value for debugOptions and turn it from
a string into a boolean value
Args:
debugOptions: string representation of boolean value for debug flag
Returns: boolean value for debug flag
"""
if debugOptions ... |
def unbundleSizeAndRest(sizeAndRestBundle: int):
"""
Get the size and the rest of the cipher base from a bundled integer
:param sizeAndRestBundle: a bundled number containing the size and the rest of the cipher
:return: the size and the rest as a tuple
"""
if sizeAndRestBundle > 0xffffffff:
... |
def get_range(value, start):
"""
Filter - returns a list containing range made from given value
Usage (in template):
<ul>{% for i in 3|get_range %}
<li>{{ i }}. Do something</li>
{% endfor %}</ul>
Results with the HTML:
<ul>
<li>0. Do something</li>
... |
def n2es(x):
"""None/Null to Empty String
"""
if not x:
return ""
return x |
def extract_key_values(array_value, separators=(';', ',', ':'), **kwargs):
"""Serialize array of objects with simple key-values
"""
items_sep, fields_sep, keys_sep = separators
return items_sep.join(fields_sep.join(keys_sep.join(x) for x in sorted(it.items()))
for it in array_v... |
def canUnlockAll(boxes):
""" canUnlockAll: figures out if all boxes can be opened """
b_len = len(boxes)
checked = [False for i in range(b_len)]
checked[0] = True
stack = [0]
while len(stack):
bx = stack.pop(0)
for b in boxes[bx]:
if isinstance(b, int) and b >= 0 and ... |
def hex_to_tcp_state(hex):
"""
For converting tcp state hex codes to human readable strings.
:param hex: TCP status hex code (as a string)
:return: String containing the human readable state
"""
states = {
'01': 'TCP_ESTABLISHED',
'02': 'TCP_SYN_SENT',
'03': 'TCP_SYN_RECV... |
def format_time_interval(seconds):
"""Format a time interval given in seconds to a readable value, e.g. \"5 minutes, 37 seconds\"."""
periods = (
('year', 60*60*24*365),
('month', 60*60*24*30),
('day', 60*60*24),
('hour', 60*60),
('minute', ... |
def dbytes_to_int(h):
""" converts bytes represenation of hash to int, without conversion """
return int.from_bytes(h,"big") |
def modifyExecutedFiles(executed_files):
"""
Modifying ansible playbook names to make them uniform across all SDK's
"""
exe = []
for executed_file in executed_files:
executed_file = executed_file.replace('.yml', '').replace('oneview_', '').replace('_facts', '')
executed_file = execut... |
def sqrt(number):
"""Returns the square root of the specified number as an int, rounded down"""
assert number >= 0
offset = 1
while offset ** 2 <= number:
offset *= 2
count = 0
while offset > 0:
if (count + offset) ** 2 <= number:
count += offset
offset //= 2
... |
def _parse_arguments(argstring):
"""
Parses argstring from nginx -V
:param argstring: configure string
:return: {} of parsed string
"""
arguments = {}
current_key = None
current_value = None
for part in argstring.split(' --'):
if '=' in part:
# next part of com... |
def string_str_to_str(string_str_rep):
"""
Return string from given string representation of string
Parameters
----------
string_str_rep : str
"'str'"
Examples
--------
>>> string_str_to_str("")
''
>>> string_str_to_str('test')
'test'
>>> string_str_to_str("'tes... |
def _get_range_tuples(data):
"""Split the ranges field from a comma separated list of start-end to a
real list of (start, end) tuples.
"""
ranges = []
for r in data['ranges'].split(',') or []:
start, end = r.split('-')
ranges.append((start, end))
return ranges |
def generateName(nodeName: str, instId: int):
"""
Create and return the name for a replica using its nodeName and
instanceId.
Ex: Alpha:1
"""
if isinstance(nodeName, str):
# Because sometimes it is bytes (why?)
if ":" in nodeName:
# Because in some cases (for reques... |
def watch_url(video_id):
"""Construct a sanitized YouTube watch url, given a video id.
:param str video_id:
A YouTube video identifier.
:rtype: str
:returns:
Sanitized YouTube watch url.
"""
return 'https://youtube.com/watch?v=' + video_id |
def histogram(values, mode=0, bin_function=None):
"""Return a list of (value, count) pairs, summarizing the input values.
Sorted by increasing value, or if mode=1, by decreasing count.
If bin_function is given, map it over values first."""
if bin_function: values = map(bin_function, values)
bins = {... |
def get_stat_name(stat):
"""Returns the stat name from an integer"""
if stat == 1:
return "armor"
elif stat == 2:
return "attackdamage"
elif stat == 3:
return "movespeed"
elif stat == 4:
return "magicresist"
elif stat == 5:
return "movespeed"
elif stat... |
def rae(*args):
"""
:param args: [actual, predicted]
:return: MRE
"""
return abs(args[0] - args[1]) / args[0] |
def remove_value_from_dict(dictionary:dict,value):
"""
takes a dict and removes a value
"""
a = dict(dictionary)
for val in dictionary:
if val == value:
del a[val]
return a |
def make_bbh(hp,hc,fs,ra,dec,psi,det,ifos,event_time):
""" Turns hplus and hcross into a detector output
applies antenna response and
and applies correct time delays to each detector
Parameters
----------
hp:
h-plus version of GW waveform
hc:
h-cross version of GW waveform
... |
def lambda_foo(itr,
start_itrs,
warmup_itrs,
mul_lr=1):
"""
:param itr: itr >= start_itrs
:param start_itrs:
:param warmup_itrs:
:param mul_lr:
:return:
"""
if itr < start_itrs:
return mul_lr
else:
if itr < start_itrs + warmup_itrs:
return (i... |
def wrapTheta(theta):
""" Wrap an angle from the real line onto (-180, 180].
Parameters
----------
theta : float
Angle, in degrees.
Returns
-------
theta_wrapped : float
The input, projected into (-180, 180].
"""
return (theta + 90) % 360 - 90 |
def is_relative_path(s):
"""
Return whether the path given in argument is relative or not.
"""
tmp = s.replace(u"\\", u"/")
return tmp.startswith(u"../") or tmp.startswith(u"~/") or tmp.startswith(u"./") |
def lr5(step: int, base_lr: float) -> float:
"""LR5."""
lr = base_lr
_lr = lr * 0.9 ** (step // 100)
return max(_lr, 1e-6) |
def calc_incidence(cases, pop):
"""Calculates the incidence value with the population and cases specified."""
return cases / pop * 100000 |
def _Join(array, delim=''):
"""
func join(items Array[Str]) Str ...
"""
# default is not ' '?
return delim.join(array) |
def indent_length(line_str):
"""Returns the indent length of a given string as an integer."""
return len(line_str) - len(line_str.lstrip()) |
def _twos_comp(val, bits):
""" Convert an unsigned integer in 2's compliment form of the specified bit
length to its signed integer value and return it.
"""
if val & (1 << (bits -1)) != 0:
return val -(1 << bits)
return val |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\
'*?????*', '*?????*', '*2*1***'])
False
>... |
def fact_rec(n):
"""Assumes n an int > 0
Returns n!"""
if n == 1:
return n
else:
return n*fact_rec(n - 1) |
def inBytes(gb):
"""Convert bytes to gigabytes"""
return gb * 1024. ** 3 |
def levelize_strength_or_aggregation(to_levelize, max_levels, max_coarse):
"""Turn parameter into a list per level.
Helper function to preprocess the strength and aggregation parameters
passed to smoothed_aggregation_solver and rootnode_solver.
Parameters
----------
to_levelize : {string, tupl... |
def num_same_elements(arr_1, arr_2):
"""Counts the number of same elements in a given lists
Args:
arr_1(list): first array
arr_2(list): second array
Returns:
same elements(int): number of same elements
"""
result = set(arr_1).intersection(set(arr_2))
return len(result) |
def is_str_float(i):
"""Check if a string can be converted into a float"""
try: float(i); return True
except ValueError: return False |
def arnonA_mono_to_string(mono, latex=False, p=2):
"""
String representation of element of Arnon's A basis.
This is used by the _repr_ and _latex_ methods.
INPUT:
- ``mono`` - tuple of pairs of non-negative integers
(m,k) with `m >= k`
- ``latex`` - boolean (optional, default False),... |
def formsetsort(formset, arg):
"""
Takes a list of formset dicts, returns that list sorted by the sortable field.
"""
if arg:
sorted_list = []
for item in formset:
position = item.form[arg].data
if position and position != "-1":
sorted_list.append(... |
def find_max(nums):
"""
>>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):
... find_max(nums) == max(nums)
True
True
True
True
"""
max_num = nums[0]
for x in nums:
if x > max_num:
max_num = x
return max_num |
def get_decimal(f, aprox=2):
"""Gets the decimal part of a float
Args:
f (float): Real number to get the decimal part from
aprox (int)(optional): Number of decimal digits, default is 2.
Returns:
float: Decimal part of f
"""
f = round((f - int(f)), aprox)
ret... |
def parse_int_list(range_string, delim=',', range_delim='-'):
"""
Returns a sorted list of positive integers based on
*range_string*. Reverse of :func:`format_int_list`.
Args:
range_string (str):
String of comma separated positive integers or ranges
(e.g. '1,2,4-6,8'). T... |
def get_preview_html(template, interactive=False):
"""get_preview_html
Parameters
----------
template : {{_type_}}
Returns
-------
Example
-------
"""
text = template['text']
if interactive:
html = '<span style="background-color:#c8f442" class="cursor-pointer"... |
def str2mdown(text):
"""
Converts the given text string to Markdown .
:param text: The string to be converted.
:return: The Markdown converted text.
"""
if text is None:
return None
else:
return text.replace("-", "\\-") \
.replace("!", "\\!") \
.repl... |
def RPL_AWAY(sender, receipient, message):
""" Reply Code 301 """
return "<" + sender + ">: " + message |
def _step(dim, ref, radius):
"""
Helper: returns range object of axis indices for a search window.
:param int dim: Total length of the grid dimension
:param int ref: The desired number of steps
:param int radius: The number of cells from the centre of the chip eg.
(chipsize / 2)
:retur... |
def is_even(number=0):
""" Checks if a given number is even or not """
print('Number = ', number)
return (number % 2 == 0) |
def wrap_space_around(text):
"""Wrap one additional space around text if it is not already present.
Args:
text (str): Text
Returns:
str: Text with extra spaces around it.
"""
if text[0] != " " and text[-1] != " ":
return " " + text + " "
elif text[0] != " ":
ret... |
def list_search(to_search, key, value):
"""
Given a list of dictionaries, returns the dictionary that matches the given key value pair
"""
result = [element for element in to_search if element[key] == value]
if result:
return result[0]
else:
raise KeyError |
def _val_subtract(val1, val2, dict_subtractor, list_subtractor):
"""
Find the difference between two container types
Returns:
The difference between the values as defined by list_subtractor() and
dict_subtractor() if both values are the same container type.
None if val1 == val2
val1 if ty... |
def dict_select(d, keys):
"""
Return a dict only with keys in the list of keys.
example:
clust_kw = 'min_density min_size haircut penalty'.split()
clust_kwargs = ut.dict_select(kwargs, clust_kw)
"""
return dict([(k,d[k]) for k in keys if k in d]) |
def _safe_restore(data, rep):
""" Safely restore pickled data, resorting to representation on fail """
import pickle
try:
return pickle.loads(data)
except Exception:
return rep |
def webstring(value):
""" Convert a Python dictionary to a web string where the values are in the
format of 'foo=bar&up=down'. This is necessary when processing needs to be done
on a dictionary but the values need to be passed to urllib2 as POST data. """
data = ""
for key in value:
new... |
def Problem_f(name, input, output):
"""
:param name: The "name" of this Problem
:param input: The "input" of this Problem
:param output: The "output" of this Problem
"""
res = '\\begin{example}\n'
if name:
res += '[' + name + ']\n'
res += 'Input: ' + input + '\n'
res += 'Outp... |
def _op_seq_str_suffix(line_labels, occurrence_id):
""" The suffix (after the first "@") of a circuit's string rep"""
if occurrence_id is None:
return "" if line_labels is None or line_labels == ('*',) else \
"@(" + ','.join(map(str, line_labels)) + ")"
else:
return "@()@" + str(... |
def revcomp_str(seq):
"""
Returns the reverse complement of a `str` nucleotide sequence.
Parameters
----------
+ seq `str` nucleotide sequence
"""
comp = str.maketrans('ACGTRYMKWSBDHV', 'TGCAYRKMWSVHDB')
anti = seq.translate(comp)[::-1]
return anti |
def is_float(value):
""" Returns whether given values is float """
try:
float(value)
return True
except Exception:
return False |
def keyfilter_json(json_object, filter_func, recurse=True):
"""
Filter arbitrary JSON structure by filter_func, recursing into the structure if necessary
:param json_object:
:param filter_func: a function to apply to each key found in json_object
:param recurse: True to look recurse into lists and d... |
def _find_year(year, year_list):
"""
Internal helper function, not exported. Returns the first
year in the list greater or equal to the year
:param year: year of interest
:param year_list:list: list of years, likely from a yaml census list
:return: first year greater than or equal to "year" in "... |
def validation_errors_to_error_messages(validation_errors):
"""
Simple function that turns the WTForms validation errors into a simple list
"""
errorMessages = []
for field in validation_errors:
for error in validation_errors[field]:
errorMessages.append(f"{error}")
return er... |
def ipv4_cidr_to_netmask(bits):
"""Convert CIDR bits to netmask """
netmask = ''
for i in range(4):
if i:
netmask += '.'
if bits >= 8:
netmask += '%d' % (2**8-1)
bits -= 8
else:
netmask += '%d' % (256-2**(8-bits))
bits = 0
... |
def attributes(attrs):
"""Returns an attribute list, constructed from the
dictionary attrs.
"""
attrs = attrs or {}
ident = attrs.get("id","")
classes = attrs.get("classes",[])
keyvals = [[x,attrs[x]] for x in attrs if (x != "classes" and x != "id")]
return [ident, classes, keyvals] |
def is_palindrome_v2(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
n = len(s)
return s[:n//2] == s[n-1:n-n//2-1:-1] |
def bit(value, position, length=1):
"""
Return bit of number value at position
Position starts from 0 (LSB)
:param value:
:param position:
:param length:
:return:
"""
binary = bin(value)[2:]
size = len(binary) - 1
if position > size:
return 0
else:
return ... |
def word_tokenizer(text):
"""
Dataset is already tokenized
"""
return text.split(" ") |
def get_artist_tags(connect, artist_mbid, maxtags=20):
"""
Get the musicbrainz tags and tag count given a musicbrainz
artist. Returns two list of length max 'maxtags'
Always return two lists, eventually empty
"""
if artist_mbid is None or artist_mbid == '':
return [],[]
# find all ta... |
def get_geocoord(coord, min_coord, max_coord, size):
"""Transform abscissa from pixel to geographical coordinate
For horizontal operations, 'min_coord', 'max_coord' and 'size' refer
respectively to west and east coordinates and image width.
For vertical operations, 'min_coord', 'max_coord' and 'size' ... |
def validate_password(password):
"""A simple password validator
"""
length = len(password) > 7
lower_case = any(c.islower() for c in password)
upper_case = any(c.isupper() for c in password)
digit = any(c.isdigit() for c in password)
return length and lower_case and upper_case and digit |
def n_tuple_name(n):
"""Return the proper name of an n-tuple for given n."""
names = {1: 'single', 2: 'pair', 3: 'triple', 4: 'quad'}
return names.get(n, '%d-tuple' % n) |
def _OsStatus(status, diagnose):
"""Beautifier function for OS status.
@type status: boolean
@param status: is the OS valid
@type diagnose: string
@param diagnose: the error message for invalid OSes
@rtype: string
@return: a formatted status
"""
if status:
return "valid"
else:
return "inva... |
def calc_point_squre_dist(point_a, point_b):
"""Calculate distance between two marking points."""
distx = point_a[0] - point_b[0]
disty = point_a[1] - point_b[1]
return distx ** 2 + disty ** 2 |
def FVIF(i,n,m=1):
"""
interest
years
payments per year
"""
FVIF = (1 + i/m)**(m*n)
return FVIF |
def buildranges(amin, amax, rangeval):
"""Retunrs a list of tuples, with the string-range first and then
the numbers in a tuple: [('990-1020', (990, 1020)), ('1020-1050', (1020, 1050))] """
r = []
allvalues = range(amin, amax, rangeval)
for index, item in enumerate(allvalues):
if (index + ... |
def track_path(actions, path=None):
"""
<Purpose>
Given a list of actions, it tracks all the activity on files. If a path is
given, only the activity on that path will be tracked. Otherwise the
activity on all paths will be tracked.
<Arguments>
actions: A list of actions from a parsed... |
def mac_hex(number):
"""Convert integer to hexadecimal for incrementing MAC addresses.
:param number: Integer number less than 100.
:type number: int
:returns: 2-digit hexadecimal representation of the input number.
:rtype: str
"""
temp = hex(number)[2:]
if number < 16:
temp =... |
def near(n: int, *args) -> str:
"""
Build the filter to find articles containing words that occur within
`n` words of each other.
eg. near(5, "airline", "climate") finds articles containing both
"airline" and "climate" within 5 words.
"""
if len(args) < 2:
raise ValueError("At least... |
def create_matrix(length, height):
""" Creates a matrix to store data in using a certain length and height. """
matrix = [[0 for x in range(length)] for y in range(height)]
return matrix |
def sanitize(string):
""" Turns '-' into '_' for accumulo table names
"""
return string.replace('-', '_') |
def build_type_flag(compiler, build_type):
"""
returns flags specific to the build type (Debug, Release, etc.)
(-s, -g, /Zi, etc.)
"""
if not compiler or not build_type:
return ""
if str(compiler) == 'Visual Studio':
if build_type == 'Debug':
return '-Zi'
else:
... |
def fv_annuity(n,c,r):
"""
Objective: estimate future value of an annuity
n : number of payments
c : payment amount
r : discount
formula : c/r*((1+r)**n-1)
e.g.,
>>>fv_annuity(2,100,0.1)
210.0000000000002
"""
return c/r*((1+r)**n-1) |
def nott(n):
"""Negative One To The n, where n is an integer."""
return 1 - 2*(n & 1) |
def jaccard(ground, found):
"""Cardinality of set intersection / cardinality of set union."""
ground = set(ground)
return len(ground.intersection(found))/float(len(ground.union(found))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.