content stringlengths 42 6.51k |
|---|
def EmailToAccountResourceName(email):
"""Turns an email into a service account resource name."""
return 'projects/-/serviceAccounts/{0}'.format(email) |
def count_sort(arr, max_element):
""" count sort, an O(n) sorting algorithm that just records the frequency
of each element in an array
:type arr: list
:type max_element: int
:rtype: list
"""
# initializing variables
freq = [0 for _ in range(max_element + 1)]
ret = list()
# coun... |
def _fullname(obj):
"""Get the fully qualified class name of an object."""
if isinstance(obj, str):
return obj
cls = obj.__class__
module = cls.__module__
if module == "builtins": # no need for builtin prefix
return cls.__qualname__
return module + "." + cls.__qualname__ |
def binary_sort(x, start, end, sorted_list):
"""Performs Binary Search
Get the middle index (start+end/2)
Take the middle element of the sorted list and compare it to x
If x is the middle element, return the index
If start == end then return -1
If x is less than this, perform binary sort on... |
def display_onnx(model_onnx, max_length=1000):
"""
Returns a shortened string of the model.
@param model_onnx onnx model
@param max_length maximal string length
@return string
"""
res = str(model_onnx)
if max_length is None or len(res) <= max_leng... |
def convert_raid_state_to_int(state):
"""
:type state: str
"""
state = state.lower()
if state == "optimal":
return 0
elif state == "degraded":
return 5
else:
return 100 |
def convert_input_to_standrad_format(inp: str):
"""_summary_
Removes spaces and dashes from argument inp. Then it returns inp.
Format of the argument inp must be validated with the function validate_format() before inserting it into this function.
Args:
inp (str): String to convert to ... |
def size_grow_function(curr_size, model_size):
"""
Compute the new size of the subproblem from the previous.
:param curr_size: the current size of the model.
:type curr_size: int
:param model_size: the model size, that is the upper bound of curr_size.
:type model_size: int
:return: the new ... |
def pretty2int(string):
"""Parse a pretty-printed version of an int into an int."""
return int(string.replace(",", "")) |
def create_reduce_job(results, wuid=None, job_num=None):
"""Test function for reduce job json creation."""
if wuid is None or job_num is None:
raise RuntimeError("Need to specify workunit id and job num.")
args = [result['payload_id'] for result in results]
return {
"job_type": "job:pa... |
def getAccuracy(l1, l2):
"""
Returns accuracy as a percentage between two lists, L1 and L2, of the same length
"""
assert(len(l1) == len(l2))
return sum([1 for i in range(0, len(l1)) if l1[i] == l2[i]]) / float(len(l1)) |
def calculate_desired_noise_rms(clean_rms, snr):
"""
Given the Root Mean Square (RMS) of a clean sound and a desired signal-to-noise ratio (SNR),
calculate the desired RMS of a noise sound to be mixed in.
Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/... |
def is_gzip(name):
"""
True if the given name ends with '.gz'
"""
return name.split('.')[-1] == 'gz' |
def union(lst1, lst2):
"""
Purpose: To get union of lists
Parameters: two lists
Returns: list
Raises:
"""
final_list = list(set().union(lst1, lst2))
return final_list |
def _extract_comment(_comment):
"""
remove '#' at start of comment
"""
# if _comment is empty, do nothing
if not _comment:
return _comment
# str_ = _comment.lstrip(" ")
str_ = _comment.strip()
str_ = str_.lstrip("#")
return str_ |
def _unpack(param):
"""Unpack command-line option.
:param list param: List of isotopes.
:return: List of unpacked isotopes.
:rtype: :py:class:`list`
"""
options = []
for option_str in param:
options.extend(option_str.split(","))
return options |
def format_classification_dictionary(csv_dictionary):
"""
Convert loaded CSV classificator to the dictionary with the following format
{suites:{device_type,operating_system,application,browser}}.
:param csv_dictionary: CSV object with loaded classification dictionary
:return: Dictionary with suites... |
def _from_data_nist(raw_data):
"""Convert a NIST data format to an internal format."""
for point in raw_data:
point.pop('species_data')
return raw_data |
def are_version_compatible(ver_a, ver_b):
"""
Expects a 2 part version like a.b with a and b both integers
"""
(a_1, a_2) = ver_a.split('.')
(b_1, b_2) = ver_b.split('.')
(a_1, a_2) = (int(a_1), int(a_2))
(b_1, b_2) = (int(b_1), int(b_2))
if a_1 < b_1:
return False
if (b_2 > ... |
def update_pos(s0, v0, delta_t_ms):
"""
Given the position and speed at time t0 (s0, v0),
computes the new position at time t1 = t0 + delta_t
"""
return s0 + (v0 * delta_t_ms / 1000) |
def is_list(value):
"""Checks if `value` is a list.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a list.
Example:
>>> is_list([])
True
>>> is_list({})
False
>>> is_list(())
False
.. versionadded:: 1.0.0
... |
def make_iterable(x):
"""
Makes the given object or primitive iterable.
:param x: item to check if is iterable and return as iterable
:return: list of items that is either x or contains x
"""
if x is None:
x = []
elif not isinstance(x, (list, tuple, set)):
x = [x]
retu... |
def read_file(filename):
"""
Read a file and return its binary content. \n
@param filename : filename as string. \n
@return data as bytes
"""
with open(filename, mode='rb') as file:
file_content = file.read()
return file_content |
def pythonize_path(path):
""" Replaces argument to valid python dotted notation.
ex. foo/bar/baz -> foo.bar.baz
:param str path: path to pythonize
:return str: pythonized path
"""
return path.replace("/", ".") |
def add_to_dict(param_dict):
"""
Aggregates extra variables to dictionary
Parameters
----------
param_dict: python dictionary
dictionary with input parameters and values
Returns
----------
param_dict: python dictionary
dictionary with old and new values added
"""
... |
def indentation(line):
"""Returns the number of leading whitespace characters."""
return len(line) - len(line.lstrip()) |
def split_number_and_unit(s):
"""Parse a string that consists of a integer number and an optional unit.
@param s a non-empty string that starts with an int and is followed by some letters
@return a triple of the number (as int) and the unit
"""
if not s:
raise ValueError('empty value')
s... |
def calculate_z(x: int, m: int, sd: int) -> float:
"""Calculate a z-score, rounded to two decimal places."""
return round((x - m) / sd, 2) |
def natMult3and5(limit):
"""Find the sum of all the multiples of 3 or 5 below 'limit'"""
sum = 0
for i in range(limit):
if i % 5 == 0 or i % 3 == 0:
sum += i
return sum |
def detect_multi_line_assignment(index, lines):
"""
detects if a line is carriage returned across multiple lines and if so
extracts the entire multiline string and how
get multi line assignment e.g. if this string is
split on multiple lines
xs = np.array([[1, 2, 3],
[5, 6, ... |
def lb_mixing(a1, a2):
"""
Applies Lorentz-Berthelot mixing rules on two atoms.
Args:
a1 (tuple):
Tuple of (epsilon, sigma)
a2 (tuple):
Tuple of (epsilon, sigma)
"""
eps = (a1[0]*a2[0])**(1./2)
sigma = (a1[1] + a2[1])/2.
return eps, sigma |
def AverageCluster(C):
"""
AverageCluster calculates the average local clustering coefficient value
of a network.
Input:
C = array of clustering coefficient values
Output:
c = average clustering coefficient value
"""
n = len(C)
c = sum(C)/n
return c |
def format_keys(keys):
"""
Converts keys like findHighlightForeground to find_highlight_foreground.
"""
for key in keys:
formatted_key = ''.join([f"_{c.lower()}" if c.isupper() else c for c in key.text])
key.text = formatted_key
return keys |
def rofi2list(datas, sep):
"""
Convert list formatted for rofi into python list object
Parameters
----------
datas : str
a string with element separeted by line-breaks
sep : str
separator character
Returns
-------
list
elements of datas in a list
Exampl... |
def extent_of_ranges(range_from, range_to):
"""Helper- returns the length of the outer extents of two ranges in ms"""
return range_to[1] - range_from[0] |
def levenshtein(s1, s2):
"""https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumera... |
def _get_native_location(name):
# type: (str) -> str
"""
Fetches the location of a native MacOS library.
:param name: The name of the library to be loaded.
:return: The location of the library on a MacOS filesystem.
"""
return '/System/Library/Frameworks/{0}.framework/{0}'.format(name) |
def iterative_factorial(n: int) -> int:
"""Returns the factorial of n, which is calculated iteratively.
This is just for comparison with the recursive implementation.
Since the "factorial" is a primitive recursive function, it can be
implemented iteratively.
Proof that factorial is a primitive re... |
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
out = []
for i in range(0, len(lst), n):
#yield lst[i:i + n]
out.append(lst[i:i + n])
return out |
def alignUp(value: int, size: int):
"""Aligns and address to the given size.
:param value: The address to align up.
:type value: int
:param size: The size to which we align the address.
:type size: int
:return The aligned address.
:rtype int
"""
return value + (size - value % size)... |
def is_file_like(value):
"""Check if value is file-like object."""
try:
value.read(0)
except (AttributeError, TypeError):
return False
return True |
def integral_4(Nstrips):
"""
The first integral: integrate x between 0 and 1.
"""
width = 1/Nstrips
integral = 0
for point in range(Nstrips):
height = (point / Nstrips)
integral = integral + width * height
return integral |
def _next_page_state(page_state, took):
"""Move page state dictionary to the next page"""
page_state['page_num'] = page_state['page_num'] + 1
page_state['took'] = page_state['took'] + took
return page_state |
def cal_recom_result(sim_info, user_click):
"""
recom by itemcf
Args:
sim_info: item sim dict
user_click: user click dict
Return:
dict, key:userid value dict, value_key itemid , value_value recom_score
"""
recent_click_num = 3
topk = 5
recom_info = {}
for user ... |
def row_value(row):
"""Calculate the difference between the highest and largest number."""
return max(row) - min(row) |
def greedy_cow_transport(cows, limit=10):
"""
Uses a greedy heuristic to determine an allocation of cows that attempts to
minimize the number of spaceship trips needed to transport all the cows. The
returned allocation of cows may or may not be optimal.
The greedy heuristic should follow the followi... |
def regenerated_configure(file_paths):
"""Check if configure has been regenerated."""
if 'configure.ac' in file_paths:
return "yes" if 'configure' in file_paths else "no"
else:
return "not needed" |
def check_elements(string):
"""Check for chemical letters outside of the CHNOPS set.
If the string only contains CHNOPS, returns True.
Otherwise, returns False.
Note: does not cover Scandium :(
"""
bad_elements = "ABDEFGIKLMRTUVWXYZsaroudlefgibtn" # chem alphabet -CHNOPS
return not any(n i... |
def valid_filename(proposed_file_name):
"""
Convert a proposed file name into a valid and readable UNIX filename.
:param str proposed_file_name: a proposed file name in string, supports
unicode in Python 3.
:return: a valid file name in string.
"""
valid_chars = list("abcdefghijklmnopq... |
def annotation_layers(state):
"""Get all annotation layer names in the state
Parameters
----------
state : dict
Neuroglancer state as a JSON dict
Returns
-------
names : list
List of layer names
"""
return [l["name"] for l in state["layers"] if l["type"] == "annotat... |
def bel_mul(d):
"""NI mul from Belaid et al."""
return int(d**2/4)+d |
def methods_of(obj):
"""
Get all callable methods of an object that don't
start with underscore (private attributes)
returns
:param obj: objects to get callable attributes from
:type obj: object
:return result: a list of tuples of the form (method_name, method)
:rtype: list
"""
r... |
def rgb_to_hex(r, g, b):
""" convert rgb to hex """
h = ("0","1","2","3","4","5","6","7","8","9", "a", "b", "c", "d", "e", "f")
r1, r2 = int(r/16), int(float("0." + str(r/16).split(".")[-1])*16)
r = h[r1] + h[r2]
g1, g2 = int(g/16), int(float("0." + str(g/16).split(".")[-1])*16)
g = h[g1] + h[g2]
b1, b2 = int(... |
def show_user_profile(username):
"""
user profile
"""
# show the user profile for that user
return 'User %s' % username |
def oddbox(funcname, boxsize, quiet=False, *args, **kwargs):
"""Ensure that the boxsize for smoothing is centered.
Makes a smoothing box/window be 2M+1 long to put the result in the centre
:param funcname: Function name, just for the message
:type funcname: string
:param boxsize: 2M|2M+1 that is ... |
def split_arg(s, sep, default=''):
"""
split str s in two at first sep, returning empty string as second result if no sep
"""
r = s.split(sep, 2)
r = list(map(str.strip, r))
arg = r[0]
if len(r) == 1:
val = default
else:
val = r[1]
val = {'true': True, 'false': ... |
def get_emoji(string):
"""Manages string input with unicode chars and turns them into Unicode Strings."""
if len(string) != 0:
if string[0] == "<":
return string
else:
string = chr(int(string, 16))
return string |
def hot_test(blue, red):
"""Haze Optimized Transformation (HOT) test
Equation 3 (Zhu and Woodcock, 2012)
Based on the premise that the visible bands for most land surfaces
are highly correlated, but the spectral response to haze and thin cloud
is different between the blue and red wavelengths.
... |
def contrast(strength=1.0):
"""
Contrast filter.
Author: SolarLune
Date Updated: 6/6/11
strength = how strong the contrast filter is.
"""
return (
"""
// Name: Contrast Filter
// Author: SolarLune
// Date Updated: 6/6/11
uniform sa... |
def check_for_reqd_cols(data, reqd_cols):
"""
Check data (PmagPy list of dicts) for required columns
"""
missing = []
for col in reqd_cols:
if col not in data[0]:
missing.append(col)
return missing |
def versiontuple(v):
"""Convert a string of package version in a tuple for future comparison.
:param v: string version, e.g "2.3.1".
:type v: str
:return: The return tuple, e.g. (2,3,1).
:rtype: tuple
:Example:
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
>>> False
... |
def cosine_similarity(a,b):
"""
Calculate the cosine similarity between two vectors.
"""
import numpy
a = numpy.array(list(a), dtype=int)
b = numpy.array(list(b), dtype=int)
n = numpy.dot(a,b)
d = numpy.linalg.norm(a,ord=2) * numpy.linalg.norm(b,ord=2)
# If one of the vectors is the... |
def generate_sequential_ints(n):
"""
Generates n sequential integers starting at 0
:param int n: number of ints to generate
:return: list of sequential ints
"""
ints = list()
for x in range(n):
ints.append(x)
return ints |
def get_template_s3_url(bucket_name, resource_path):
"""
Constructs S3 URL from bucket name and resource path.
:param bucket_name: S3 bucket name
:param prefix string: S3 path prefix
:return string: S3 Url of cloudformation templates
"""
return 'https://%s.s3.amazonaws.com/%s' % (bucket_name... |
def gray2int(graystr):
"""Convert greycode to binary."""
num = int(graystr, 2)
num ^= (num >> 8)
num ^= (num >> 4)
num ^= (num >> 2)
num ^= (num >> 1)
return num |
def from_perfect_answer(text: str) -> str:
"""
Generates GIFT-ready text from a perfect answer.
Parameters
----------
text : str
The phrasing of the answer.
Returns
-------
out: str
GIFT-ready text.
"""
return f'={text}' |
def extract_key(key_shape, item):
"""construct a key according to key_shape for building an index"""
return {field: item[field] for field in key_shape} |
def solution(S, P, Q):
"""
DINAKAR
Order A,C,G,T => order as impact factor 1,2,3,4
in loop A,C,G,T appends 1,2,3,4 due to order and value of impact factor
Objective is to find the minimal impact in each P,Q
Clue- below line has the hidden answer - [find the minimal impact factor of nucleotide... |
def compare_arr_str(arr1, arr2):
"""
Function that takes two arrays of str or str and compares them.
The string from one can be a sub string of the
"""
# Both str
if (isinstance(arr1, str) and isinstance(arr2, str)):
if arr1 in arr2:
return True
# First str
... |
def splitext_all(_filename):
"""split all extensions (after the first .) from the filename
should work similar to os.path.splitext (but that splits only the last extension)
"""
_name, _extensions = _filename.split('.')[0], '.'.join(_filename.split('.')[1:])
return(_name, "."+ _extensions) |
def get_n_grams(token, grams_count):
"""
returns the n_grams of a token
:param token: ex. results
:param grams_count: ex. 2
:return: ['$r', 're', 'es', 'su', 'ul', 'lt', 'ts', 's$']
"""
grams = [token[i:i + grams_count] for i in range(len(token) - grams_count + 1)]
grams.append(grams[-1]... |
def calc_weight(judge_i, pairing_i):
""" Calculate the relative badness of this judge assignment
We want small negative numbers to be preferred to large negative numbers
"""
if judge_i < pairing_i:
# if the judge is highly ranked, we can have them judge a lower round
# if we absolutely... |
def make_compact(creation_sequence):
"""
Returns the creation sequence in a compact form
that is the number of 'i's and 'd's alternating.
Examples
--------
>>> from networkx.algorithms.threshold import make_compact
>>> make_compact(['d', 'i', 'i', 'd', 'd', 'i', 'i', 'i'])
[1, 2, 2, 3]
... |
def get_first_syl(w):
"""
Given a word w, return the first syllable and the remaining suffix.
"""
assert len(w) > 0
a = w[0]
n = 0
while n < len(w) and w[n] == a:
n = n + 1
return ((a, n), w[n:]) |
def split_by_sep(seq):
"""
This method will split the HTTP response body by various separators,
such as new lines, tabs, <, double and single quotes.
This method is very important for the precision we get in chunked_diff!
If you're interested in a little bit of history take a look at the git log
... |
def extract_digit(str):
"""
extract only digits from a string
"""
return [int(s) for s in str.split() if s.isdigit()] |
def is_api_response_success(api_response: dict) -> bool:
"""Check if the response returned from the Connect API is a success or not."""
return "result" in api_response and api_response["result"].lower() == "success" |
def search_results_dict(results, num_matches, limit, offset, sort):
"""This is for consistent search results"""
ret = {
'matches': num_matches,
'limit': limit,
'offset': offset,
'results': results
}
return ret |
def update(tagid):
"""
Think a tag we have in our database isn't accurate?
Request this endpoint to update our db
"""
return {"Status": "Not finished"} |
def Crc8(data):
"""Calculates the CRC8 of data.
The generator polynomial used is: x^8 + x^2 + x + 1.
This is the same implementation that is used in the EC.
Args:
data: A string of data that we wish to calculate the CRC8 on.
Returns:
crc >> 8: An integer representing the CRC8 value.
"""
crc = 0... |
def wrap_text(text: str, max_length: int = 16) -> str:
"""Return a new label with wrapped text.
Parameters
----------
text : str
The current label text
max_length : int
The max length for the label (defaults to 16 characters)
Returns
-------
str
The new label te... |
def _find_linar_poly(p1_x, p1_y, p2_x, p2_y):
"""
Finding the linear polynomial y=kx+d from two points
Parameters
----------
p1_x : float
X value of first point.
p1_y : float
Y value of first point.
p2_x : float
X value of second point.
p2_y : float
Y val... |
def dockerhub_url(name, version):
"""Dockerhub URL."""
return "https://registry.hub.docker.com/v2/repositories/{}/tags/{}/".format(
name,
version,
) |
def ratio_to_int(percentage, max_val):
"""Converts a ratio to an integer if it is smaller than 1."""
if 1 <= percentage <= max_val:
out = percentage
elif 0 <= percentage < 1:
out = percentage * max_val
else:
raise ValueError("percentage={} outside of [0,{}].".format(percentage, m... |
def sum_of_squares(x, y, fn):
"""
Calculates error between training set and our approximation
Residential sum of squares: sum(|f(x) - y|^2)
for all (x,y) in out training set
:return: float which represents error
"""
return sum([(i - j) ** 2 for i, j in zip(map(fn, x), y)]) |
def isdatadescriptor(object):
"""Return true if the object is a data descriptor.
Data descriptors have both a __get__ and a __set__ attribute. Examples are
properties (defined in Python) and getsets and members (defined in C).
Typically, data descriptors will also have __name__ and __doc__ attributes
... |
def calc_density_diff(cube1_value, cube2_value):
"""Computes formated density difference.
Parameters
----------
cube1_value : str
Single value of electron density.
cube2_value : str
Single value of electron density.
Returns
-------
str
cube1 - cube2 value.
... |
def to_lowercase(words):
"""Convert all characters to lowercase from list of tokenized words"""
new_words = [word.lower() for word in words]
return new_words |
def grouplist(obj):
"""Returns a list of groups"""
return obj['hostgroup'] |
def form_columns(form):
"""
:param form: Taken from requests.form
:return: columns: list of slugified column names
labels: dict mapping string labels of special column types
(observed_date, latitude, longitude, location)
to names of columns
"""
labels = {}
... |
def get_baji_for_icmrucc_spinfree(b, a, j, i, v_n, a_n, c_n, a2a):
"""
Author(s): Yuhto Mori
"""
if a2a:
bj = (b - c_n) * (a_n + c_n) + j
ai = (a - c_n) * (a_n + c_n) + i
if bj > ai:
if b > j:
if b >= a_n + c_n:
redu = (a_n+1)*a_n//... |
def _is_datetime_dtype(obj):
"""Returns True if the obj.dtype is datetime64 or timedelta64
"""
dtype = getattr(obj, 'dtype', None)
return dtype is not None and dtype.char in 'Mm' |
def green(s):
"""Color text green in a terminal."""
return "\033[1;32m" + s + "\033[0m" |
def _gf2mul(a,b):
"""
Computes ``a * b``.
Parameters
----------
a, b : integer
Polynomial coefficient bit vectors.
Returns
-------
c : integer
Polynomial coefficient bit vector of ``c = a * b``.
"""
c = 0
while a > 0:
if (a & 1) != 0:
... |
def parse_row(row, cols, sheet):
"""
parse a row into a dict
:param int row: row index
:param dict cols: dict of header, column index
:param Sheet sheet: sheet to parse data from
:return: dict of values key'ed by their column name
:rtype: dict[str, str]
"""
vals = {}
for header, ... |
def response_test(response: dict):
"""Quick test of the http request to make sure it has the data structure needed to analyze
Args:
response (dict): dictionary of http response
Returns:
boolean test
"""
if 'items' in response:
if len(response['items'])>0:
if 's... |
def bubble_sort(list_to_sort):
""" Sort list in input using bubble sorting.
:param list_to_sort: the list to sort
:type list_to_sort: list
:return: the list sorted
:rtype: list
"""
list_size = len(list_to_sort)
for i in range(list_size):
for j in range(0, list_size-i-1):
... |
def get(args, attr):
"""
Gets a command-line argument if it exists, otherwise returns None.
Args:
args: The command-line arguments.
attr (str): The name of the command-line argument.
"""
if hasattr(args, attr):
return getattr(args, attr)
return None |
def butlast(mylist):
"""Like butlast in Lisp; returns the list without the last element."""
return mylist[:-1] |
def is_float(string):
"""
Check if `string` can be converted
into a float.
Parameters
----------
string : str
String to check.
Returns
-------
check : bool
True if `string` can be converted.
"""
try:
float(string)
return True
except ValueError:
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.