content stringlengths 42 6.51k |
|---|
def determine_native_name(coreclr_args, base_lib_name, target_os):
""" Determine the name of the native lib based on the OS.
Args:
coreclr_args (CoreclrArguments): parsed args
base_lib_name (str) : root name of the lib
target_os (str) : os to run tests on
Return:
(str) : nam... |
def video_type(compress: bool = False,
trim: bool = False,
trim_compress: bool = False) -> str:
"""Return type of the video.
The returned value is generated by conditional checks.
Args:
compress: Boolean value (default: False) if video to be compress.
trim: Boolean... |
def get_lock_filepath(filepath):
"""Get a lock file path for filepath.
Args:
filepath (str): Path.
Returns:
str: Lock file path.
"""
return f'{filepath}.lock' |
def next_power(x: int, k: int = 2) -> int:
"""Calculate x's next higher power of k."""
y, power = 0, 1
while y < x:
y = k ** power
power += 1
return y |
def getAngleStatus(angle):
""" returns status based on the angle. Status codes:
0 - straight (-10 to +10)
1 - left or down (less than -10)
2 - right or up (greater than 10)
"""
if angle < -10:
return 1
elif angle > 10:
return 2
return 0 |
def transform(data, pse):
"""The transformer function."""
param = "payload"
pos = data.find(param + "=")
pos += len(param + "=")
body = data[pos:]
if body.endswith("\r\n"):
body = body.rstrip("\r\n")
elif body.endswith("\n"):
body = body.rstrip("\n")
elif body.endswith("... |
def cpu_bound_summing_custom(number: int):
""" Multiprocessing doesn't seem to like the library "deal". """
return sum(i * i for i in range(number + 1)) |
def use_middleware_script(container_type):
"""
Should the pilot use a script for the stage-in/out?
Check the container_type (from queuedata) if 'middleware' is set to 'container' or 'bash'.
:param container_type: container type (string).
:return: Boolean (True if middleware should be containerised)... |
def iou_set(set1, set2):
"""Calculate iou_set """
union = set1.union(set2)
return len(set1.intersection(set2)) / len(union) if union else 0 |
def camel_case(st):
""" Convert a string to camelCase. From:
https://stackoverflow.com/questions/8347048/camelcase-every-string-any-standard-library
"""
output = ''.join(x for x in st.title() if x.isalnum())
return output[0].lower() + output[1:] |
def pad(input, size=8):
"""
>>> pad('foo')
'foo====='
>>> pad('MZXW6YTBOJUWU23MNU')
'MZXW6YTBOJUWU23MNU======'
"""
quanta, remainder = divmod(len(input), size)
padding = '=' * ((size - remainder) % size)
return input + padding |
def _merge_keys(dicts):
"""Return the union of the keys in the list of dicts."""
keys = []
for d in dicts:
keys.extend(d.keys())
return frozenset(keys) |
def fix_file(filename):
"""
ASCII STL file from 3D GNOME have a broken first line
so we patch it into another file, leaving the original
untouched
"""
new_filename = filename.replace('.stl','_fix.stl') # Kludgy
with open(filename,'r') as f:
first_line = f.readline()
if '... |
def duo_anonymous_ip_failure(rec):
"""
author: airbnb_csirt
description: Alert on Duo auth logs marked as a failure due to an Anonymous IP.
reference: https://duo.com/docs/policy#anonymous-networks
playbook: N/A
"""
return rec['result'] == 'FAILURE' and rec['reason'] == 'Anonym... |
def fibonacci(n):
"""Function that provides nth term of a fibonacci series."""
x, y = 0, 1
for i in range(n - 1):
x, y = y, x + y
return x |
def all_equal(values: list):
""" Check that all values in given list are equal """
return all(values[0] == v for v in values) |
def removePenBob(data):
"""
Merge segments with same beginning and end
"""
outData = {}
for pen in data:
outSegments = []
outSegment = []
for segment in data[pen]:
if not outSegment:
outSegment = list(segment)
elif outSegment[-1] == ... |
def ScaleData(data, old_min, old_max, new_min, new_max):
"""Scale the input data so that the range old_min-old_max maps to
new_min-new_max.
"""
def ScalePoint(x):
if x is None:
return None
return scale * x + translate
if old_min == old_max:
scale = 1
else:
scale = (new_max - new_min) ... |
def get_user_video_url(user_type, key):
"""Compile the user videos url."""
return f'https://www.pornhub.com/{user_type}/{key}/videos' |
def does_intersect_rect(p, particles, padding, rect, is_3d = False):
"""
Returns true if particle p is sufficiently close or outside the rectangle (in 2d) or cuboid (in 3d)
Parameters
----------
p : list
Coordinates of center and radius of particle [x,y,z,r]
particles : list
List of center + ra... |
def to_string(tag):
"""
Creates a pretty string from any given XML tag.
"""
temp = tag.replace('_', ' ').title()
temp = temp.replace('Fir', 'FIR')
return temp |
def get_numeric_columns(columns):
"""Identify numeric string elements in a list.
Parameters
----------
columns : list
List of str with column names.
Returns
-------
list
List containing all string elements which are numeric.
"""
numeric_elements = []
for column... |
def hyphen_last(s):
"""Converts '-foo' to 'foo-', so that 'foo-' comes after 'foo'
which is useful for sorting."""
if s.startswith('-'):
return s[1:] + '-'
return s |
def selected_summary(summaries: list = []):
"""
The gene summary selection algorithm used to select the summary that is displayed at the top of the
gene report.
:param summaries: An ordered list containing counts of each gene summary type.
:return: The name of the summary that would be selected gi... |
def decUTF8(inp):
"""
Recursively decode bytes as utf8 into unicode
"""
if isinstance(inp, bytes):
return inp.decode('utf8')
elif isinstance(inp, list):
return [decUTF8(x) for x in inp]
elif isinstance(inp, dict):
return {decUTF8(key): decUTF8(val) for key, val in inp.ite... |
def read_file(path: str) -> str:
""" Get the content of a file """
try:
return open(path, "r").read()
except FileNotFoundError:
return "" |
def flight_time_movies_3_utilize_set(movie_lengths, flight_length):
"""
Solution: As we iterate through our movie lengths, store the matching
movie length needed in a set for a constant time lookup on all subsequent
iterations.
Complexity:
Time: O(n)
Space: O(n)
"""
if len(movie_lengths) < 2:
raise ValueEr... |
def remove_path_segments(segments, remove):
"""
Removes the path segments of <remove> from the end of the path
segments <segments>.
Examples:
# '/a/b/c' - 'b/c' == '/a/'
remove_path_segments(['','a','b','c'], ['b','c']) == ['','a','']
# '/a/b/c' - '/b/c' == '/a'
remove_path_segm... |
def tokenize(source):
"""
Splits an input string into meaningful tokens (left parens, right parens,
other whitespace-separated values). Returns a list of strings.
Arguments:
source (str): a string containing the source code of a carlae
expression
"""
# Separate al... |
def retriable_error(exception):
"""Return True if test should be re-run based on the Exception"""
return isinstance(exception, (AssertionError,)) |
def _maybe_right_split(s, splitter):
"""If we can, split the string `s` by `splitter` and take the right-hand
component (the second item in the returned tuple).
"""
if splitter and splitter in s:
return s.split(splitter)[1]
else:
return s |
def flatten(d, sep='_', parent_key=''):
"""Flattens a nested map.
Adapted from https://stackoverflow.com/a/6027615/254190"""
items=dict()
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if v and isinstance(v, dict):
items = {**items, **flatten(v, s... |
def path_shift(script_name, path_info, shift=1):
""" Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift.... |
def pascal_row(n):
""" Returns n-th row of Pascal's triangle
"""
result = [1]
x, numerator = 1, n
for denominator in range(1, n // 2 + 1):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if n & 1 == 0:
result.extend(reversed(result[:-1]))
... |
def format_runtime(runtime):
"""Formats the given running time (in seconds)."""
if runtime < 60:
# Just seconds.
return '{:.2f}s'.format(runtime)
# Minutes and seconds.
return '{}m {}s'.format(int(runtime // 60), int(runtime % 60)) |
def printable_glyph_list(glyph_list, quote=False):
"""Returns a printable form for a list of glyphs."""
if quote:
suffix = "'"
else:
suffix = ""
if len(glyph_list) == 1:
return glyph_list[0] + suffix
else:
glyph_list = [glyph + suffix for glyph in glyph_list]
... |
def filter_by_value(dct, func=lambda val: val):
""" filter dictionary entries by their values
"""
return {key: val for key, val in dct.items() if func(val)} |
def create_final_top_msg(top_songs: list) -> str:
"""
Function, that create top command response message.
"""
msg = f"TOP {len(top_songs)} songs\n"
for song in top_songs:
msg += f"{song['artist']} - {song['title']} ---- {len(song['voted_users'])}\n"
return msg |
def get_strs_in_cats(str_list, cats, compl=False):
"""
str_list is the general list of strings, usually the list of all cell names
cats is a selection of strings, it is usually a list
for any x in str_list, if x is part of any y (y is an element of cats)
then x is chosen. Example of str_list: all th... |
def contigs_n_bases(contigs):
"""Returns the sum of all n_bases of contigs."""
return sum(c.n_bases for c in contigs) |
def classToExceptionCode(cls):
"""
return C++ enum exception code for class
Args:
cls: an exception class, must be inheriting from Exception
Returns: integer encoding exception type
"""
lookup = {BaseException : 100,
Exception : 101,
ArithmeticError : 102,
... |
def get_env_logname(name):
"""
get_env_logname
"""
modname = name.split('.')[0].upper()
envname = f"{modname}_LOGLEVEL"
# print(envname)
return envname |
def _getname(infile):
"""
Get file names only.
Examples
--------
>>> _getname("drop/path/filename.txt")
'filename.txt'
>>> _getname(["drop/path/filename.txt", "other/path/filename2.txt"])
['filename.txt', 'filename2.txt']
"""
from pathlib import Path
if isinstance(infile,... |
def _generate_params(kwargs):
"""
Generate JSON based on the arguments passed to this function
"""
params = {}
for key in kwargs:
if kwargs[key] != None:
params[key] = kwargs[key]
return params |
def compute_max_shape(shapes, max_dims=None):
"""Computes the maximum shape combination from the given shapes.
Parameters
----------
shapes : iterable of tuple
Shapes to coombine.
max_dims : int, optional
Pre-computed maximum dimensions of the final shape.
If None, is comput... |
def eliminate(problem, location, listOfLocations):
"""
Given a list of locations, eliminate from the problem the number that is
present at the `location`.
:param list problem: Two-dimensional list of sets
:param tuple location: Location with the number to be removed
:param list<tuple> listOfLoc... |
def sqlchar_encode(encvalue):
""" SQL char encode the specified value.
Example Format: CHAR(72)+CHAR(101)+CHAR(108)+CHAR(108)+CHAR(111)"""
charstring = ""
for item in encvalue:
val = "CHAR(" + str(ord(item)) + ")+"
charstring += val
return(charstring.rstrip("+")) |
def normalize(text, *, title_case: bool = True, underscores: bool = True, **kwargs):
"""Attempts to normalize a string
Parameters
-----------
text: Any
The string or object to attempt to normalize
title_case: bool
Returns the formatted string as a Title Case string. Any substitution... |
def elipses(long_string,max_length=40,elipses='...'):
"""!Returns a shortened version of long_string.
If long_string is longer than max_length characters, returns a
string of length max_length that starts with long_string and ends
with elipses. Hence, the number of characters of long_string that
w... |
def runnable_validator(language, options):
"""Options validator for runnable codemirror code blocks."""
okay = True
if 'lang' not in options:
okay = False
return okay |
def get_tool_info(whitelist, tool_name):
"""
Search the whitelist by tool name.
:returns: A dictionary , or none if no tool matching that name was found.
:rtype: dict or None
"""
for category, category_tools in whitelist.items():
for tool_info in category_tools:
if tool_info... |
def XYToInd(location, width, height):
"""Location (x,y) to index"""
return location[1] * width + location[0] |
def stringify_value(value):
"""Convert any value to string.
"""
if value is None:
return u''
isoformat = getattr(value, 'isoformat', None)
if isoformat is not None:
value = isoformat()
return type(u'')(value) |
def code_to_str(code,alphabet):
"""
Takes a code list/tensor and gets the corresponding sentence using the alphabet.
Alphabet must have has blank(0) at index zero, each symbol is an idx.
"""
return "".join([alphabet[symbol] for symbol in code]) |
def to_bool(value: str) -> bool:
"""
Convert a string to a boolean.
Arguments:
value: The string to convert.
Returns:
True or False.
"""
return value.lower() not in {"", "0", "no", "n", "false", "off"} |
def sunset_float(solar_noon_float, hour_angle_sunrise):
"""Returns Sunset as float with Solar Noon Float, solar_noon_float
and Hour Angle Deg, hour_angle_deg"""
sunset_float = (solar_noon_float * 1440 + hour_angle_sunrise * 4) / 1440
return sunset_float |
def get_user(user_id=None):
"""
Return object representing the logged in user
Keyword Parameters:
user_id -- String, identifier representing the logged in user
(Default: None, representing an public/anonymous user session)
>>> # Check public/Anonymous user
>>> from pprint import pprint
... |
def get_lake_abbrev(record):
"""A helper function used by get_latlon()
Arguments:
- `record`:
"""
lake = record.get("lake")
if lake:
lake = lake.strip()
if len(lake) > 2:
return lake[:2].upper()
else:
return lake.upper()
else:
return N... |
def go_up_right(x: int, y: int) -> tuple:
"""
Go 1 unit in both positive x and y directions
:param x: x-coordinate of the node
:param y: y-coordinate of the node
:return: new coordinates of the node after moving diagonally up-right
"""
return x + 1, y + 1 |
def make_pairs(I, mid):
"""
We take pairs as [ [9, 1], [8, 2], [7, 3], [6, 4]]
:param I:
:param mid:
:return:
"""
h = 0
t = len(I) - 1
pairs = []
while h < mid-1:
pairs.append([I[h], I[t]])
h += 1
t -= 1
return pairs |
def sample_bounded_Pareto(alpha = 1., L = 1., H = 100., size=None, seed=None):
"""
Use:
sample_bounded_Pareto(alpha = 1., L = 1., H = 100., size=None, seed=None)
random samples drawn from the bounded Pareto distribution,
p_X(x) ~ x^(-alpha-1), L<x<H
0, else
S... |
def create_zero_matrix(rows: int, columns: int) -> list:
"""
Creates a matrix rows * columns where each element is zero
:param rows: a number of rows
:param columns: a number of columns
:return: a matrix with 0s
e.g. rows = 2, columns = 2
--> [[0, 0], [0, 0]]
"""
matrix = []
if n... |
def calories(snacks):
"""
>>> calories(0)
0
>>> calories(1)
5
>>> calories(2)
55
>>> calories(3)
60
>>> calories(4)
110
"""
unhealthy = 50
healthy = 5
if snacks % 2 == 0 and snacks != 0:
return calories(snacks - 1) + unhealthy
elif (snacks % 2 ... |
def complete_english(string):
"""
>>> complete_english('dont do this')
"don't do this"
>>> complete_english('doesnt is matched as well')
"doesn't is matched as well"
"""
for x, y in [("dont", "don't"),
("doesnt", "doesn't"),
("wont", "won't"),
... |
def is_float_like(val):
"""Check if a value looks like a float."""
try:
return str(float(val)) == str(val)
except Exception:
return False |
def equation(operation, firstnum, secondnum):
"""
Solve a simple maths equation manually
"""
if operation == 'plus':
return firstnum + secondnum
elif operation == 'minus':
return firstnum - secondnum
elif operation == 'multiply':
return firstnum * secondnum
elif opera... |
def get_bold_token(token):
"""Apply bold formatting to a given token.
https://api.slack.com/docs/message-formatting#message_formatting
Args:
token (str): String sequence with a specific definition (for parser).
Returns:
str: bold formatted version of a token.
"""
return "*{}*"... |
def cdf_points(marginal_hist):
"""
Generate the points for a CDF of a distribution from its marginal
histogram.
"""
cumulative = 0
total = sum(x[1] for x in marginal_hist)
points = []
for (val, count) in marginal_hist:
cumulative += count
points.append((val, cumulative / ... |
def get_max_len(in_string, max_len):
"""Gets current length of string and returns it if it exceeds the provided
max_len. Otherwise, returns the provided max_len.
"""
curr_len = len(in_string)
if curr_len > max_len:
return curr_len
return max_len |
def chunkIt(seq, num):
"""
Divide a sequence seq into num roughly equal pieces.
:param seq:
:param num:
:return:
"""
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out |
def uncap_sentence(sent):
"""
Workaround for tweets: sometimes the entire sentence is in upper case. If more than 99%
of the sentence is in upper case, this function will convert it to lower case.
:param sent: the tweet
:return: the sentence, lower cased if it is all in upper case
"""
... |
def ext(name):
"""Extracts the filename extension."""
dot = name.rfind(".")
if -1 != dot:
return name[dot:]
return "" |
def hash_function_2(key: str) -> int:
"""
Sample Hash function #2 to be used with A5 HashMap implementation
DO NOT CHANGE THIS FUNCTION IN ANY WAY
"""
hash, index = 0, 0
index = 0
for letter in key:
hash += (index + 1) * ord(letter)
index += 1
return hash |
def street_not_in_use(street, items):
"""
Check if elements of street are not in use already.
For example [[(2, 'black'), (3, 'black'), (4, 'black'),(5, 'black)],[(3, 'black'), (4, 'black'), (5, 'black')]]
would return false, because 3, 4 and 5 are already used
:param street: List of elements that w... |
def prime_factors(n):
"""Returns all the prime factors of a positive integer"""
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n /= d
d = d + 1
if d*d > n:
if n > 1: factors.append(n)
break
retur... |
def escape_for_tsv(text: str) -> str:
"""Changes double-quotes to single-quotes, and adds double-quotes around the
text if it has newlines/tabs."""
text.replace("\"", "'")
if "\n" in text or "\t" in text:
return "\"{}\"".format(text)
return text |
def pixel_pos_to_game_grid(x_pixel, y_pixel):
"""
input: position in pixels, touple
return: position in gridtouple
"""
grid_nx = x_pixel // 100 # integere division
grid_ny = y_pixel // 100
return(grid_nx, grid_ny) |
def unnormalize_parameters(normed_parameters, minvals, maxvals):
"""takes in a list of parameters and undoes simple min/max normalization according to min/max values
INPUTS
normed_parameters: length n, containing parameters for a star
minvals: length n, minimum parameter values
maxvals: length n, ma... |
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
res = 0
if len(array)>0:
sum = 0
for i in range(0,len(array)):
if i % 2 == 1:
continue
print ('Selecting ', i , '->', array[i])
sum += array[i]
... |
def get_pp_line(cv, vals):
"""
Return a point that gives a particular CV, when the collective variables are defined through a line.
Parameters
----------
cv : array
The target cv.
vals : list
A list of the line defining the CV.
Returns
-------
pp : array
Th... |
def c2scToSmcpName( c2scname ):
"""Turns 'Aacute.c2sc' into 'aacute.smcp'."""
glyphname = c2scname[:c2scname.find(".")].lower()
suffix = c2scname[c2scname.find("."):].replace("c2sc", "smcp")
return glyphname + suffix |
def format_tweet_url(tweet: dict) -> str:
"""
Construct tweet link url
:param tweet:
:return:
"""
tweet_url = "https://twitter.com/{}/status/{}".format(tweet['user']['screen_name'],
tweet['id_str'])
return tweet_url |
def make_tuple_fromstr(s, value_type):
"""
Create a tuple from a string.
:param str s: string to convert to a tuple
:param value_type: type of values to be contained within tuple
:return: tuple from string
:rtype: tuple
"""
# remove tuple braces and strip commands and space from all val... |
def convert_row_to_dict(row):
"""
Convert a list of fields in the CloudFlare CSV file
into a dict with field names.
"""
cf_dict = dict()
cf_dict['hostname'] = row[0]
cf_dict['clientIp'] = row[1]
# CloudFlare Placeholder, always a hyphen
cf_dict['col3'] = row[2]
# CloudFlare Plac... |
def ByteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip() |
def get_min_dr(frequency):
""" Returns the MIN data rate for the provided frequency."""
# if frequency in VALID_FREQ:
# return 0
# else:
# return 0
return 0 |
def lwavg(a1, a2, w1, w2):
"""
A linear weighted average for comparison
"""
return (w1*a1 + w2*a2), 0 |
def nemoFibonacci(n, nemo):
"""Recursive Fibonacci function with nemoization. """
if n <= 0:
return 0
elif n ==1:
return 1
elif nemo[n] == 0:
nemo[n] = nemoFibonacci(n-2, nemo) + nemoFibonacci(n-1, nemo)
return nemo[n] |
def _api_cmd(cmd):
"""Prefix the container command with the docker cmd"""
return f"docker exec -it mpasocial_api {cmd}" |
def GetGapSequenceConsensus_old(origTopoMSASeqList, indexIDTTopo):#{{{
"""Get a sequence of gap fractions of the consensus topology """
gapSeqCons =[];
apd=gapSeqCons.append
lengthAlignment = len(origTopoMSASeqList[0]);
numIDTTopo = len(indexIDTTopo)
for i in range(0, lengthAlignment):
... |
def convert_truelike_to_bool(input_item, convert_int=False, convert_float=False, convert_nontrue=False):
"""Converts true-like values ("true", 1, True", "WAHR", etc) to python boolean True.
Taken from korbinian python package by Mark Teese. This is allowed under the permissive MIT license.
Parameters
... |
def idx_to_zbin_nob(idx):
"""
Alternative to idx_to_zbin for when shear B modes are not included.
Return the z bin corresponding to a particular row or column index, assuming 2 fields per z bin.
Args:
idx (int): Field index.
Returns:
int: z-bin corresponding to field index, where 1... |
def convert(names, midterm1, midterm2, final):
"""
Takes dictinaries and convert them to a list
Args:
names: dictionary keys are numbers values are names
midterm1: dictionary keys are numbers values are midterm1 scores
midterm2: dictionary keys are numbers values are midterm2 scores... |
def idtp(df, id_global_assignment, num_objects, idfn):
"""ID measures: Number of true positives matches after global min-cost matching."""
del df, id_global_assignment # unused
return num_objects - idfn |
def zipformat(ll, header_list):
"""
zips together FORMAT labels, Sample name and format values into one dict
"""
for nr, plist in enumerate(ll[9:]):
formatlist = [
header_list[nr + 9] + "_" + i for i in plist[0].split(":")
]
ll[nr + 9] = dict(zip(formatlist, plist[1].... |
def unpack_str(bytes):
"""Convert a list of bytes to a string."""
return b''.join(bytes).decode("utf-8") |
def _to_mask_bits(size):
"""Create a 32-bit integer representing a mask of the given # of bits"""
mb = 0
for bs in range(31, 31 - size, -1):
mb = mb | 1 << bs
return mb |
def assert_that_rectangles_do_not_overlap(rectangles):
"""given a list of rectangles and a description (any string)
verify that all the rectangles are disjoint. The rectangles
list consists of tuples, containing a rectangle and a description"""
def geometry_to_string(rectangle):
return '%dx%d%+d... |
def flatten(xs):
"""
Flatten any recursive list or tuple into a single list.
For instance:
- `flatten(x) => [x]`
- `flatten([x]) => [x]`
- `flatten([x, [y], [[z]]]) => `[x, y, z]`
"""
if isinstance(xs, (list, tuple)):
return [y for ys in [flatten(x) for x in xs] for y in ys]
return [xs] |
def is_rejected_with_high_vaf(vaf, status, vaf_th):
"""Check if SNV is rejected with vaf over threshold.
Args:
vaf: vaf of the SNV.
vaf_th: vaf threshold.
status: reject/pass status of SNV.
Returns:
True if rejected, False otherwise
"""
if vaf > vaf_th and status =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.