content stringlengths 42 6.51k |
|---|
def is_marked(name):
"""Returns True if the input file contains either a header or a Quran quote
The file name is used to determine whether the file contains a header or a
Quran quote.
"""
if 'header' in name:
return True
if 'QQuote' in name or 'HQuote' in name:
return True
... |
def get_1st_ck_line_from_line( line ):
"""
A check line may contain more than 1 check.
Here we get only the info(line aka string) from the 1st one.
"""
# return line # if there is only 1 check per line
splited = line.split()
ck1 = splited[:4] # in this case, 1st check info is in 1... |
def compare_verbose(gt, out):
"""
function that compares two lists of edges
ex: ground truth list and list of discovered edges
and returns precision and recall with explanations
"""
print("Number of ground truth edges: " +str(len(gt)))
print("Number of discovered edges: " +str(len(out)))
print(" ")
correct = l... |
def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
... |
def string_to_nat(b):
"""Given a binary string, converts it into a natural number. Do not modify this function."""
if b == "":
return 0
else:
return 2 * string_to_nat(b[:-1]) + int(b[-1]) |
def convert(number):
"""
Converts a number into string based on rain drops methodj
Pling = if 3 is a factor
Plang = if 5 is a factor
Plong = if 7 is a factor
the number itself if none of the above are factors.
"""
raindrops = ''
r_3 = divmod(number, 3)[1]
r_5 = divmod(number, 5)[... |
def _r_count_num_m(n, factors_d, i):
"""Count of numbers coprime to d less than end; sum( gcd(m, d) == 1 for m in range(n, n+i) )
Uses inclusion exclusion on prime factorization of d
"""
if n == 0:
return 0
if i < 0:
return n
return _r_count_num_m(n, factors_d, i-1) - _r_coun... |
def getCDXJLineClosestTo(datetimeTarget, cdxjLines):
""" Get the closest CDXJ entry for a datetime and URI-R """
smallestDiff = float('inf') # math.inf is only py3
bestLine = None
datetimeTarget = int(datetimeTarget)
for cdxjLine in cdxjLines:
dt = int(cdxjLine.split(' ')[1])
diff =... |
def _MarkupDescriptionLineOnInput(line, tmpl_lines):
"""Markup one line of an issue description that was just entered.
Args:
line: string containing one line of the user-entered comment.
tmpl_lines: list of strings for the text of the template lines.
Returns:
The same user-entered line, or that line... |
def _pixel_to_coords(col, row, transform):
"""Returns the geographic coordinate pair (lon, lat) for the given col, row, and geotransform."""
lon = transform[0] + (col * transform[1]) + (row * transform[2])
lat = transform[3] + (col * transform[4]) + (row * transform[2])
return lon, lat |
def strip_and_replace_backslashes(path: str) -> str:
"""
>>> strip_and_replace_backslashes('c:\\\\test')
'c:/test'
>>> strip_and_replace_backslashes('\\\\\\\\main\\\\install')
'//main/install'
"""
path = path.strip().replace('\\', '/')
return path |
def interval_to_col_name(interval):
"""
Queries the proper name of the column for timespans given an interval.
"""
interval = interval.lower()
if interval == "yearly":
return "year"
elif interval == "monthly":
return "month"
elif interval == "weekly":
return "week"
... |
def _get_image_lib_name_from_object(obj):
"""
Hackish way to determine from which image lib 'obj' come from
without importing each lib module individually.
"""
result = ()
if obj is not None:
# PIL/Pillow Image
if hasattr(obj, "_close_exclusive_fp_after_loading"):
re... |
def merge_dicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy.
"""
# python 3.5 provides a more elegant way of doing this,
# but at the cost of backwards compatibility
z = x.copy()
z.update(y)
return z |
def parse(input):
"""
parse an input string into token/tree.
For now only return a list of tokens
"""
tokens = []
for l in input.splitlines():
tokens.extend(l.split(" "))
return tokens |
def nondiscrete_relative_likelihood(p, k, k0):
"""given binomial probability (p,k,n) => p^k*(1-p)^(n-k),
return binom_prob(p,k,n) / binom_prob(p,k0,n)
note that n isn't actually needed! this is because we're calculating a
per-configuration weight, and in a true binomial distribution we'd then
multi... |
def get_first(objs, default=""):
"""get the first element in a list or get blank"""
if len(objs) > 0:
return objs[0]
return default |
def strip_metadata(posts, blacklist):
"""Return the post list stripped of specific metadata keys."""
formatted = []
for post in posts:
core_post = {}
for field in post.keys():
if field in blacklist:
continue
core_post[field] = post[field]
forma... |
def generate_schedule_event(region):
"""
Generates a Scheduled Event
:param str region: AWS Region
:return dict: Dictionary representing the Schedule Event
"""
return {
"version": "0",
"account": "123456789012",
"region": region,
"detail": {},
"detail-typ... |
def clamp(minimum, value, maximum):
"""
Clamp the passed `value` to be between `minimum` and `maximum`, including.
"""
return max(minimum, min(maximum, value)) |
def set_value(value_index, value):
"""
API for operator's control.
:param value_name: global variable in main.py
:param value: notuse2 value
:return:
flag: True indicates sucess while False means failure
"""
global f_show
if value_index == 0:
f_show = value
return Tru... |
def autoBindEvents (sink, source, prefix='', weak=False, priority=None):
"""
Automatically set up listeners on sink for events raised by source.
Often you have a "sink" object that is interested in multiple events
raised by some other "source" object. This method makes setting that
up easy.
You name handl... |
def digitsToInt(digits, base=10):
"""
Convert list of digits (in specified base) to an integer
"""
# first get an iterator to digits
if not hasattr(digits, 'next'):
# digits is an iterator
digits = iter(digits)
# now loop through digits, updating num
num = next(digits)
for d in digits:
num *... |
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
True
"""
if n <= 3:
return n
return g... |
def isprime(i):
"""
input: 1, a positive integer
i > 1
returns True if i is a prime number, False otherwise
"""
if i > 1:
count = 0
for z in range(2,i+1):
if (i % z) == 0:
count +=1
if count > 1:
return False
... |
def make_list(string):
"""Turn a binary string into a list of integers."""
return [int(x) for x in list(string)] |
def grouped(s, mode):
"""
Takes a string and a mode. The mode is either "concatenate" or "star."
Determines if the string needs parentheses around it before it gets concatenated or starred with something.
Returns either the original string or the string with parentheses around it.
"""
if len(s) == 1:
... |
def get_response(action, next):
"""Returns a fairly standard Twilio response template."""
response = """<?xml version="1.0" encoding="UTF-8"?>
<Response>
{action}<Redirect method="GET">{next}</Redirect>
</Response>"""
return response.format(action=ac... |
def get_loop_segments(loop):
"""returns a list of segments in a loop"""
segments = []
last_point = None
for this_point in loop:
if last_point is not None:
new_segment = [last_point, this_point]
segments.append(new_segment)
last_point = this_point
return segmen... |
def has_next(seq, index):
"""
Returns true if there is at least one more item after the current
index in the sequence
"""
next_index = index + 1
return len(seq) > next_index |
def b2mb(num):
""" convert Bs to MBs and round down """
return int(num/2**20) |
def _convert_value_to_eo3_type(key: str, value):
"""
Convert return type as per EO3 specification.
Return type is String for "instrument" field in EO3 metadata.
"""
if key == "instruments":
if len(value) > 0:
return "_".join([i.upper() for i in value])
else:
... |
def f(a:int,b:int)->int:
""" Retourne la somme de a et b"""
x:int
x:int
return a+b |
def _mai(a: int, n: int) -> int:
"""
Modular Additive Inverse (MAI) of a mod n.
"""
return (n - a) % n |
def serverparse(server):
"""serverparse(serverpart)
Parses a server part and returns a 4-tuple (user, password, host, port). """
user = password = host = port = None
server = server.split("@", 1)
if len(server) == 2:
userinfo, hostport = server
userinfo = userinfo.split(":",1)
... |
def scalar_multiplication(first_vector, second_vector):
"""
>>> scalar_multiplication([2, 3, 4], [3, 4, 6])
42
"""
return sum([first_vector[i]*second_vector[i] for i in range(len(first_vector))]) |
def related_domain_annotation(sample, domain, relatedness):
"""Create a string for the summary annotation of related samples"""
if sample in relatedness:
if relatedness[sample] == domain:
rv = ":Y"
else:
rv = ":Y:%s" % relatedness[sample]
else:
rv = ""
ret... |
def rands(n):
"""Generates a random alphanumeric string of length *n*"""
from random import Random
import string
return ''.join(Random().sample(string.ascii_letters+string.digits, n)) |
def assume_in_vitro_based_enzyme_modification_assertions(ac):
""" write a JTMS assumption specifying that in vitro-based evidence is acceptable
@param ac:bool True if action is to assert!, False if action is to
retract!, None to get the representation of the assumption
@returns: a string r... |
def is_county(puma):
"""This function takes a string input and checks if it is in King County
or South King County.
It returns a 0 for the greater washinton area, 1 for King County areas that are NOT south king county
and 2 for South King County. It is meant to use as apart of a .map(lambda) style... |
def set_wanted_position(ra, dec, prefix='', rconn=None):
"""Sets the wanted Telescope RA, DEC - given as two floats in degrees
Return True on success, False on failure"""
if rconn is None:
return False
try:
result_ra = rconn.set(prefix+'wanted_ra', str(ra))
result_dec = rcon... |
def matrix_power(M, n):
"""Returns M**n for a symmetric square matrix M for n > 0."""
def symmetric_matmul(A, B):
"""Matrix multiplication of NxN symmetric matrices."""
N = len(A)
C = [[0] * N for _ in range(N)]
for i in range(N):
for j in range(N):
C... |
def counting_sort(array: list) -> list:
"""
Implementation of the linear O(n) Counting Sort algorithm
Arguments:
array - array of integers to be sorted
Returns:
Contents of array argument
"""
# Number of items to be sorted
n: int = len(array)
# Get maximum value in arr... |
def bytestring_to_integer(bytes):
"""Return the integral representation of a bytestring."""
n = 0
for (i, byte) in enumerate(bytes):
n += ord(byte) << (8 * i)
return n |
def validate_geometry(screen_geometry):
"""Raise ValueError if 'screen_geometry' does not conform to <integer>x<integer> format"""
columns, rows = [int(value) for value in screen_geometry.lower().split('x')]
if columns <= 0 or rows <= 0:
raise ValueError('Invalid value for screen-geometry option: "{... |
def combine_blocks(*groups):
"""Combine several blocks of commands into one.
This means that blank lines are inserted between them.
"""
combined = []
for i, group in groups:
if i != 0:
combined.append("")
combined.extend(group)
return combined |
def get_or_else_empty_list(map_to_check, key):
"""
Use map.get to handle missing keys for list values
"""
return map_to_check.get(key, []) |
def parse_percent(size):
"""parses string percent value to float, ignores -- as 0"""
if size == '--':
return 0
number = size[:-1]
return float(number) / 100 |
def convert_empty_value_to_none(event, key_name):
""" Changes an empty string of "" or " ", and empty list of [] or an empty dictionary of {} to None so it will be NULL in the database
:param event: A dictionary
:param key_name: The key for which to check for empty strings
:return: An altered dictionar... |
def _strip_or_pad_version(version, num_components):
"""Strips or pads a version string to the given number of components.
If the version string contains fewer than the requested number of
components, it will be padded with zeros.
Args:
version: The version string.
num_components: The d... |
def filter_values(item):
"""
Returns last element of the tuple or ``item`` itself.
:param object item: It can be tuple, list or just an object.
>>> filter_values(1)
... 1
>>> filter_values((1, 2))
... 2
"""
if isinstance(item, tuple):
return item[-1]
return item |
def is_url(path):
"""
Check if given path is an url path.
Arguments:
path (string): Ressource path.
Returns:
bool: True if url path, else False.
"""
if path.startswith("http://") or path.startswith("https://"):
return True
return False |
def sort_into_sections(events, categories):
"""Separates events into their distinct (already-defined) categories."""
categorized = {}
for c in categories:
categorized[c] = []
for e in events:
categorized[e["category"]].append(e)
return categorized |
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle.
Case is ignored for strings. These string values are handled:
True: 'True', "1", "TRue", "yes", "y", "t"
False: "", "0", "faLse", "no", "n", "f"
Non-string values are passed to bo... |
def all_indexes (text,phrase):
"""Returns a list of all index positions for phrase in text"""
returnlist = []
starting_from = 0
while text and phrase in text:
position = text.index(phrase)
returnlist.append(starting_from+position)
text = text[position+len(phrase)... |
def format_fasta_record(name, seq, wrap=80):
"""Fasta __str__ method.
Convert fasta name and sequence into wrapped fasta format.
Args:
name (str): name of the record
seq (str): sequence of the record
wrap (int): length of sequence per line
Yields:
tuple: name, sequence... |
def align_up(value, align):
"""Align up int value
Args:
value:input data
align: align data
Return:
aligned data
"""
return int(int((value + align - 1) / align) * align) |
def get_redis_url(db, redis=None):
"""Returns redis url with format `redis://[arbitrary_username:password@]ipaddress:port/database_index`
>>> get_redis_url(1)
'redis://redis:6379/1'
>>> get_redis_url(1, {'host': 'localhost', 'password': 'password'})
'redis://anonymous:password@localhost:6379/1'
... |
def default_thread_index (value, threads):
"""
find index in threads array value
:param value:
:param threads:
:return:
"""
value_index = threads.index(value)
return value_index |
def clamp(value, min_=0., max_=1.):
"""Clip a value to a range [min, max].
:param value: The value to clip
:param min_: The min edge of the range
:param max_: The max edge of the range
:return: The clipped value
"""
if value < min_:
return min_
elif value > max_:
return ... |
def gcd(a, b):
"""Returns the greatest common divisor of a and b.
Should be implemented using recursion.
>>> gcd(34, 19)
1
>>> gcd(39, 91)
13
>>> gcd(20, 30)
10
>>> gcd(40, 40)
40
"""
if a < b:
return gcd(b, a)
if not a % b == 0:
return gcd(b, a % b)
... |
def get_slice(tensors, slicer):
"""Return slice from tensors.
We handle case where tensors are just one tensor or dict of tensors.
"""
if isinstance(tensors, dict):
tensors_sliced = {}
for key, tens in tensors.items():
tensors_sliced[key] = tens[slicer]
else:
ten... |
def replace_all_str(x, pattern_list, repl_by):
"""Replace all patterns by a str"""
for p in pattern_list:
x = x.replace(p, repl_by)
return x |
def byte_pad(data: bytes, block_size: int) -> bytes:
"""
Pad data with 0x00 until its length is a multiple of block_size.
Add a whole block of 0 if data lenght is already a multiple of block_size.
"""
padding = bytes(block_size - (len(data) % block_size))
return data + padding |
def diff(x0, y0, z0, x1, y1, z1):
"""
Return the sum of the differences in related values.
"""
dx = abs(x0 - x1)
dy = abs(y0 - y1)
dz = abs(z0 - z1)
return dx + dy + dz |
def upper_bound(arr, value):
"""Python version of std::upper_bound."""
for index, elem in enumerate(arr):
if elem > value:
return index
return len(arr) |
def console_output(access_key_id, secret_access_key, session_token, verbose):
""" Outputs STS credentials to console """
if verbose:
print("Use these to set your environment variables:")
exports = "\n".join([
"export AWS_ACCESS_KEY_ID=%s" % access_key_id,
"export AWS_SECRET_ACCESS_KE... |
def is_pos_float(string):
"""Check if a string can be converted to a positive float.
Parameters
----------
string : str
The string to check for convertibility.
Returns
-------
bool
True if the string can be converted, False if it cannot.
"""
try:
return True... |
def convert_slice(s, rev_lookup_table):
"""Convert slice to (start, stop, step)."""
if s.start is None:
start = 0
else:
start = s.start
if s.stop is None:
stop = len(rev_lookup_table)
else:
stop = s.stop
if s.step is None:
step = 1
else:
step =... |
def combinations(c, d):
"""
Compute all combinations possible between c and d and their derived values.
"""
c_list = [c - 0.1, c, c + 0.1]
d_list = [d - 0.1, d, d + 0.1]
possibilities = []
for cl in c_list:
for dl in d_list:
possibilities.append([cl, dl])
re... |
def extract_primitives(transitions):
"""
Extract all the primitives out of the possible transititions, which are defined by the user and make an list
of unique primitives.
Args:
transitions (list): indicated start, end primitive and their transition probability
Returns:
list of al... |
def chunk_list(lst, n):
"""
Splits a list into n parts
:param lst: list obj
:param n: parts int
:return: list of lists
"""
return [lst[i:i + n] for i in range(0, len(lst), n)] |
def u2nt_time(epoch):
"""
Convert UNIX epoch time to NT filestamp
quoting from spec: The FILETIME structure is a 64-bit value
that represents the number of 100-nanosecond intervals that
have elapsed since January 1, 1601, Coordinated Universal Time
"""
return int(epoch*10000000.0)+116444736... |
def LeakyReLU(v):
"""
Leaky ReLU activation function.
"""
return 0.01*v if v<0 else v |
def exists_and_equal(dict1,key1,val1):
"""
Simple test to see if
"""
if key1 in dict1:
if dict1[key1] == val1:
return True
else:
return False
else:
return False |
def find_shape(bottom_lines, max_len):
"""
Finds a shape of lowest horizontal lines with step=1
:param bottom_lines:
:param max_len:
:return: list of levels (row values), list indexes are columns
"""
shape = [1] * max_len
for i in range(max_len):
for line in bottom_lines:
... |
def compare_structure(source, target, match_null=False):
"""Compare two structures against each other. If lists, only compare the first element"""
# pylint: disable=R0911
if isinstance(source, (list, tuple)) and isinstance(target, (list, tuple)):
if not source or not target:
if match_... |
def partition(A, start_idx, stop_idx, pivot_idx):
"""
FIRST
>>> partition([3, 8 ,2, 5, 1, 4, 7, 6], 0, 8, 0)
2
>>> partition([3, 8 ,2, 5, 1, 4, 7, 6], 3, 8, 3)
5
>>> partition([2, 1], 0, 2, 0)
1
LAST
>>> partition([3, 4, 2, 1, 6], 0, 5, 4)
4
>>> partition([3, 4, 2, ... |
def get_L_BB_k_d(L_HP_d, L_dashdash_d, L_dashdash_k_d):
"""
Args:
L_HP_d: param L_dashdash_d:
L_dashdash_k_d:
L_dashdash_d:
Returns:
"""
return L_dashdash_k_d - L_HP_d * (L_dashdash_k_d / L_dashdash_d) |
def stand_alone_additional_dist_desc(lst_dist_name1, lst_dist_name2, lst_desc_name1, lst_desc_name2):
"""Return True if there is an additional distinctive or descriptive in the stand-alone name."""
if lst_dist_name1.__len__() != lst_dist_name2.__len__() or lst_desc_name1.__len__() != lst_desc_name2.__len__():
... |
def linear_interpolate_pdfs(sample, xvals, pdfs):
"""
Parameters
----------
sample
xvals:
Returns
-------
PDF: np.ndarray
The PDF at sample.
"""
x1, x2 = xvals
pdf1, pdf2 = pdfs
grad = (pdf2 - pdf1) / (x2 - x1)
dist = sample - x1
return grad * dist +... |
def removeArgs(l,r):
""" Used to remove specific parameters from the main function """
args=l[l.find("(")+1:l.rfind(")")]
args=[x.strip() for x in args.split(',')]
new_l=l[:l.find("(")+1]
removeLastComma=False
for idx,arg in enumerate(args):
if r not in arg:
new_l=new_l+args[... |
def g(row):
"""helper function"""
if row['prev_winner_runnerup'] == row['winner_name']:
val = 1
else:
val = 0
return val |
def clone_list(lst: list) -> list:
"""Clone a List"""
new_lst = lst.copy()
return new_lst |
def some_calculation(x, y, z=1):
"""Some arbitrary calculation with three numbers. Choose z smartly if you
want a division by zero exception.
"""
return x * y / z |
def intersectarea(p1,p2,size):
"""
Given 2 boxes, this function returns intersection area
"""
x1, y1 = p1
x2, y2 = p2
ix1, iy1 = max(x1,x2), max(y1,y2)
ix2, iy2 = min(x1+size,x2+size), min(y1+size,y2+size)
iarea = abs(ix2-ix1)*abs(iy2-iy1)
if iy2 < iy1 or ix2 < ix1: iarea = 0
return iarea |
def GetTypeAllocationCode(imei):
"""Returns the 'type allocation code' (TAC) from the IMEI."""
return imei[0:8] |
def select(_, vectors):
"""
Any vector works, pick the first one
"""
return vectors[0] if vectors else None |
def replace_range(new_content: str, target: str, start: int, end: int) -> str:
"""
Replace `target[start:end]` with `new_content`.
"""
if start > len(target):
raise IndexError(
f"start index {start} is too large for target string with length {len(target)}"
)
return targe... |
def remove_paren(token: str):
"""Remove ( and ) from the given token."""
return token.replace('(', '') \
.replace(')', '') |
def remove_space_characters(field):
"""Remove every 28th character if it is a space character."""
if field is None:
return None
return u"".join(c for i, c in enumerate(field) if i % 28 != 27 or c != u' ') |
def convert_seconds(seconds):
"""Convert seconds into """
seconds_in_day = 86400
seconds_in_hr = 3600
seconds_in_min = 60
days = seconds // seconds_in_day
hrs = (seconds - (days*seconds_in_day)) // seconds_in_hr
mins = (seconds - (days*seconds_in_day) - (hrs*seconds_in_hr)) // seconds_in_min... |
def make_album(artist, album, tracks=""):
"""Try it yourself 8-7. Album."""
if tracks:
return {'artist': artist, 'album': album, 'tracks': tracks}
return {'artist': artist, 'album': album} |
def calc_db_cost_v2(db) -> float:
"""Returns a noise cost for given dB based on a linear scale (dB >= 45 & dB <= 75).
"""
if db <= 44:
return 0.0
db_cost = (db-40) / (75-40)
return round(db_cost, 3) |
def search_binary_iter(xs, target):
""" Find and return the index of key in sequence xs """
lb = 0
ub = len(xs)
while True:
if lb == ub: # If region of interest (ROI) becomes empty
return -1
# Next probe should be in the middle of the ROI
mid_index = (lb + ... |
def getTitle(test:str) -> str:
"""
getting str like #test TITLE
return TITLE
"""
return test[5:].strip() |
def best_customer_record(new_record, top_record):
"""Find the best customer record.
Compares the new_record to the current top_record to determine what's the
best extra_dimension for the customer.
Records are lists containing the following information in the specified
position:
2: dimension_cou... |
def _number_of_graphlets(size):
"""Number of all undirected graphlets of given size"""
if size == 2:
return 2
if size == 3:
return 4
if size == 4:
return 11
if size == 5:
return 34 |
def find_all_paths(parents_to_children, start, end, path=[]):
"""Return a list of all paths through a graph from start to end.
`parents_to_children` is a dict with parent nodes as keys and sets
of child nodes as values.
Based on https://www.python.org/doc/essays/graphs/
"""
path = path + [start... |
def calc_f1_macro(y_true, y_pred):
"""
@param y_true: The true values
@param y_pred: The predicted values
@return the f1 macro results for true and predicted values
"""
tp1 = tn1 = fp1 = fn1 = 0
tp0 = tn0 = fp0 = fn0 = 0
for i, val in enumerate(y_pred):
if y_true[i] == val:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.