content stringlengths 42 6.51k |
|---|
def merge_and_count(a1, a2):
"""Merges two arrays and counts the inversions present amongst them.
Args:
a1: A list of integer values.
a2: Another list of integer values.
Returns:
merged_array: List of the final array merged back together from the
created subarrays.
c... |
def seq_match(exseq, inseq, allowMismatch):
"""
Return True if <exseq> and <inseq> are same length and either
(1) identical OR
(2) has at most one mismatch (if allowMismatch is True)
:return: bool, num_mismatch
"""
if len(exseq)!=len(inseq):
return False, None
elif exseq == inse... |
def weakest_cipher(supported_ciphers):
"""Returns the minimum supported cipher strength"""
# find lowest cipher bits supported
lowest_cipher_bits = 4000000000 # suitably large number
for c in supported_ciphers:
cipher_bits = int(c['bits'])
if cipher_bits < lowest_cipher_bits:
... |
def stats_variance_1d(data, ddof=0):
"""Pre compiled method to get 1d variance."""
a_a, b_b = 0, 0
for i in data:
a_a = a_a + i
b_b = b_b + i * i
var = b_b / (len(data)) - ((a_a / (len(data))) ** 2)
var = var * (len(data) / (len(data) - ddof))
return var |
def remove_unknowns(x, y):
"""
Remove word pairs from the results where one or two word embedding weren't found.
Args:
x (list): List of similarity scores assigned by humans.
y (list): List of similarity scores assigned by the system.
Returns:
x (list): Purged list of similarity scores assigned by humans.
... |
def get_parent_path(path):
"""Get the parent path of an xdot node."""
path_tokens = path.split('/')
if len(path_tokens) > 2:
parent_path = '/'.join(path_tokens[0:-1])
else:
parent_path = '/'.join(path_tokens[0:1])
return parent_path |
def _get_sorted_server_names_from_output(output, separator='\t'):
"""return server name list from output"""
server_names = [
row.split(separator)[0]
for row in output.rstrip().split('\n') if row != ''
]
return sorted(server_names) |
def truncate_str(input_str, maxlen, ending='..'):
"""Truncate teh string if more than maxlen chars """
if len(input_str) > maxlen:
return input_str[:(maxlen - len(ending))] + ending
return input_str |
def mapping_filename(mapping):
"""
returns the filename mappings are stored in
"""
filename1, filename2 = mapping
result = f"{filename1}_{filename2}.json"
return result |
def extract_container_id(line):
"""
Extract container id from a Running in line
---> Running in 816abeca3961
"""
parts = line.strip().split(' ')
if len(parts) == 4:
return parts[3]
else:
raise Exception("Unrecognized docker running in line: " + line) |
def getFileNameList(dir, splitSequences = False, extraInformation = False, returnDirs=True, returnHidden=False):
"""getFileNameList( dir, splitSequences = False, extraInformation = False, returnDirs=True, returnHidden=False ) -> str
@param dir the directory to get sequences from
@param splitSequences whether to spl... |
def get_note_title(note):
"""get the note title"""
if 'title' in note:
return note['title']
return '' |
def format_duration(dur: float) -> str:
"""Formats duration (from minutes) into a readable format"""
if float(dur) >= 1.0:
return "{} min".format(int(dur))
else:
return "{} sec".format(int(round(dur * 60))) |
def shipping_cost(num_copy):
"""Finds total shipping cost for a given number of copies
"""
return 3 + 0.75 * (num_copy - 1) |
def caculate(s):
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces .
The integer division should truncate toward zero.
:param s: string
:return: int
"""
if not s:
... |
def solve1(ins_set):
"""Execute the instruction set <ins_set> and return the last value of the
accumulator before an infinite loop (or before the normal conclusion of
the program). """
acc = 0
executed = set()
i = 0
while i < len(ins_set):
if i in executed:
break
... |
def check_previewUrls(search_results):
""" Checks if a result provides a previewUrl for thumbnails. Otherwise a placeholder will be set.
This function is needed to avoid too much logic in template rendering.
Args:
search_results: Contains all search results
Returns:
search_results
... |
def get_ssp_rk_coefficients(K):
"""
Get coefficients for the strong stability-preserving
Runge-Kutta method of order K. May return more stages
S than the order K to avid negative B coeffients and
provide more CFL stability (S >= K).
Returns RK SSP coefficients A, B and the effective CFL
mul... |
def wrap_content(content: str, content_type: str) -> str:
"""
Wraps content in tokens that shows its beginning and the end.
"""
s = f'__{content_type}__'
e = f'__end-{content_type}__'
return f'{s} {content} {e}' |
def _map(f, seq):
""" version of map() for function with multiple return values.
instead of a list of tuples (like map), return a tuple of lists. """
return tuple(map(list, zip(*map(f, seq)))) |
def _cast_output_to_type(value, typ):
"""cast the value depending on the terraform type"""
if typ == "b":
return bool(value)
if typ == "i":
return int(value)
return value |
def cigreen(b3, b8):
"""
Chlorophyll Index Green (Gitelson et al., 2003a).
.. math:: CIGREEN = (b8/b3) - 1
:param b3: Green.
:type b3: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
:returns CIGREEN: Index value
.. Tip::
Gitelson, A. A., Gritz, Y... |
def cy2y(cy, e):
"""Transform from *y* index value to *y* index value, using the
*e.css('ch')* (column height) as column measure."""
if cy is None:
y = 0
else:
paddingY = e.pb
y = paddingY + cy * (e.css('ch', 0) + e.gh)
return y |
def calc_highest_frequency(marks):
""" Function which returns the score with the highest frequency in the list. """
highest_frequency_mark = 0
marks.sort()
frequency = []
cnt = 0
while cnt < len(marks):
frequency.append(marks.count(marks[cnt]))
cnt += 1
frequency_d... |
def hamming(s1,s2):
"""Return minimum Hamming distance between s1 and s2, against all shifts if one is longer."""
if len(s1) == len(s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
if len(s1) > len(s2): s1,s2 = s2,s1
excess = len(s2) - len(s1)
return min( sum(c1 != c2 for c1, c2 in zip(s1... |
def epsg_string_to_epsg(epsg_string: str) -> int:
"""From a string of the form 'EPSG:${code}' return
the epsg code as a integer
Raise a ValueError if the epsg_string cannot
be decoded
"""
epsg_string = epsg_string.lower()
epsg_string = epsg_string.strip()
epsg_string = epsg_string.replac... |
def _wrap(name: str, ttype: int) -> dict:
"""Wrap the tag info inside a nice dict"""
return {
'name': name,
'tag_type': ttype,
} |
def crop(traces, end=None):
"""Crops all the traces signals to have the same duration.
If ``end`` parameter is not provided the traces are cropped to have
the same duration as the shortest given trace.
Parameters
----------
traces : list[list[int]]
2D list of numbers representing the t... |
def createOutLine(list,message):
"""makes result string"""
outline = "Hand: "
for i in range(5):
outline += list[i] + " "
outline += "Deck: "
for i in range(5, 10):
outline += list[i] + " "
outline += "Best hand: "
outline += message + '\n'
return outline |
def _parse_post(post: dict) -> dict:
"""Helper method - parse news response object to dictionary with target structure.
[Source: https://cryptopanic.com/]
Parameters
----------
post: dict
Response object from cryptopanic api.
Returns
-------
dict
Parsed dictionary with ... |
def aa_precision_recall_with_threshold(correct_aa_confidences, all_aa_confidences, num_original_aa, threshold):
"""
Calculate precision and recall for the given amino acid confidence score threshold
Parameters
----------
correct_aa_confidences : list
List of confidence scores for corre... |
def valid_port(_port):
"""[Determine if the port is valid]
Arguments:
ip {[string]} -- [port number]
Returns:
[bool] -- [true or false]
"""
port = int(_port)
if isinstance(port, int) and (port > 1023) and (port <= 65535):
return True
return False |
def polygon_list_to_dict(polygon):
"""
Returns a dictionary with the list of points of a polygon.
Parameters
----------
polygon : `list`
A list with the XYZ coordinates of the vertices of a polygon.
Returns
-------
polygon_dict : `dict`
A dictionary of with the points o... |
def ndim2spatial_axes(ndim):
"""
>>> ndim2spatial_axes(3)
(-3, -2, -1)
>>> ndim2spatial_axes(1)
(-1,)
"""
return tuple(range(-ndim, 0)) |
def extract_x(lst):
"""
Extract x coordinate from list with x, y, z coordinates
:param lst: list with [[x, y, z], ..., [x, y, z]]
:return: list with x coordinates [x, ..., x]
"""
return [item[0] for item in lst] |
def to_safe_filename(uri):
"""
Convert URI to safe filename
:param uri: URI
:return: safe file name
"""
return uri.replace(":", "+") |
def char_to_decimal(text):
"""
Converts a string to its decimal ASCII representation, with spaces between
characters
:param text: Text to convert
:type text: string
:rtype: string
For example:
>>> import putil.misc
>>> putil.misc.char_to_decimal('Hello world!')
'... |
def _check_axes_range(axes, ndim):
"""
Check axes are within the number of dimensions of tensor x and normalize the negative axes.
Args:
axes (Union[int, tuple(int), list(int)]): Axes of the tensor.
ndim (int): The number of dimensions of the tensor.
Return:
Axes (Union[int, tupl... |
def make_onehot(int_list, one_hot_length):
"""Convert each int to a one-hot vector.
A one-hot vector is 0 everywhere except at the index equal to the
encoded value.
For example: 5 as a one-hot vector is [0, 0, 0, 0, 0, 1, 0, 0, 0, ...]
Args:
int_list: A list of ints, each of which will get a one-hot en... |
def is_job_done(res):
"""
Parses a bjobs response to whether or not the job is done
:param res: platform LSF response array
:return: True if the job is done, False if it is not
"""
status = ''
job_done = False
if 'is not found\n' in res[0]: # response: "Job <452341> is not found\n"
... |
def avg(lst: list):
"""
This function computes average of the given list. If the length of list is zero, it will return zero.
:param lst: list for which you want to compute average
:return: average of the given list
"""
if len(lst) == 0:
return 0
return sum(lst) / len(lst) |
def checksum(buffer, checkA, checkB):
"""
8-bit Fletcher algorithm for packet integrity checksum. Refer to [1]
(section 32.4 UBX Checksum, pages 135 - 136).
Inputs:
buffer - They byte buffer to compute the checksum over.
checkA - The first part of the reference checksum to compare the
... |
def parse_RNAfold_out(RNAfold_out):
"""Parse the RNAfold output stream.
The format is
>RNA_id
[seqence]
[structure ([potential_blank]score)]
"""
if type(RNAfold_out) == bytes:
RNAfold_out = RNAfold_out.decode("utf-8")
lines = RNAfold_out.split("\n")
RNA_ids, seq_len, en... |
def flatten_ds(data_struct, key="", path="", flattened=None):
""" Flatten a nested data structure """
if flattened is None:
flattened = {}
if type(data_struct) not in(dict, list):
flattened[((path + ".") if path else "") + key] = data_struct
elif isinstance(data_struct, list):
for i, item in enumera... |
def String(value):
"""Encode a byte string or UTF-8 string value"""
if isinstance(value, str):
value = value.encode('utf-8', errors='strict')
return len(value).to_bytes(4, 'big') + value |
def permutation_as_config_number( p ):
"""
A numeric representation of a numeric list.
Example:
>>> permutation_as_config_number( [ 1, 1, 0, 0, 1 ] )
11001
"""
tot = 0
for num in p:
tot *= 10
tot += num
return tot |
def dh_wrap_field(field):
"""
Wraps a field value for DynamoDB
"""
if isinstance(field, str):
return {"S": field}
elif isinstance(field, list):
wrapped_list = []
for item in field:
wrapped_list.append(dh_wrap_field(item))
return {"L": wrapped_list}
else:
return {"N": str(field)} |
def mult(M, v):
"""
function to multiply a matrix times a vector
"""
n = len(M)
return [sum(M[i][j] * v[j] for j in range(n)) for i in range(n)] |
def check_bouncy(n: int) -> bool:
"""
Returns True if number is bouncy, False otherwise
>>> check_bouncy(6789)
False
>>> check_bouncy(-12345)
False
>>> check_bouncy(0)
False
>>> check_bouncy(6.74)
Traceback (most recent call last):
...
ValueError: check_bouncy() accep... |
def longest_palindrome2(s):
""" correct version """
if len(s) <= 1:
return s
# always match first character
min_i = 0
max_j = 0
cache = [0] * len(s)
for i in range(len(s) - 1, -1, -1):
new_cache = [0] * len(s)
new_cache[i] = 1
for j in range(i+1, len(s)):
... |
def check_continuity(array):
"""
Check whether the array contains continous values or not like 1, 2, 3, 4, ..
"""
max_v = max(array)
min_v = min(array)
n = len(array)
# print(n, min_v, max_v)
if max_v - min_v + 1 == n:
# print("Given array has continous values")
retur... |
def can_show_deleted(context):
"""
Calculates whether to include deleted objects based on context.
Currently just looks for a flag called deleted in the context dict.
"""
if hasattr(context, 'show_deleted'):
return context.show_deleted
if not hasattr(context, 'get'):
return False... |
def _is_summary(l):
# type: (str) -> bool
"""Checks if the line is the summary line 'Found X errors in Y files (checked Z source files)'"""
return l.startswith("Found ") and l.endswith("source files)\n") |
def kth_smallest_select(nums, k):
"""Kth smallest element by selection.
Time complexity: O(n).
Space complexity: O(n).
"""
# Just select the kth element, without caring about the
# relative ordering of the rest of them.
pivot = nums[len(nums) // 2]
mid_pos = [pos for pos, x in enumera... |
def make_list(list_file):
"""create a blacklist list from a file"""
return [line.strip("\n").strip("\r") for line in open(list_file)] |
def dicts_same_except(d1, d2, ignore):
"""
Checks if dicts d1 and d2 are equal, but ignoring keys specified in the ignore list.
"""
d1 = d1.copy()
d2 = d2.copy()
for k in ignore:
try:
del d1[k]
except KeyError:
pass
try:
del d2[k]
... |
def ESS(inString1, inString2):
"""Encode two strings as a single string.
ESS is an acronym for Encode as Single String. This function uses
the encoding method suggested in the textbook: the encoding
consists of the length of the first string, followed by a space
character, followed by the two stri... |
def pop_and_rotate_text_list(text) -> tuple:
"""Rotates once, a python list contained within a string
Returns rotated list in string form and the popped item.
"""
pylist = text.strip().strip('[]').strip().strip(',').split(',')
pylist = [i.strip() for i in pylist]
first_item = pylist.pop(0)
... |
def name2path(name):
"""
Replace '/' in name by '_'
"""
return name.replace("/", "-") |
def calc_other_grammar(probs):
"""
:param probs: list of negative log likelihoods for a corpus
:return: grammaticality of corpus
"""
grammar = 0
for idx in range(0, len(probs), 24):
grammar -= probs[idx + 1] + probs[idx + 3] + probs[idx + 5] + probs[idx + 7]
grammar -= probs[idx ... |
def findUnsortedSubarray(nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
start=-1
end=-2
small=nums[n-1]
big=nums[0]
for i in range(1,n):
big = nums[i] if big < nums[i] else big
small = nums[n-1-i] if small > nums[n-1-i] else small
if nums[i] < big:
end=i
if nums[n-1-i] > small:
sta... |
def get_dict_values(dict_keys: list, a_dict: dict) -> list:
"""Get the dictionary's values from a provided list of dictionary's keys.
- dict_keys (list): a list of dictionary's keys to be filtered out from a
dictionary _dict.
_ a_dict (dict): a dictionary to be filtered with a dict_list.
-> Retur... |
def is_number(s):
"""Check if a string is a number or not."""
try:
float(s)
return True
except ValueError:
return False |
def parse_argument(arg):
"""Helper function for wild arguments"""
if arg in ["No", "N", "NO", "OFF", "off", "n", "no"]:
return "no"
else:
return "yes" |
def _bias_correction(X, beta, t):
"""Performs bias correction."""
bc = 1 - beta ** t
return X / bc |
def split_container_name(name):
"""
Takes a container name (e.g. samtools:1.7--1) and returns a list (e.g. ['samtools', '1.7', '1'])
>>> split_container_name('samtools:1.7--1')
['samtools', '1.7', '1']
"""
return name.replace("--", ":").split(":") |
def _match_message(key, value, event):
"""Return true if `key` and `value` exist within the given message."""
if key == 'datapath_id' and value is None:
return True
val = str(value).upper()
msg = event['msg']
if key in msg:
return str(msg[key]).upper() == val
pkt = msg.get('pkt')... |
def warning_message(message, category, filename, lineno, file=None, line=None):
""" Define the format of a warning message.
"""
return ">>> {0}:{1}: {2}\n {3}\n".format(
filename, lineno, category.__name__, message) |
def dag_s3_prefix(dag_id, timestamp):
"""Define the prefix that will be prepended to all files created by this dag run"""
return "{}/{}".format(dag_id, timestamp) |
def is_bad_version(m, x):
"""
Evaluates version quality.
:type m: int
:type x: int
:rtype: bool
"""
if m >= x:
return True
else:
return False |
def uniq(lst):
"""list -> list. remove duplicated items without changing the order"""
seen = set()
result = []
for x in lst:
if x not in seen:
seen.add(x)
result.append(x)
return result |
def pick(d, *fields):
""" Pick keys from a dictionary if present.
If a field starts with a '+' it is converted to a list if it isn't one
already.
"""
result = {}
for f in fields:
listify = f.startswith('+')
if listify:
f = f[1:]
if f in d:
value =... |
def trim_trailing_lines(lines):
"""
Trim trailing blank lines.
"""
lines = list(lines)
while lines and not lines[-1]:
lines.pop(-1)
return lines |
def recursive_sum(n):
"""
Sums n + n -1 until it is 1
Alejandro AS
"""
if n == 1:
return 1
return n + recursive_sum(n - 1) |
def min_operations(target):
"""
Return number of steps taken to reach a target number
input: target number (as an integer)
output: number of steps (as an integer)
"""
steps = 0
number = target
while number > 0:
if number % 2 == 0:
number /= 2
else:
... |
def cosmic_link(variant_obj):
"""Compose link to COSMIC Database.
Args:
variant_obj(scout.models.Variant)
Returns:
url_template(str): Link to COSMIIC database if cosmic id is present
"""
cosmic_ids = variant_obj.get('cosmic_ids')
if not cosmic_ids:
return None
els... |
def rgb_list_to_decimal(color):
"""Convert an rgb color from list to decimal representation."""
return int(int(color[0]) << 16) + (int(color[1]) << 8) + (int(color[2])) |
def last_index(seq, f):
"""Returns index of last item in seq where f(item) is True, or None.
To invert the function, use lambda f: not f
NOTE: We could do this slightly more efficiently by iterating over s in
reverse order, but then it wouldn't work on generators that can't be
reversed.
... |
def int_to_ip(ip):
"""
Convert a 32-bit integer into IPv4 string format
:param ip: 32-bit integer
:return: IPv4 string equivalent to ip
"""
if type(ip) is str:
return ip
return '.'.join([str((ip >> i) & 0xff) for i in [24, 16, 8, 0]]) |
def _is_external(p):
"""Checks if the string starts with ../"""
return p[0:3] == '../' |
def depth_PT(depth):
"""Retrun liquidus P and T at a given depth in a magma ocean
Liquidus data is taken from figure 3 of Andrault et at. 2011
(EPSL doi:10.1016/j.epsl.2011.02.006) and is for a chondritic
material. We assime linear behaviour to 60 GPa.
"""
dPdDepth = 60.0/1400.0 # GPa/km
P... |
def convert_idx(text, tokens):
"""
unchanged from @chrischute
"""
current = 0
spans = []
for token in tokens:
#for small_token in token:
# unclear why this is necessary, but I'll just appease it for now.
# the functions should all be sending and receiving the same type
... |
def get_days_from_json(j):
""" Return just the day names from the json response """
return [i['name'] for i in j['holidays']] |
def recon_action_payload(passed_keywords: dict) -> dict:
"""Create a properly formatted payload for attaching recon actions to a monitoring rule.
{
"actions": [
{
"frequency": "string",
"recipients": [
"string"
],
... |
def colstr2tuple(colstr):
"""Conterts a '#rrggbb' string to RGB 0-255 triple."""
red = int("0x" + colstr[1:3], base=16)
green = int("0x" + colstr[3:5], base=16)
blue = int("0x" + colstr[5:7], base=16)
return red, green, blue |
def setup_sendgrid_connection(sendgrid_key):
"""
16-May-2018, deprecated in favor of notify.api.sendgrid_api
Use send_mail
"""
# return sendgrid.SendGridClient(sendgrid_key)
return None |
def left_late(departure):
"""Return True if left late. False, otherwise."""
planned = departure[0]
actual = departure[1]
if not actual:
return False
return actual > planned |
def find_fomoists(events_attendees, rsvp_statuses=['attending']):
"""
"events" is a list of lists of attendees:
[
[
{
"name": "Brittany Miller",
"rsvp_status": "attending",
"id": "1442173849420454"
},
...
]
...
]
... |
def f1(precision: float, recall: float) -> float:
"""Compute F1, returning 0.0 if undefined."""
if precision and recall:
return 2 * precision * recall / (precision + recall)
else:
return 0.0 |
def safe_string(string: str):
"""https: / stackoverflow.com/questions/7406102/create-sane-safe-filename-from-any-unsafe-string"""
keepcharacters = (' ', '.', '_')
return "".join(c for c in string if c.isalnum() or c in keepcharacters).rstrip() |
def findORF_all_sorted_longest_n_r_r_r_r_r(dna_seq, n):
"""
Finds all the longest open reading frames in the DNA sequence.
"""
tmpseq = dna_seq.upper();
orf_all = []
for i in range(0, len(tmpseq), 3):
codon = tmpseq[i:i+3]
if codon == 'ATG':
orf = tmpseq[i:]
... |
def lighten(color, scale=1.0):
"""
Lighten a color.
- color is a tuple (r, g, b, a)
- scale can be any number, if < 1, color will be darken
"""
return tuple(map(
lambda x: int(min(max(x * scale, 0), 255)),
color[:3]
)) + color[3:] |
def is_valid_boolean_param(param, required=True):
"""Checks if the parameter is a valid boolean.
@param param: Value to be validated.
@return True if the parameter has a valid boolean value, or False otherwise.
"""
if param is None and not required:
return True
elif param is None:
... |
def Primenumbers(number):
"""This function returns the factors of any number"""
primes = []
factors = []
j = 1
while len(primes) < 20:
for a in range(j,0,-1):
if j % a == 0:
factors.append(a)
else:
... |
def ints_to_rgb(r, g=None, b=None):
"""Convert ints in the [0...255] range to the standard [0...1] range.
Parameters:
:r:
The Red component value [0...255]
:g:
The Green component value [0...255]
:b:
The Blue component value [0...255]
Returns:
The color as an (r, g, b) tuple in... |
def format_variant(variant):
"""
Return None for null variant and strips trailing whitespaces.
Parameters
----------
variant : str, optional.
HGVS_ formatted string.
Returns
-------
str
"""
if variant is None:
return variant
return variant.strip() |
def tf_sched(cur_epoch,epochs,final_tf_ratio):
"""
modified teacher forcing ratio according to epoch counts
Args:
cur_epoch: (int) current epoch
epochs: (int) total epochs
final_tf_ration: (float) smallest teacher forcing ratio
Returns:
teacher forcing ratio for cur... |
def gt0(val: int) -> int:
"""Value must be grater than 0"""
if val <= 0:
raise ValueError("bal must be greater than 0.")
return val |
def query_create_index(table, index, col_name):
"""
Generate query to create index with name 'index' on column
'col_name' in table 'table'
"""
return 'CREATE INDEX ' + index + ' ON ' + table + '(' + col_name + ')' |
def heap_sort(array):
""" Sort an array of a given size """
def build_heap(array, heap_size):
""" Building max heap """
for i in range((heap_size//2), -1, -1):
# Check for max-heap property
max_heapify(array, heap_size, i)
def max_heapify(array, heap_size, i):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.