content stringlengths 42 6.51k |
|---|
def ext_binary_gcd(a, b):
"""Extended binary GCD.
Given input a, b the function returns
d, s, t such that gcd(a,b) = d = as + bt."""
u, v, s, t, r = 1, 0, 0, 1, 0
while (a % 2 == 0) and (b % 2 == 0):
a, b, r = a//2, b//2, r+1
alpha, beta = a, b
#
# from here on we maintain a =... |
def as_attr(s):
""" Replaces dashes with underscores, so `s` can be a python attribute :) """
return s.replace('-', '_') |
def get_indices_that_contain_selector(input_list, selectors):
"""Generates list of indices of strings in input_list that
contain a string inside of selectors
:param list input_list: list of strings
:param list selectors: list of strings
:return: (*list*) -- list of indices of strings in input_list... |
def get_quadrant(x, y):
"""
>>> from itertools import product
>>> [get_quadrant(x, y) for x, y in product([-1, 1], [-1, 1])]
[2, 1, 3, 0]
>>> get_quadrant(-1, 0)
1
"""
return 2*(y < 0) + 1*((x < 0) ^ (y < 0)) |
def find_missing_number(numbers):
"""
akes a shuffled list of unique numbers from 1 to n with one element missing (which can be any number including n).
:param numbers: array of intergers.
:return: this missing number.
"""
total = 1
for i in range(2, len(numbers) + 2):
total += i
... |
def remove_author_username(list_of_contributors):
"""Remove the username of the author from the list of contributors
:param list_of_contributors: A list, the list of contributors
"""
authors_username = 'EragonJ'
authors_username_transifex = 'eragonj'
if authors_username in list_of_contributor... |
def truncate_arg_value(value, max_len=1024):
"""Truncate values which are bytes and greater than `max_len`.
Useful for parameters like 'Body' in `put_object` operations.
"""
if isinstance(value, bytes) and len(value) > max_len:
return b"..."
return value |
def type_to_extension(kernel_type):
"""Given a SPICE kernel type provide the SPICE kernel extension.
:param kernel_type: SPICE kernel type
:type kernel_type: str
:return: SPICE Kernel extension
:rtype: str
"""
kernel_type = kernel_type.upper()
kernel_type_map = {
"IK": ["ti"],
... |
def make_result (text, weight_map):
""" Extract the (possibly-empty) list of country codes with the highest weight.
Order is not significant.
@param text: the original text
@param weight_map: a weight map (country codes as keys, weights as values)
@returns: a list of country codes (may be empty)
... |
def str2intorfloat(v):
""" String to int or float formatter for argparse. """
try:
return int(v)
except:
return float(v) |
def compare_seq(lines, align_lines, positions):
""""Compare sequences and determine what matches"""
bp_match = {}
for bp in range(positions):
compare = [lines[line][bp] for line in range(align_lines)]
if len(set(compare)) != 1:
bp_match[bp] = 'X'
else:
bp_matc... |
def binary_search(array, required, from_index: int, to_index: int) -> int:
"""
Just one more version of binary search in sorted array
@param from_index: Index to search from
@param to_index: Index to search to
@return: Index of required element. -1 if not found
"""
if array[from_index] == re... |
def dequote(x):
""" Removes outermost quotes from a string, if they exist """
if x[0] == '"' and x[len(x)-1] == '"':
return x[1:len(x)-1]
return x |
def solution(limit: int = 50000000) -> int:
"""
Return the number of integers less than limit which can be expressed as the sum
of a prime square, prime cube, and prime fourth power.
>>> solution(50)
4
"""
ret = set()
prime_square_limit = int((limit - 24) ** (1 / 2))
primes = set(ra... |
def CalcSize(bits):
"""Calculate the best display version of the size of a given file
1024 = 1KB, 1024KB = 1MB, ...
@param bits: size of file returned by stat
@return: formatted string representation of value
"""
val = ('bytes', 'KB', 'MB', 'GB', 'TB')
ind = 0
while bits > 1024:
... |
def _replace_val(line,find,replace):
""" Find and replace a value in a string.
Keyword arguments:
line -- string.
find -- value to find.
replace -- new value.
"""
strList = line.strip("\n").split()
flag = False
for i,val in enumerate(strList):
if val==find:
flag = True
strList[i] = str(replace)
line ... |
def _fast_is_cjk(x) -> bool:
"""Given a character ordinal, returns whether or not it is CJK."""
# Clauses, in order:
# (1) CJK Unified Ideographs
# (2) CJK Unified Ideographs Extension A
# (3) CJK Unified Ideographs Extension B
# (4) CJK Unified Ideographs Extension C
# (5) CJK Unified Ideog... |
def is_random(name):
"""
Determine if a user has a randomly generated display name.
"""
if len(name.split('_')) and name.startswith('user'):
return True
else:
return False |
def indexPosition2D(i, j, N, M):
"""This function is a generic function which determines if for a grid
of data NxM with index i going 0->N-1 and j going 0->M-1, it
determines if i,j is on the interior, on an edge or on a corner
The funtion return four values:
type: this is 0 for interior, 1 for on ... |
def decode_string(s):
"""
Decode bytes s to string. Return original if decode failed.
"""
try:
return s.decode('utf-8')
except (UnicodeDecodeError, AttributeError):
return s |
def precision_single_class(correctly_assigned, total_assigned):
"""
Computes the precision for a single class
:rtype : float
:param correctly_assigned: Samples correctly assigned to the class
:param total_assigned: Total samples assigned to the class
:return: The precision value
"""
# ... |
def str2binary(s):
"""
:param s: string content to be transformed to binary
:return: binary
"""
return s.encode('utf-8') |
def sigma_u(z, params):
"""
Non-linear velocity rms, used as the smoothing scale for the redshift-space
velocity field.
"""
sigma_u = params['sigma_u'] # Mpc
return sigma_u + 0.*z |
def get_json(data):
"""Find the JSON string in data and return a string.
:param data: :string:
:returns: string -- JSON string stripped of non-JSON data
"""
first = data.index('{')
last = data.rindex('}')
return data[first:last + 1] |
def count_words_in_str(long_str, keys):
"""
It counts the sum of number of times each element in the array "keys" occurs in the string "long_str".
Parameters
-----------
long_str: The long string which needs to be checked for the count of words.
keys: The array of keys for which we need to cou... |
def prettyFloat( val, format = "%5.2f" ):
"""output a float or "na" if not defined"""
try:
x = format % val
except (ValueError, TypeError):
x = "na"
return x |
def mb(n_bytes):
""" Mb from bytes """
return n_bytes / 1024 / 1024 |
def reachable(items,iter_succ,key=lambda x:x):
""" items is a list, key maps list elements to hashable keys,
order is a set of pairs of items representing a pre-order. Returns a
list of descendants of items."""
m,s,l,d = set(),list(items),[],set()
while len(s) > 0:
i = s.pop()
k = k... |
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
Returns:
parameters -- pytho... |
def custom_admin_notification(session, notification_type, message, task_id=None):
"""
Function for implementing custom admin notifications.
notifications are stored in session and show to user when user refreshes page.
A valid session object must be passed to this function with notification type and me... |
def form_page_ranges(current_page, last_page):
"""Leave only the first 2, the last 2 pages, and selected page with 4 its neighbours.
The method assumes that less than 10 pages shouldn't be separated.
Example outputs:
* if 6 is selected, 11 pages total: [[1, 2], [4, 5, 6, 7, 8], [10, 11]]
* if... |
def does_match_fields(d, field_match):
"""
Returns if the given dictionary matches the {field_match}.
{field_match} may look like: { 'must_be' : 'this', 'and_any_of_' : ['tho', 'se']} """
if not field_match:
return True
for mk, mv in field_match.iteritems(): # each matches must be fulfilled
... |
def coding_problem_30(arr):
"""
You are given an array of non-negative integers that represents a two-dimensional elevation map where each element
is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled
up. Compute how many units of water remain ... |
def editSim(str1, str2):
"""
Calculates the EditSim(ES).
Description: The EditSim between two strings str1 and str2,
is an edit distance based similarity measure calculated by
1.0 - (ED(str1, str2)/maximum(length(str1), length(str2))).
Parameters:
str1(str): The first string
str2(... |
def append(iterable, data):
"""Appends data to the iterable.
:param iterable: collection of data to transform
:type iterable: list
:param data: any type of data to be appended
"""
iterable.append(data)
return iterable |
def _slistShape0(slist):
"""_slistShape0(slist) computes the (shape, itemsize) tuple
of the nested string list 'slist'.
itemsize is set to the maximum of all string lengths in slist.
>>> s=["this","that","the other"]
>>> _slistShape(s)
((3,), 9)
>>> _slistShape((s,s,s,s))
((4, 3), 9)
... |
def square_to_curly(l):
"""Convenience function that converts a list to a string,
then replaces the square brackets with curly braces."""
return str(l).replace('[', '{').replace(']', '}') |
def predicate(line):
"""
Remove lines starting with ` # `
"""
if "#" in line:
return False
return True |
def get_divisor(high, low):
"""
Method to obtain a sensible divisor based on range of two values
Args:
high: (float), a max data value
low: (float), a min data value
Returns:
divisor: (float), a number used to make sensible axis ticks
"""
delta = high-low
divis... |
def choose_management(tui, config):
"""Ask the user which PIF should be used for management traffic"""
options = []
for d in config["devices"]:
options.append((d, "<insert description>",))
if options == []:
return config
mgmt = tui.choose("Please select a management interface", options, options[0][0])
config[... |
def unique(string: str)-> bool:
"""naive implementation, memory intensive
"""
memory = set()
for e in string:
if e in memory: return False
memory.add(e)
return True |
def get_conjunction_match_query(conjunction):
"""
Search the es pubmed index for all documents that admit the MeSH conjunction
"""
return {
'query': {
'match': {
'mesh_set': {
'query': ' '.join(conjunction),
'ana... |
def roman_to_int(s: str) -> int:
"""
roman_to_int
:param s:
:return:
"""
roman_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
'IV': 4,
'XL': 40,
'XC': 90,
'CD': 400,
'CM': 9... |
def stoi(n):
"""String to integer. Handles negative values."""
return int(str(n).replace("-", "")) * -1 if "-" in n else int(n) |
def inVolts(adc_value, bits=12, vRef=1.8):
""" Converts and returns the given ADC value to a voltage according
to the given number of bits and reference voltage. """
return adc_value*(vRef/2**bits) |
def value_check(value, ctx):
"""Return boolean result from ctx parsing."""
if not value or ctx.resilient_parsing:
return True
return False |
def p_list_tail(p, l, el=-1):
"""
qualname : qualname PERIOD name
typestmts_plus : typestmts_plus stmtdelim typestmt
arguments_plus : arguments_plus COMMA argument
dictents_plus : dictents_plus COMMA dictent
getters_plus : getters_plus... |
def usr_dtype(this_str):
"""usr_dtype: test for system `dtypes`"""
excluded = {'_root_', '_version_', '_text_', '_nest_path_'}
return not this_str in excluded |
def merge_intervals(array):
"""
return overlapping intervals
ex: [[1,6], [2,6], [8,10]] -> [[1,6],[8,10]]
O(nlog(n)) time
O(n) space
"""
array = sorted(array, key = lambda elem: elem[0])
res = []
for elem in array:
if not res or elem[0] > res[-1][1]:
res.append(elem)
else:
res[-1][1] = max(elem[1],... |
def is_static_pending_pod(pod):
"""
Return if the pod is a static pending pod
See https://github.com/kubernetes/kubernetes/pull/57106
:param pod: dict
:return: bool
"""
try:
if pod["metadata"]["annotations"]["kubernetes.io/config.source"] == "api":
return False
p... |
def round_thousands_to_1dp(value: float) -> float:
"""
Rounds values to 1dp in steps of 1000.
Rounds values greater than 1B to nearest 100M
Rounds values > 1B and >= 1M to nearest 100k
Rounds values > 1M and >= 1k to nearest 100
Rounds values less than 1000 to 1dp.
If value is not a number, ... |
def set_waiting_players_msg(waiting_players: dict):
"""
:param waiting_players:
list of players who waiting for other player to join their game.
:return:
A valid message including all games waiting for a player.
The message form is that:
players waiting count
name length, name , is fi... |
def normalize_pointer(c_type: str) -> str:
"""Remove extra space and const* qualifier."""
return c_type.replace('const*', '*').replace('const *', '*').replace(' *', '*') |
def _expand_cwdaemon_prosigns_for_winkeyer(s):
"""returns string with cwdaemon prosigns expanded for winkeyer"""
MERGE_LETTERS = "\x1b"
TABLE = {
'*': "AR",
'=': "BT",
'<': "SK",
'(': "KN",
'!': "SN",
'&': "AS",
'>': "BK"
}
rval = ... |
def _get_region(zone):
"""
Get region name from zone
:param zone: str, zone
:return:
"""
return zone if 'gov' in zone else zone[:-1] |
def xor(a_string, b_string):
"""Return a bytearray of a bytewise XOR of a_string and b_string"""
result = bytearray()
for a, b in zip(bytearray(a_string), bytearray(b_string)):
result.append(a ^ b)
return result |
def compute_ks_statistic(ks_distances):
"""
Compute the Kolmogorov-Smirnov statistic for the given Kolmogorov-Smirnov distances.
:param ks_distances: the Kolmogorov-Smirnov distances.
:return: the Kolmogorov-Smirnov statistic for the given Kolmogorov-Smirnov distances.
"""
return max(value[1] fo... |
def white_space_fix(text):
"""fix whitespace"""
return ' '.join(text.split()) |
def pascal_triangle(n):
"""
function that returns a list of lists of integers representing the Pascals
triangle of size n
Args:
n (int): How many lists
Returns:
List of lists with the integer values according to the Pascal Triangle.
"""
tri = list()
if n <= 0:
... |
def find_border_entry(positions, i, border_pt=42):
"""
Recursively search through the positions list for the first position where
the player actually moves. Return the index of that position.
"""
i = 0
while i < len(positions) - 1 and positions[i][1] < border_pt:
i += 1
return i |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary) raw structured data to process
Returns:
Dictionary. Structured data with the following schema:
{
"uid": {
"id": integer,
"name... |
def _unpacker(results_):
""" HELPER: Unpacks results if unpack_scalars is True. """
if len(results_) == 0:
results = None
else:
assert len(results_) <= 1, 'throwing away results! { %r }' % (results_,)
results = results_[0]
return results |
def frontend_ip_configuration_id(subscription_id, resource_group_name, load_balancer_name, name):
"""Generate the id for a frontend ip configuration"""
return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/frontendIPConfigurations/{}'.format(
subscription_id,
r... |
def build_pes_idx_dct(pes_dct):
""" build a dct relating index to formulat
"""
idx_dct = {}
form_dct = {}
for pes_idx, formula in enumerate(pes_dct):
idx_dct[pes_idx+1] = formula
form_dct[formula] = pes_idx+1
return idx_dct, form_dct |
def get_type(event):
"""Gets the line type for both file and report types"""
if isinstance(event, str):
if event.startswith('20'):
return 'begincast'
elif event.startswith('26'):
return 'applydebuff'
elif event.startswith('21') or event.startswith('22'):
... |
def clean_path(path):
"""
Clean both the API method path as well as the
rate_limit_status resource path in order to have exact match.
E.g.: "/geo/id/{id}.json" -> "/geo/id" <- "/geo/id/:place_id"
"""
return u'/'.join([t for t in path.rstrip('.json').split('/') \
if not (t and t[0] in ('{... |
def _accuracy(pred_data, ref_data):
"""compute sentence-level accuracy"""
pred_size = len(pred_data)
ref_size = len(ref_data)
if pred_size <= 0 or ref_size <= 0:
raise ValueError("size of predict or reference data is less than or equal to 0")
if pred_size != ref_size:
raise ValueErro... |
def startswith(string, prefixes):
"""Checks if str starts with any of the strings in the prefixes tuple.
Returns the first string in prefixes that matches. If there is no match,
the function returns None.
"""
if isinstance(prefixes, tuple):
for prefix in prefixes:
if strin... |
def change_job_name(input_lines, job_name):
"""
Change slurm job name.
"""
job_lines = []
for i, line in enumerate(input_lines):
new_line = line
if '#SBATCH --job-name' in line:
new_line = '#SBATCH --job-name=%s\n' % job_name
job_lines.append(new_line)
return ... |
def _ps(score):
""" Convenience function for score printing
"""
#s = "({0[0]:.3f}, {0[1]:.3f})".format(score)
s = "{0:.3f}".format(score)
return s |
def all_is_same(vec):
"""
Test that all elements in a vector are the same
"""
return all(el == vec[0] for el in vec) |
def to_currency(amount, add_decimal=True):
"""
Return the US currency format
"""
return '{:1,.2f}'.format(amount) if add_decimal else '{:1,}'.format(amount) |
def validate_card(DEBIT_CARD=True):
"""
The Card Reader validates the card if it can be used with ATM or not
"""
return "1234-5678-9999-000" if DEBIT_CARD else False |
def max_size_for_tile(tile, grid, tile_by_loc, rclk_rows):
""" Guess maximum size for a tile. """
tile_type = grid[tile]['type']
if tile_type == 'NULL':
return (1, 1)
# Pos X, Neg Y
base_grid_x = grid[tile]['grid_x']
base_grid_y = grid[tile]['grid_y']
# Walk up X
grid_x = base_... |
def normalize_rgb_values(color: tuple) -> tuple:
"""
Clean-up any slight color differences in PIL sampling.
:param color: a tuple of RGB color values eg. (255, 255, 255)
:returns: a tuple of RGB color values
"""
return tuple([0 if val <= 3 else 255 if val >= 253 else val for val in color]) |
def paginate_response(response, page, per_page):
"""
Paginate the incoming response json vector, accordinlgly to page and
per_page values
:param response: The whole response text
:param page: The selected page number
:param per_page: How many response record per page
:return: The number of s... |
def pix2wave(x, coeff):
"""Convert pixel to wavelength using the coefficients from the e2ds header, for a single echelle order.
Parameters
----------
x : 1d array
Pixels.
"""
w = coeff[0] + coeff[1] * x + coeff[2] * x**2 + coeff[3] * x**3
return w |
def get_pagetext_json_value(pagetext, key):
"""Return a value for a key in a JSON blob in the HTML of a page.
Args:
pagetext (string): Text to search through.
key (string): The key we want the value for.
Format: '<differentiating chars>"key"'
Note a colon would be the ne... |
def _find_best_thresh(predictions, scores, na_probs, qid_to_has_ans):
"""Find the best threshold for no answer probability."""
num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k])
cur_score = num_no_ans
best_score = cur_score
best_thresh = 0.0
qid_list = sorted(na_probs, key=lambda k: na_pro... |
def txt_cln(s):
"""prepare a string for processing in the JTMS"""
t = s.replace("'","prime-")
return t.replace("--","-") |
def username_criteria(username):
"""
Demand proper length and do not allow anything else than alphabetic characters and numbers
"""
return len(username) >= 5 and len(username) <= 20 and username.isalnum() |
def idx_to_string(val):
"""Convert index to base pair
"""
idx_to_string = {0: "A",
1: "C",
2: "G",
3: "T"}
return idx_to_string[val] |
def wrap_as_dictionary(keys, values):
""" Wrap values with respective keys into a dictionary.
# Arguments
keys: List of strings.
Values: List.
# Returns
output: Dictionary.
"""
output = dict(zip(keys, values))
return output |
def __inclst(intlst, maxval):
"""
intlst:list
array representing a number (each item is a digit)
maxval: int
max. allowed value for each item in the list, intlst
Returns
intlst incremented by 1.
"""
p=0
n=len(intlst)
while p<n:
if intlst[p]... |
def elementwise_quantile(true_val, pred_val, q):
"""The quantile loss between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
quantile_loss : float
Quantile loss, absolute er... |
def process_clinvar_field(data):
"""
>>> data = ""
>>> process_clinvar_field(data)
{}
>>> data = "CLINSIG=untested;CLNDBN=Breast-ovarian_cancer\x2c_familial_1;CLNREVSTAT=no_assertion_provided;CLNACC=RCV000112677.1;CLNDSDB=GeneReviews:MedGen:OMIM:Orphanet;CLNDSDBID=NBK1247:C2676676:60... |
def tor_to_rune(tor):
"""
1e8 Tor are 1 Rune
Format depending if RUNE > or < Zero
"""
# Cast to float first if string is float
tor = int(float(tor))
if tor == 0:
return "0 RUNE"
elif tor >= 100000000:
return "{:,} RUNE".format(int(tor / 100000000))
else:
retu... |
def factorial_iter(n: int):
"""Iteartively compute factorial of n."""
result = 1
for i in range(1, n+1):
result = result * i
return result |
def get_power_set(s):
"""
Computes the powerset lattice of a set.
:param s: A set.
:return: A powerset.
"""
power_set = [set()]
for element in s:
new_sets = []
for subset in power_set:
new_sets.append(subset | {element})
power_set.extend(new_sets)
re... |
def make_zigzag(points, num_cols):
""" Converts linear sequence of points into a zig-zag shape.
This function is designed to create input for the visualization software. It orders the points to draw a zig-zag
shape which enables generating properly connected lines without any scanlines. Please see the belo... |
def LeapYear(year):
"""
Check leap year or not
"""
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False |
def check_metric_can_be_zero(metric_name, metric_value, json_attributes):
"""
When a counter is reset, don't send a zero because it will look bad on the graphs
This checks if the zero makes sense or not
"""
if "last" in metric_name or "Last" in metric_name:
return True
if not metric_valu... |
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string) / 2) * 2
count = 0
while count < countTo:
thisVal = (source_string[count ... |
def _is_float_convertable(string) -> bool:
"""Checks whether a string can be converted into a float
http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
Args:
string: The string to check for
Returns:
True if the string is float convertable... |
def get_name(assembly_file):
""" Returns the name of the assembly based on the assembly data file"""
name_end = 0
name_start = 0
for i in range(0, len(assembly_file)):
if (
assembly_file[len(assembly_file) - i - 1: len(assembly_file) - i]
== "/"
):
nam... |
def sumDigits(digits):
"""Return the sum of all the digits in 'digits'."""
if type(digits) == type(""):
s = digits
else:
s = str(digits)
total = 0
for c in s:
total += int(c)
return total |
def merge_params(params, config):
"""Merge CLI params with configuration file params. Configuration params
will overwrite the CLI params.
"""
return {**params, **config} |
def trim_words(word_set, data_sets, num):
"""
trim words number to num
Args:
word_set: word set
data_sets: data set list
num: trim number
"""
word_dict = {}
for data in data_sets:
for word_list, _ in data:
for word in word_list:
if word... |
def vec_scale (x, alpha):
"""[Lab 14] Scales the vector x by a constant alpha."""
return [x_i*alpha for x_i in x] |
def num_str(s):
""" Tries to convert input to integer, then tries float, then complex.
If all these fails the string is returned unchanged"""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
try:
return complex(s)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.