content stringlengths 42 6.51k |
|---|
def shorten_to_len(text, max_len):
"""
Take a text of arbitrary length and split on new lines.
Keep adding whole lines until max_len is reached or surpassed.
Returns the new shorter text.
"""
shorter_text = ''
text_parts = text.split("\n")
while text_parts and len(shorter_text) < max_l... |
def av_len(ans):
"""
input:[[3, 4], 7, 9, 11, [11, 12, 13, 14], [12, 13, 14], [13, 14], 16, [16, 17, 18], [17, 18], 20, [20, 21]]
output:[[3, 4], 7, 9, [11, 12, 13, 14], [16, 17, 18], [20, 21]]
"""
true_major = ans[:]
for i in range(len(ans)):
try:
if len(ans[i]):
... |
def _validate_manifest_download(expected_objs, download_results):
"""
Given a list of expected object names and a list of dictionaries of
`SwiftPath.download` results, verify that all expected objects are in
the download results.
"""
downloaded_objs = {
r['object']
for r in downl... |
def get_party_name(party):
"""
Normalize the AP party name to our format
"""
parties = {
'GOP': 'Republican',
'Dem': 'Democrat',
'Lib': 'Libertarian',
'Grn': 'Green'
}
return parties[party] |
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')):
"""Return string as bool if possible, else raise TypeError.
>>> asbool(b' False ')
False
"""
value = value.strip().lower()
if value in true: # might raise UnicodeWarning/BytesWarning
return True
if value in fa... |
def parse_grid(lines):
"""Parse grid from lines to list of lists."""
return [list(line) for line in lines] |
def board_spacing(edges, size):
"""Calculate board spacing"""
space_x = (edges[1][0] - edges[0][0]) / float(size-1)
space_y = (edges[1][1] - edges[0][1]) / float(size-1)
return space_x, space_y |
def _ord(of_int: int) -> str:
"""For Roam"""
return str(of_int) + (
"th"
if 4 <= of_int % 100 <= 20
else {1: "st", 2: "nd", 3: "rd"}.get(of_int % 10, "th")
) |
def task4(arg4):
"""
Last task that depends on the output of the third task.
Does not return any results, as this is the last task.
"""
# Report results
pass
# End of tasks
return False |
def mouse_body_size_constants(body_scale = 1,use_old=False,use_experimental=False):
"""
Now, we make a function, which spits out the constants
"""
## HIP is a prolate ellipsoid, centered along the x axis
a_hip_min = 0.01/2 #m
a_hip_max = 0.055/2 #m
b_hip_min = 0.03/2 #m
b_hip_max = 0.035... |
def unpack_and_add(l, c):
"""Convenience function to allow me to add to an existing list
without altering that list."""
t = [a for a in l]
t.append(c)
return(t) |
def flatten(iterable):
"""Flatten a list, tuple, or other iterable so that nested iterables are combined into a single list.
:param iterable: The iterable to be flattened. Each element is also an interable.
:rtype: list
"""
iterator = iter(iterable)
try:
return sum(iterator, next(iter... |
def bytes_to_string (bytes):
"""
Convert a byte array into a string aa:bb:cc
"""
return ":".join(["{:02x}".format(int(ord(c))) for c in bytes]) |
def factorial(n):
"""Calculates factorial of a given number integer n>0."""
"""Returns None if otherwise"""
try:
if n == 0:
return 1
else:
return n * factorial(n-1)
except:
return None |
def _wrap_config_compilers_xml(inner_string):
"""Utility function to create a config_compilers XML string.
Pass this function a string containing <compiler> elements, and it will add
the necessary header/footer to the file.
"""
_xml_template = """<?xml version="1.0" encoding="UTF-8"?>
<config_compi... |
def convert_feature_coords_to_input_b_box(anchor_point_x_coord,anchor_point_y_coord,feature_to_input):
"""Convert feature map coordinates to a bounding box in the input space in a dictionary """
anchor_point_in_input_space = {
"x_centre" : anchor_point_x_coord*feature_to_input["x_scale"] + feature_to_in... |
def getPhaseEncoding(DWI,ADNI_boolean=True):
"""Returns 'AP' (the phase encoding for ADNI images). Eventually, code this to extract the PE direction from the input DWI."""
if ADNI_boolean:
pe_dir = 'AP'
else: # Extract the phase encoding direction from the DWI???
pe_dir = 'LR'
return pe_... |
def _IndentString(source_string, indentation):
"""Indent string some number of characters."""
lines = [(indentation * ' ') + line
for line in source_string.splitlines(True)]
return ''.join(lines) |
def class_from_module_path(module_path):
"""Given the module name and path of a class, tries to retrieve the class.
The loaded class can be used to instantiate new objects. """
import importlib
# load the module, will raise ImportError if module cannot be loaded
if "." in module_path:
modu... |
def escape_quotes(my_string):
"""
convert " quotes in to \"
:param my_value the string to be escaped
:return: string with escaped
"""
data = my_string.split('"')
new_string = ""
for item in data:
if item == data[-1]:
new_string = new_string + item
e... |
def vlq(value):
"""variable-len quantity as bytes"""
bts = [value & 0x7f]
while True:
value = value >> 7
if not value:
break
bts.insert(0, 0x80 | value & 0x7f)
return bytes(bts) |
def insertion_sort(L):
"""Implementation of insertion sort."""
n = len(L)
if n < 2:
return L
for i in range(1, n):
tmp = L[i]
j = i
while j > 0 and tmp < L[j - 1]:
L[j] = L[j - 1]
j -= 1
L[j] = tmp |
def retirement_plan (estimated_savings, state_costs):
"""filter out with states and their cost of living comfortably.
args:
estimated_savings(float): The customer's expected amount of savings.
state_cost: The list of available states of where the users wants to live
Q... |
def adjacency_to_edges(nodes, adjacency, node_source):
"""
Construct edges for nodes based on adjacency.
Edges are created for every node in `nodes` based on the neighbors of
the node in adjacency if the neighbor node is also in `node_source`.
The source of adjacency information would normally ... |
def get_matrix38():
"""
Return the matrix with ID 38.
"""
return [
[1.0000000, 0.5186014, 0.0000000],
[0.5186014, 1.0000000, 0.0000000],
[0.0000000, 0.0000000, 1.0000000],
] |
def _count_chunks(matches):
"""
Counts the fewest possible number of chunks such that matched unigrams
of each chunk are adjacent to each other. This is used to caluclate the
fragmentation part of the metric.
:param matches: list containing a mapping of matched words (output of allign_words)
:r... |
def get_ddy(tau, alpha_z, beta_z, g, y, dy, f):
"""
Equation [1]
:param tau: time constant
"""
return (1.0 / tau**2) * (alpha_z * (beta_z * (g - y) - tau*dy) + f) |
def is_hex_str(test_str):
"""Returns True if the string appears to be a valid hexidecimal string."""
try:
return True
except ValueError:
pass
return False |
def get_diagonals(arr):
"""returns the diagonals for a given matrix """
d1, d2 = [], []
for row in range(len(arr)):
forwardDiag = arr[row][row]
d1.append(forwardDiag)
backwardDiag = arr[row][len(arr[row]) - 1 - row]
d2.append(backwardDiag)
return d1, d2 |
def update_dependencies(new_dependencies, existing_dependencies):
"""Update the source package's existing dependencies.
When a user passes additional dependencies from the command line,
these dependencies will be added to the source package's existing dependencies.
If the dependencies passed from the c... |
def get_map_data(year, loc_dict, years_dict):
"""
Returns data needed for map creation for given year as a list.
:param year: integer, year
:param loc_dict: dictionary, keys - location strings, values - geo data
:param years_dict: dictionary, keys - years, values - film dictionaries
:return map_... |
def change_state(current_state, new_state):
"""
Change the current state dict to
reflect state param: new_state
return current_state
"""
current_state['/state'] = new_state
print("New State Set to {0}".format(current_state))
return current_state |
def cloudfront_access_control_allow_methods(access_control_allow_methods):
"""
Property: AccessControlAllowMethods.Items
"""
valid_values = ["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "ALL"]
if not isinstance(access_control_allow_methods, list):
raise TypeError("AccessContr... |
def inv_pos_item_score(i):
"""Function returns the final rank as a simple inverse of the item position.
Parameters
----------
i : int
Item position.
Returns
-------
result : float
Inverted position rank.
"""
result = 1 / i
return result |
def hamming(s1, s2):
"""Calculate the Hamming distance between two bit lists"""
assert len(s1) == len(s2)
return sum(c1 != c2 for c1, c2 in zip(s1, s2)) |
def rev(l):
"""
>>> rev([20, 13, 8, 19, 19, 4, 18, 19, 8, 18, 1, 4, 19, 19, 4, 17])
'unittestisbetter'
"""
t = ""
for c in l:
t += chr(c + 97)
return t |
def get_digit_count(number):
"""
https://stackoverflow.com/questions/2189800/length-of-an-integer-in-python
# Using log10 is a mathematician's solution
# Using len(str()) is a programmer's solution
# The mathematician's solution is O(1) [NOTE: Actually not O(1)?]
# The programmer's solution in ... |
def build_resilient_url(host, port):
"""
build basic url to resilient instance
:param host: host name
:param port: port
:return: base url
"""
if host.lower().startswith("http"):
return "{0}:{1}".format(host, port)
return "https://{0}:{1}".format(host, port) |
def check_tag(tag_token, content) :
"""
Check tag of news not in content of the news
:param tag_token:
:param content:
:return: list of tags satisfy exist in the content of news
"""
tag = tag_token.split(";")
remove = []
for tg in tag :
if tg.strip().lower().replace("_"," ") ... |
def escape_html(text: str):
"""
return escaped text
:param text: text to escape
:return:
"""
return text.replace('<', '<').replace('>', '>') |
def get_parent_directory_name(path: str) -> str:
""":returns: the path of the containing directory"""
return "/".join(path.rstrip("/").split("/")[:-1]) + "/" |
def report_error(message, value):
"""
Returns: An error message about the given value.
This is a function for constructing error messages to be used in assert
statements. We find that students often introduce bugs into their assert
statement messages, and do not find them because they a... |
def result_structure_is_valid(test_result_data):
"""
Check if the test result structure is valid. Takes a test result as input.
'name', 'value' and 'valuetype' fields are needed in the test result.
If no 'reference' is supplied, the current reference for this test is used. If it does not exist, the 're... |
def pascal_triangle(n):
"""
returns a list of lists of
integers representing the Pascal's
triangle of n
"""
if n <= 0:
return []
res = []
l = []
for i in range(n):
row = []
for j in range(i + 1):
if i == 0 or j == 0 or i == j:
row.a... |
def lorentzian(x, height, center, width):
""" defined such that height is the height when x==x0 """
halfWSquared = (width/2.)**2
return (height * halfWSquared) / ((x - center)**2 + halfWSquared) |
def int_64_to_128(val1, val2):
"""Binary join 128 bit integer from two 64bit values.
This is used for storing 128bit IP Addressses in integer format in
database. Its easier to search integer values.
Args:
val1 (int): First 64Bits.
val2 (int): Last 64Bits.
Returns:
int: IP ... |
def div42by(divideBy):
"""
Divide 42 by a parameter.
"""
try:
return 42 / divideBy
except:
print("Error! -- You tried to divide by Zero!") |
def sample_nucleotide_diversity_entity(H, D):
"""
# ========================================================================
SAMPLE NUCLEOTIDE DIVERSITY (ENTITY-LEVEL)
PURPOSE
-------
Calculates the sample nucleotide diversity.
INPUT
-----
[INT] [H]
The number of haplo... |
def knapsack_matrix(items, limit):
""" value matrix for knapsack problem
items - list(name, weight, value)
limit - maximum weight of knapsack
return matrix NxM (N - len(item) + 1, M - limit + 1 )
"""
# set zero matrix
# rows equal limit weight, columns - items
matrix = [[0]... |
def gen_key_i(i, kappa, K):
"""
Create key value where key = kappa, except for bit i:
key_(i mod n) = kappa_(i mod n) XOR K_(i mod n)
Parameters:
i -- integer in [0,n-1]
kappa -- string
K -- string
Return:
key -- list of bool
"""
# Transform string into list of booleans
kappa = list(kappa)
kap... |
def filter_times(sorted_times, filter):
"""Filters the list of times by the filter keyword. If no filter is given the
times are returned unfiltered.
Parameters
-----------
`sorted_times` : list
Collection of already sorted items, e.g. pitstops or laptimes data.
`filter` : str
Th... |
def format_time(t: float) -> str:
"""
Format a time duration in a readable format.
:param t: The duration in seconds.
:return: A human readable string.
"""
hours, remainder = divmod(t, 3600)
minutes, seconds = divmod(remainder, 60)
return '%d:%02d:%02d' % (hours, minutes, seconds) |
def str_to_bool(s):
""" Convert multiple string sequence possibilities to a simple bool
There are many strings that represent True or False connotation. For
example: Yes, yes, y, Y all imply a True statement. This function
compares the input string against a set of known strings to see if it
... |
def __tuples(a):
"""map an array or list of lists to a tuple of tuples"""
return tuple(map(tuple, a)) |
def insetRect(rect, dx, dy):
"""Inset a bounding box rectangle on all sides.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to inset the rectangle along the X axis.
dY: Amount to inset the rectangle along the Y axis.
Retur... |
def FormatTimedelta(delta):
"""Returns a string representing the given time delta."""
if delta is None:
return None
hours, remainder = divmod(delta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
return '%02d:%02d:%02d' % (hours, minutes, seconds) |
def backend_is_up(backend):
"""Returns whether a server is receiving traffic in HAProxy.
:param backend: backend dict, like one of those returned by smartstack_tools.get_multiple_backends.
:returns is_up: Whether the backend is in a state that receives traffic.
"""
return str(backend['status']).st... |
def mean(num_list):
"""
Return the average of a list of number. Return 0.0 if empty list.
"""
if not num_list:
return 0.0
else:
return sum(num_list) / float(len(num_list)) |
def calc_start(page, paginate_by, count):
"""Calculate the first number in a section of a list of objects to be displayed as a numbered list"""
if page is not None:
if page == 'last':
return paginate_by * (count / paginate_by) + 1
else:
return paginate_by * (int(page) - 1... |
def noamwd_decay(step, warmup_steps,
model_size, rate=0.5, decay_steps=1000, start_step=500):
"""Learning rate schedule optimized for huge batches
"""
return (
model_size ** (-0.5) *
min(step ** (-0.5), step * warmup_steps**(-1.5)) *
rate ** (max(step - start_step + ... |
def find_hexagon_through_edge(aHexagon_in, pEdge_in):
"""find the hexagons which contain an edge
Args:
aHexagon_in ([type]): [description]
pEdge_in ([type]): [description]
Returns:
[type]: [description]
"""
nHexagon = len(aHexagon_in)
aHexagon_out = list()
for i in... |
def get_unique_ptr(obj):
"""Read the value of a libstdc++ std::unique_ptr."""
return obj['_M_t']['_M_t']['_M_head_impl'] |
def average_housing(house_prices):
"""
Calculate the lowest average price of houses in given areas while also
ignoring the null value (-9999).
Parameters:
house_prices: A dictionary containing locations and their list
of house prices.
Returns:
The house location with the low... |
def xyz_to_lab(c: float) -> float:
"""Converts XYZ to Lab
:param c: (float) XYZ value
:return: (float) Lab value
"""
if c > 216.0 / 24389.0:
return pow(c, 1.0 / 3.0)
return c * (841.0 / 108.0) + (4.0 / 29.0) |
def split_unescape(value, delimiter = " ", max = -1, escape = "\\", unescape = True):
"""
Splits the provided string around the delimiter character that
has been provided and allows proper escaping of it using the
provided escape character.
This is considered to be a very expensive operation ... |
def intoNum(s: str) -> float:
"""
Turns string into floats.
NOTE: Fraction are automatically turned to percentages
>>> intoNum("3")
3.0
>>> intoNum("3.5")
3.5
>>> intoNum("3/5")
60.0
>>> intoNum("3.1/10")
31.0
>>> intoNum("3.1/100.0")
3.1
"""
if "/" in s:
... |
def filter_lowercase(data):
"""Converts text of all items to lowercase"""
new_data = []
for d in data:
d['article'] = d['article'].lower()
new_data.append(d)
data = new_data
return data |
def sum_squares2(n):
"""
Returns: sum of squares from 1 to n-1
Example: sum_squares(5) is 1+4+9+16 = 30
Parameter n: The number of steps
Precondition: n is an int > 0
"""
# Accumulator
total = 0
print('Before while')
x = 0
while x < n:
print('Start loo... |
def dictlist(dict_):
"""
Convert dict to flat list
"""
return [item for pair in dict_.items() for item in pair] |
def subst_string(s,j,ch):
""" substitutes string 'ch' for jth element in string """
res = ''
ls = list(s)
for i in range(len(s)):
if i == j:
res = res + ch
else:
res = res + ls[i]
return res |
def feature_array_to_string(feature_array):
"""Transforms feature array into a single string.
"""
feature_array_str = [str(x) for x in feature_array]
feature_array_str[0] = "\"" + feature_array_str[0] + "\"" # query
feature_array_str[1] = "\"" + feature_array_str[1] + "\"" # target
feature_ar... |
def rivers_with_station(stations):
"""Find rivers which have monitoring stations
Args:
stations (list): list of MonitoringStation objects
Returns:
set: contains name of the rivers with a monitoring station
"""
river_set = set()
for station in stations:
river_set.add(sta... |
def find_tx_extra_field_by_type(extra_fields, msg, idx=0):
"""
Finds given message type in the extra array, or returns None if not found
:param extra_fields:
:param msg:
:param idx:
:return:
"""
cur_idx = 0
for x in extra_fields:
if isinstance(x, msg):
if cur_idx ... |
def from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code"""
return "#%02x%02x%02x" % rgb |
def D(f, x, N):
"""
takes a function f(x), a value x, and the number N and returns the sequence for 0,N
"""
sequence = []
for i in range(N):
sequence.append((f(float(x)+(2.0**(-1 *float(i))))-f(x))/(2.0**(-1 *float(i))))
return sequence |
def union_tag(obj):
"""Get the tag of a union object."""
return next(iter(obj)) |
def globalize_query(search_query):
"""
Take the bag parts out of a search query.
"""
query = ' '.join([part for part in search_query.split()
if not part.startswith('bag:')])
return query |
def numIslands(grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
def visit_island(grid,visit,i,j):
if i >= len(grid):
return
if j >= len(grid[0]):
return
if grid[i][j] == "1" and not visit[i][j]:
visit[i][j] = 1
visit_islan... |
def get_video_dimensions(lines):
"""Has it's own function to be easier to test."""
def get_width_height(video_type, line):
dim_col = line.split(", ")[3]
if video_type != "h264":
dim_col = dim_col.split(" ")[0]
return map(int, dim_col.split("x"))
width, height = None, No... |
def count_genes_in_pathway(pathways_gene_sets, genes):
"""Calculate how many of the genes are associated to each pathway gene set.
:param dict pathways_gene_sets: pathways and their gene sets
:param set genes: genes queried
:rtype: dict
"""
return {
pathway: len(gene_set.intersection(ge... |
def get_quantized_bits_dict(bits, ibits, sign=False, mode="bin"):
"""Returns map from floating values to bit encoding."""
o_dict = {}
n_bits = bits
for b in range(1 << (bits - sign)):
v = (1.0 * b) * (1 << ibits) / (1 << bits)
if mode == "bin":
b_str = bin(b)[2:]
b_str = "0" * (n_bits - l... |
def regularize_guest_names(guest_list):
"""Regularizes the names of guest.
"""
guest_list_cp = guest_list[:]
number_of_guests = len(guest_list_cp)
for i in range(number_of_guests):
guest_list_cp[i].firstname = "Guest {}".format(i + 1)
return guest_list_cp |
def has_duplicates(t):
"""Checks whether any element appears more than once in a sequence.
Simple version using a for loop.
t: sequence
"""
d = {}
for x in t:
if x in d:
return True
d[x] = True
return False |
def listify(x):
"""Make x a list if it isn't."""
return [] if not x else (list(x) if isinstance(x, (tuple, list)) else [x]) |
def utilization_graph(utilization, warning_threshold=75, danger_threshold=90):
"""
Display a horizontal bar graph indicating a percentage of utilization.
"""
return {
'utilization': utilization,
'warning_threshold': warning_threshold,
'danger_threshold': danger_threshold,
} |
def epoch_time_standardization(epoch_time):
"""Convert the given epoch time to an epoch time in seconds."""
epoch_time_string = str(epoch_time)
# if the given epoch time appears to include milliseconds (or some other level of precision)...
# and does not have a decimal in it, add a decimal point
if ... |
def informacoes_formatada(comparacao):
""" Exibe na tela os dados de maneira formatada"""
comparacao_nome = comparacao["name"]
comparacao_descricao = comparacao["description"]
comparacao_pais = comparacao["country"]
return f"{comparacao_nome}, {comparacao_descricao}, do {comparacao_pais}" |
def intersection_list(*lists) -> list:
"""
Common elements in all given lists.
"""
l = list(set.intersection(*[set(lst) for lst in lists]))
l.sort()
return l |
def repeat(s, exclaim):
"""
return string 's' repeated 3 times
if exclaim is true ,and exclamation marks
:param s:
:param exclaim:
:return:
"""
# result = s + s + s
result = s * 3
if exclaim:
result += "! ! !"
return result |
def convert_to_wkt(geotrace):
"""Converts a Geotrace string in JavaRosa format to a WKT LINESTRING.
The JavaRosa format consists of points separated by semicolons, where each
point is given as four numbers (latitude, longitude, altitude, accuracy)
separated by spaces."""
wkt_points = []
for poi... |
def get_prod_name(product):
""" this is just a terrible hack since folder containing this product
and files have a slightly different name
"""
if product=='ASII':
product = 'ASII-TF'
return product |
def orangePurchase2(m):
"""
Calculate how many oranges can be bought with a set amount of
money. The first orange costs 1, and each subsequent exponentially costs more than the previous
(the second costs 2, the third costs 4, and so on).
:param m:total amount of money available (nb m<2,147,483,647)... |
def check_for_empty_string(input_data):
"""
Checks if data presented by a user is empty.
"""
if input_data.strip() == "":
return 'All fields are required'
return None |
def transpose_m2m(m2m_list):
""" converts single line single column to multi line double column """
ds_list, fb_list = [], []
for entry in m2m_list:
if entry == '':
continue
ds, fb = entry.split('\t')
ds_list.append(ds.strip('|').split('|'))
fb_list.append(fb.str... |
def urlsplit(url):
""" Splits a URL like "https://example.com/a/b?c=d&e#f" into a tuple:
("https", ["example", "com"], ["a", "b"], ["c=d", "e"], "f")
A trailing slash will result in a correspondingly empty final path component.
"""
split_on_anchor = url.split("#", 1)
split_on_query = split_o... |
def get_config_value(config, key, default_value, value_types, required=False, config_name=None):
"""
Parameters
----------
config: dict
Config dictionary
key: str
Config's key
default_value: str
Default value when key is absent in config
value_types: Type or List of ... |
def weaksauce_decrypt(text, password):
"""Decrypt weakly and insecurely encrypted text"""
offset = sum([ord(x) for x in password])
decoded = ''.join(
chr(max(ord(x) - offset, 0))
for x in text
)
return decoded |
def get_form_list(items):
""" """
ret = []
for item in items:
ret.append( (item.CodeKey, item.TextKey) )
return ret |
def _BuildSettingsTargetForTargets(targets):
"""Returns the singular target to use when fetching build settings."""
return targets[0] if len(targets) == 1 else None |
def command_clone(ctx, src, dest, bare=False):
""" Take in ctx to allow more configurability down the road.
"""
bare_arg = ""
if bare:
bare_arg = "--bare"
return "git clone %s '%s' '%s'" % (bare_arg, src, dest) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.