content
stringlengths 42
6.51k
|
|---|
def gcd(a,b=None):
""" Return greatest common divisor using Euclid's Algorithm.
a - can be either an integer or a list of integers
b - if 'a' is an integer, 'b' should also be one. if 'a' is a list, 'b' should be None
"""
if (b == None):
if (a == []):
return 1
g = a[0]
for i in range(1, len(a)):
g = gcd(g, a[i])
return g
else:
while b:
a, b = b, a % b
return a
|
def group_blocks_into_fills(blocks, max_size, min_size=(0, 0, 0)):
"""
A 'good enough' function that groups similar blocks into fills where possible.
`blocks` is an array of (x, y, z, name) tuples where `name` can be any type that defines a
block (eg. if all the blocks are the same then `name` could just be `True`). `max_size` is a
voxel tuple defining the size of the volume the blocks are bound by. If blocks have negative
voxels `min_size` is used to define the minimum bounds of the volume - eg. two blocks (1, 1, 1)
and (-1, -1, -1) would be bound by `min_size=(-1, -1, -1)` and `max_size=(2, 2, 2)`.
An array of ((min_x, min_y, min_z), (max_x, max_y, max_z), name) tuples is returned. If a block
couldn't be grouped then the min and max voxels will be equivalent.
"""
# create ranges for iterating over the volume occupied by the block (indexed from 0)
range_x, range_y, range_z = [
range(max_coord - min_coord) for min_coord, max_coord in zip(min_size, max_size)
]
# initialise a 3D array with block values
volume = [[[None for z in range_z] for y in range_y] for x in range_x]
min_size_x, min_size_y, min_size_z = min_size
for x, y, z, name in blocks:
volume[x - min_size_x][y - min_size_y][z - min_size_z] = name
def group_blocks(min_x, min_y, min_z):
"""
From a particular block within the volume, try to match with adjacent (and higher) matching
blocks to form a fill which is returned. At a minimum the block itself is returned.
Any blocks returned are removed from the volume.
"""
# this is the block to match
name = volume[min_x][min_y][min_z]
# group all matching contiguous blocks in the `x` direction
max_x = min_x + 1
while max_x in range_x and volume[max_x][min_y][min_z] == name:
max_x += 1
# group all matching contiguous blocks in the `y` direction
max_y = min_y + 1
while max_y in range_y:
match = all(
volume[x][max_y][min_z] == name
for x in range(min_x, max_x)
)
if not match:
break
max_y += 1
# group all matching contiguous blocks in the `z` direction
max_z = min_z + 1
while max_z in range_z:
match = all(
volume[x][y][max_z] == name
for x in range(min_x, max_x)
for y in range(min_y, max_y)
)
if not match:
break
max_z += 1
# Remove the grouped blocks from the volume.
for x in range(min_x, max_x):
for y in range(min_y, max_y):
for z in range(min_z, max_z):
volume[x][y][z] = None
return (
(min_size_x + min_x, min_size_y + min_y, min_size_z + min_z),
(min_size_x + max_x - 1, min_size_y + max_y - 1, min_size_z + max_z - 1),
name
)
# iterate over the volume in an ascending direction and when a block is encountered, try to
# group it with blocks in the same direction to form a fill.
fills = []
for x in range_x:
for y in range_y:
for z in range_z:
if volume[x][y][z]:
fills.append(group_blocks(x, y, z))
return fills
|
def how_much_to_go(current_level):
""" Calculates the number of points the user needs to obtain to advance
levels based on their current level
Args:
current_level::int
The users current level
Returns:
to_go_points::int
The number of points the user needs to gain in order to move onto
the next level
"""
if current_level < 9:
# transforming the current_level which is a float into an int
int_value = int(current_level)
# adding 1 to the int value to get the next threshold
# take away from the next threshold the current level
# this will give the level missing to go to the next threshold
to_go_level = (int_value+1) - current_level
# multiplying it by the 50 (this value has to be the same as the
# divider in the function check_points_treshold)
# this gives the number of points to go before the next treshold
to_go_points = to_go_level*50
else:
to_go_points = 0
return to_go_points
|
def isbn_gendigit (numStr):
"""
(string)-->(string + 1-digit)
Generates the 10th digit in a given 9-digit isbn string. Multiplies the values of individual digits within the given 9-digit string to determine the 10th digit.
Prints the original string with its additional 10th digit. Prints X for the 10th digit if the value of isbn_mathremainder is 10.
('123456788')-->1234567881
('123456789')-->123456789X
"""
if (len(numStr)) == 9:
isbn_math = sum([(int(numStr[i])*(i+1)) for i in range(0,9)])
isbn_mathremainder = (isbn_math % 11)
if isbn_mathremainder == 10:
print ('ISBN 10-digit: ', str(numStr) + 'X')
return (str(numStr) + 'X')
else:
print ('ISBN 10-digit: ', str(numStr) + str(isbn_mathremainder))
return (str(numStr) + str(isbn_mathremainder))
else:
print ('unacceptable')
return None
|
def _splitquery(url):
"""splitquery('/path?query') --> '/path', 'query'."""
path, delim, query = url.rpartition('?')
if delim:
return path, query
return url, None
|
def check_for_horseshoe(farm, n_var, m_var, horseshoe) -> int:
"""Brute-froces the farm to find possible horseshoe places"""
found = 0
row = 0
col = 0
horseshoe_length = len(horseshoe)
while row < n_var:
# check if we can separate a 3x3 square:
if (
row + horseshoe_length <= n_var
and col + horseshoe_length <= m_var
):
can_fit_horseshoe = True
for i in range(horseshoe_length):
for j in range(horseshoe_length):
# print(f"row:{row}, col:{col}, i:{i}, j:{j}")
if (
horseshoe[i][j] == "*"
and farm[row + i][col + j] == "."
):
can_fit_horseshoe = False
break
if not can_fit_horseshoe:
break
if can_fit_horseshoe and i == horseshoe_length - 1:
found += 1
col += 1
if col >= m_var:
col = 0
row += 1
return found
|
def _cmp_zorder(lhs, rhs) -> bool:
"""Used to check if two values are in correct z-curve order.
Based on https://github.com/google/neuroglancer/issues/272#issuecomment-752212014
Args:
lhs: Left hand side to compare
rhs: Right hand side to compare
Returns:
bool: True if in correct z order
"""
def less_msb(x: int, y: int) -> bool:
return x < y and x < (x ^ y)
# Assume lhs and rhs array-like objects of indices.
assert len(lhs) == len(rhs)
# Will contain the most significant dimension.
msd = 2
# Loop over the other dimensions.
for dim in [1, 0]:
# Check if the current dimension is more significant
# by comparing the most significant bits.
if less_msb(lhs[msd] ^ rhs[msd], lhs[dim] ^ rhs[dim]):
msd = dim
return lhs[msd] - rhs[msd]
|
def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Celsius and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
>>> rankine_to_celsius(273.354, 3)
-121.287
>>> rankine_to_celsius(273.354, 0)
-121.0
>>> rankine_to_celsius(273.15)
-121.4
>>> rankine_to_celsius(300)
-106.48
>>> rankine_to_celsius("315.5")
-97.87
>>> rankine_to_celsius("rankine")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'rankine'
"""
return round((float(rankine) - 491.67) * 5 / 9, ndigits)
|
def _int_to_bytes(n):
"""Takes an integer and returns a byte-representation"""
return n.to_bytes((n.bit_length() + 7) // 8, 'little') or b'\0'
# http://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes
|
def convert_mb_to_b(size):
"""
Convert value from MB to B for the given size variable.
If the size is a float, the function will convert it to int.
:param size: size in MB (float or int).
:return: size in B (int).
:raises: ValueError for conversion error.
"""
try:
size = int(size)
except Exception as e:
raise ValueError('cannot convert %s to int: %s' % (str(size), e))
return size * 1024 ** 2
|
def parse_components(components, trans_to_range):
"""Get genes data.
Each gene has the following data:
1) It's ID
2) Included transcripts
3) Genic range.
"""
genes_data = []
for num, component in enumerate(components, 1):
gene_id = f"reg_{num}"
# get transcripts and their ranges
transcripts = set(component.nodes())
regions = [trans_to_range[t] for t in transcripts]
# define gene range, chrom and strand are same everywhere
# just get them from the 0'st region
reg_0 = regions[0]
gene_chrom = reg_0[0]
gene_strand = reg_0[1]
# start and end -> just min of starts and max of ends
starts = [r[2] for r in regions]
ends = [r[3] for r in regions]
gene_start = min(starts)
gene_end = max(ends)
# pack everything
gene_range = (gene_chrom, gene_strand, gene_start, gene_end)
gene_data = {"ID": gene_id, "range": gene_range, "transcripts": transcripts}
genes_data.append(gene_data)
return genes_data
|
def check_validity(passport):
"""Check if a passport is valid."""
return len(passport) == 8 or len(passport) == 7 and "cid" not in passport
|
def generate_filename(in_path, out_dir, bitrate, encoder):
"""
Create a new filename based on the original video file and test bitrate.
Parameters
----------
in_path : str
Full path of input video.
out_dir : str
Directory of output video.
bitrate : int
Video bitrate in kbit/s.
encoder : str
Encoder for FFmpeg to use.
Returns
-------
out_path : str
Full path of new output video.
"""
if in_path.count('.') >= 2:
raise Exception('Filename has multiple full stops')
out_video = in_path.split(
'/')[-1].replace('.', f'_{encoder}_{int(bitrate)}.')
out_path = out_dir + out_video
return out_path
|
def partition(A, p, r):
"""
Quicksort supporting algorithm.
"""
q = p
for u in range(p, r):
if A[u] <= A[r]:
A[q],A[u] = A[u],A[q]
q += 1
A[q],A[r] = A[r],A[q]
return q
|
def virial_mass(FWHM, vel_disp):
"""
Calculates the Vyrial Theorem based Dynamical mass
FWHM is the deconvolved size of the source in pc
vel_disp is the velocity dispersion in km/s
http://adsabs.harvard.edu/abs/2018arXiv180402083L
Leroy et al 2018
"""
M = 892. * FWHM * (vel_disp**2.)
return M
|
def get_type(data):
"""
@param data: rosdoc manifest data
@return 'stack' of 'package'
"""
return data.get('package_type', 'package')
|
def post(post_id):
"""
get post page url
:param post_id: int
:return: string
"""
return "http://www.vanpeople.com/c/" + str(post_id) + ".html"
|
def count_number_fishers_alive(dict_fishers,gamerunning):
"""
This function , count the number of fishers alive in the island, if is 1 the number of players
alive and the game is running, he catch the number, and form a message of the winner, otherwise
,return just return the number of players
@param dict_fishers:(dictionary of fishers objects) a dictionary of all the fishers present on game
@param gamerunning:(int) indicate if the number of players is bigger or equal 2(1), and gamming is runing
,otherwise game waits for beggin(0).
@return:(str or int), a message with the winner game, or the number of players otherwise
"""
if(gamerunning == 1):
if(len(dict_fishers) >= 2):
return len(dict_fishers)
elif(len(dict_fishers) == 1):
answer = ""
for key, objfisher in dict_fishers.items():
answer = objfisher.getName()
return "The winner of game section is "+answer+" , Congratulations!!!, the game is over!!!\n"
else:
return "Sorry all the players are dead, more luck in the next round, ;) \n"
else:
return len(dict_fishers)
|
def xy_data(dataset, variable):
"""X-Y line/circle data related to a dataset"""
# import time
# time.sleep(5) # Simulate expensive I/O or slow server
if dataset == "takm4p4":
return {
"x": [0, 1e5, 2e5],
"y": [0, 1e5, 2e5]
}
else:
return {
"x": [0, 1e5, 2e5],
"y": [0, 3e5, 1e5]
}
|
def create_distance_data(distances: list):
"""
:param distances: list of Distance objects
:return: array of distance values, array of id values
"""
ids = []
values = []
for dist in distances:
ids.append(dist._id)
values.append(dist.value)
return values, ids
|
def mark_code_blocks(txt, keyword='>>>', split='\n', tag="```", lang='python'):
"""
Enclose code blocks in formatting tags. Default settings are consistent with
markdown-styled code blocks for Python code.
Args:
txt: String to search for code blocks.
keyword(optional, string): String that a code block must start with.
split(optional, string): String that a code block must end with.
tag(optional, string): String to enclose code block with.
lang(optional, string) : String that determines what programming
language is used in all code blocks. Set this to '' to disable
syntax highlighting in markdown.
Returns:
string: A copy of the input with code formatting tags inserted (if any
code blocks were found).
"""
import re
blocks = re.split('^%s' % split, txt, flags=re.M)
out_blocks = []
for block in blocks:
lines = block.split(keyword)
match = re.findall(r'(\s*)(%s[\w\W]+)' % keyword,
keyword.join(lines[1:]), re.M)
if match:
before_code = lines[0]
indent = match[0][0]
indented_tag = '%s%s' % (indent, tag)
code = '%s%s' % (indent, match[0][1])
out_blocks.append('%s%s%s\n%s%s' % (before_code, indented_tag,
lang, code, indented_tag))
else:
out_blocks.append(block)
return split.join(out_blocks)
|
def countSuccess( successList, failList ):
"""Intended to be used with 'renewsliver', 'deletesliver', and
'shutdown' which return a two item tuple as their second
argument. The first item is a list of urns/urls for which it
successfully performed the operation. The second item is a
list of the urns/urls for which it did not successfully
perform the operation. Failure could be due to an actual
error or just simply that there were no such resources
allocated to this sliver at that aggregates. In this context
this method returns a tuple containing the number of items
which succeeded and the number of items attempted.
"""
succNum = len( successList )
return (succNum, succNum + len( failList ) )
|
def prime(n, primes):
"""Return True if a given n is a prime number, else False."""
if n > 5 and n % 10 == 5:
return False
for p in primes:
if n % p == 0:
return False
return True
|
def intersect(tup1, tup2):
"""
Return the common interval between tup1 and tup2.
"""
return (max(tup1[0], tup2[0]), min(tup1[1], tup2[0]))
|
def parseSysfsValue(key, value):
""" Parse the sysfs value string
Parameters:
value -- SysFS value to parse
Some SysFS files aren't a single line/string, so we need to parse it
to get the desired value
"""
if key == 'id':
# Strip the 0x prefix
return value[2:]
if key == 'temp':
# Convert from millidegrees
return int(value) / 1000
if key == 'power':
# power1_average returns the value in microwatts. However, if power is not
# available, it will return "Invalid Argument"
if value.isdigit():
return float(value) / 1000 / 1000
return ''
|
def _fix_missing_period(line):
"""
Adds a period to a line that is missing a period.
"""
dm_single_close_quote = u'\u2019'
dm_double_close_quote = u'\u201d'
END_TOKENS = [
'.',
'!',
'?',
'...',
"'",
"`",
'"',
dm_single_close_quote,
dm_double_close_quote,
")",
] # acceptable ways to end a sentence
if "@highlight" in line or line == "" or line[-1] in END_TOKENS:
return line
return line + "."
|
def intersect_lists(l1, l2):
"""Returns the intersection of two lists. The result will not contain
duplicate elements and list order is not preserved."""
return list(set(l1).intersection(set(l2)))
|
def extract_chat_id(body):
"""
Obtains the chat ID from the event body
Parameters
----------
body: dic
Body of webhook event
Returns
-------
int
Chat ID of user
"""
if "edited_message" in body.keys():
chat_id = body["edited_message"]["chat"]["id"]
else:
chat_id = body["message"]["chat"]["id"]
return chat_id
|
def selection_sort(array):
"""
Selection sort algorithm.
:param array: the array to be sorted.
:return: sorted array
>>> import random
>>> array = random.sample(range(-50, 50), 100)
>>> selection_sort(array) == sorted(array)
True
"""
for i in range(0, len(array) - 1):
min_index = i
for j in range(i + 1, len(array)):
if array[j] < array[min_index]:
min_index = j
if min_index != i:
array[i], array[min_index] = array[min_index], array[i]
return array
|
def output_pins(pins):
"""
:param pins: dictionary of all pins, input and output
:return: dictionary of pins configured as output
"""
outputs = {}
for key in pins.keys():
if pins[key]['pin_direction'] == 'output':
outputs[key] = pins[key]
return outputs
|
def start_from(year, starting_year):
"""[Returns the years from the first publication of the book]
Args:
year ([str]): [Year of the book]
starting_year ([str]): [Year of pulication of the first book of the serie]
Returns:
[int]: [Years since the publication of the first book of the serie]
"""
return int(year)-int(starting_year)
|
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
try:
if number < 0 :
return 'complex numbers not supported'
elif number >= 0:
return int(number**(1/2))
except:
return 'data type not supported'
|
def product(A,B):
"""Takes two sets A and B, and returns their
cartesian product as a set of 2-tuples."""
product = set()
for x in A:
for y in B:
product.add((x,y))
"""Now it is time to return the result"""
return product
|
def strategy(history, alivePlayers, whoami, memory):
"""
history contains all previous rounds (key : id of player (shooter), value : id of player (target))
alivePlayers is a list of all player ids
whoami is your own id (to not kill yourself by mistake)
memory is None by default and transferred over (if you set it to 1, it will be 1 in the next round)
memory is NOT shared between games (subject to changes)
"""
# Your code would be here but this strategy is dumb...
"""
You must return an id of a player (if not : you shoot in the air)
Memory must be set to something but can be anything (None included )
"""
return alivePlayers[0], None
|
def list_to_text(what_to_show_):
"""converts list to text to use in plottitle
Args:
what_to_show_ (list with strings): list with the fields
Returns:
string: text to use in plottitle
"""
what_to_show_ = what_to_show_ if type(what_to_show_) == list else [what_to_show_]
w = ""
for w_ in what_to_show_:
if w_ == what_to_show_[-1]:
w += w_
elif w_ == what_to_show_[-2]:
w += w_ + " & "
else:
w += w_ + ", "
return w
|
def parse_version(version):
"""Parse version string and return version date integer."""
try:
if "-" in version:
return int(version.split("-", 1)[0])
except TypeError:
return version
|
def normalize_course_id(course_id):
"""Make course_id directory naming name worthy
convert:
from: course-v1:course+name
to: course_name
"""
return course_id.split(":")[1].replace("+", "_")
|
def is_key_valid(key):
"""
Return True if a key is valid
"""
if len(key) < 8:
print()
print('The master key should be at least 8 characters. Please try again!')
print()
return False
return True
|
def Nv_for_nuclide(nuclide):
"""Calculate oscillator quantum number of valence shell for given nuclide.
Arguments:
nuclide (tuple): (Z,N) for nuclide
Returns:
Nv (int): oscilllator quantum number for valence shell
"""
# each major shell eta=2*n+l (for a spin-1/2 fermion) contains (eta+1)*(eta+2) substates
Nv = 0
for species_index in (0,1):
num_particles = nuclide[species_index]
eta=0
while(num_particles>0):
# discard particles in shell
shell_degeneracy = (eta+1)*(eta+2)
num_particles_in_shell = min(num_particles,shell_degeneracy)
num_particles -= num_particles_in_shell
# update Nv
Nv = max(Nv, eta)
# move to next shell
eta += 1
return Nv
|
def class_fullname(obj):
"""Returns the full class name of an object"""
return obj.__module__ + "." + obj.__class__.__name__
|
def decay_value(base_value, decay_rate, decay_steps, step):
""" decay base_value by decay_rate every decay_steps
:param base_value:
:param decay_rate:
:param decay_steps:
:param step:
:return: decayed value
"""
return base_value*decay_rate**(step/decay_steps)
|
def count_binary_ones(number):
"""
Returns the number of 1s in the binary representation of number (>=0)
For e.g 5 returns 2 (101 has 2 1's), 21 returns 3 ("10101")
"""
# Use only builtins to get this done. No control statements plz
return bin(number)[2:].count("1")
|
def convert_message(content, id):
""" Strip off the useless sf message header crap """
if content[:14] == 'Logged In: YES':
return '\n'.join(content.splitlines()[3:]).strip()
return content
|
def sum_value(values, period=None):
"""Returns the final sum.
:param values: list of values to iterate.
:param period: (optional) # of values to include in computation.
* None - includes all values in computation.
:rtype: the final sum.
Examples:
>>> values = [34, 30, 29, 34, 38, 25, 35]
>>> result = sum_value(values, 3) #using 3 period window.
>>> print "%.2f" % result
98.00
"""
if not values:
return None
maxbar = len(values)
beg = 0
if period:
if period < 1:
raise ValueError("period must be 1 or greater")
beg = maxbar - int(period)
if beg < 0:
beg = 0
return sum(values[beg:])
|
def get_comma_separated_values(values):
"""Return the values as a comma-separated string"""
# Make sure values is a list or tuple
if not isinstance(values, list) and not isinstance(values, tuple):
values = [values]
return ','.join(values)
|
def invert_dict(d):
"""unvert dict"""
inverse = dict()
for key in d:
# Go through the list that is saved in the dict:
for item in d[key]:
# Check if in the inverted dict the key exists
if item not in inverse:
# If not create a new list
inverse[item] = key
else:
inverse[item].append(key)
return inverse
|
def get_ue_sla(ue_throughput, ue_required_bandwidth):
"""
Function to calculate UE's SLA
"""
return int(ue_throughput >= ue_required_bandwidth)
|
def is_ascii(s):
"""Checks if text is in ascii.
Thanks to this thread on StackOverflow: http://stackoverflow.com/a/196392/881330
"""
return all(ord(c) < 256 for c in s)
|
def adjust_learning_rate(learning_rate, epoch, step=20):
"""Sets the learning rate to the initial LR decayed by 10 every 10 epochs"""
lr = learning_rate * (1 ** (epoch // step))
return lr
|
def totalcost(endclasses):
"""
Tabulates the total expected cost of given endlcasses from a run.
Parameters
----------
endclasses : dict
Dictionary of end-state classifications with 'expected cost' attributes
Returns
-------
totalcost : Float
The total expected cost of the scenarios.
"""
return sum([e['expected cost'] for k,e in endclasses.items()])
|
def highest_occurrence(array):
"""
Time: O(n)
Space: O(n)
:param array: strings, int or floats, can be mixed
:return: array containing element(s) with the highest
occurrences without type coercion.
Returns an empty array if given array is empty.
"""
# hash table with a count of each item in the array
counted = {}
for item in array:
if item in counted.keys():
counted[item] += 1
else:
counted[item] = 1
frequencies = counted.values()
highest_frequency = max(frequencies, default="")
most_frequent = [item for item in counted if counted[item] == highest_frequency]
return most_frequent
|
def get_version_mapping_directories(server_type):
"""
This function will return all the version mapping directories
:param server_type:
:return:
"""
if server_type == 'gpdb':
return (
{'name': "gpdb_5.0_plus", 'number': 80323},
{'name': "5_plus", 'number': 80323},
{'name': "default", 'number': 0}
)
return ({'name': "12_plus", 'number': 120000},
{'name': "11_plus", 'number': 110000},
{'name': "10_plus", 'number': 100000},
{'name': "9.6_plus", 'number': 90600},
{'name': "9.5_plus", 'number': 90500},
{'name': "9.4_plus", 'number': 90400},
{'name': "9.3_plus", 'number': 90300},
{'name': "9.2_plus", 'number': 90200},
{'name': "9.1_plus", 'number': 90100},
{'name': "9.0_plus", 'number': 90000},
{'name': "default", 'number': 0})
|
def isGifv(link):
""" Returns True if link ends with video suffix """
return link.lower().endswith('.gifv')
|
def multis_2_mono(table):
"""
Converts each multiline string in a table to single line.
Parameters
----------
table : list of list of str
A list of rows containing strings
Returns
-------
table : list of lists of str
"""
for row in range(len(table)):
for column in range(len(table[row])):
table[row][column] = table[row][column].replace('\n', ' ')
return table
|
def parse_header(elements) -> dict:
"""
Parse headers from nodes TSV
Parameters
----------
elements: list
The header record
Returns
-------
dict:
A dictionary of node header names to index
"""
header_dict = {}
for col in elements:
header_dict[col] = elements.index(col)
return header_dict
|
def _GetNestedKeyFromManifest(manifest, *keys):
"""Get the value of a key path from a dict.
Args:
manifest: the dict representation of a manifest
*keys: an ordered list of items in the nested key
Returns:
The value of the nested key in the manifest. None, if the nested key does
not exist.
"""
for key in keys:
if not isinstance(manifest, dict):
return None
try:
manifest = manifest[key]
except KeyError:
return None
return manifest
|
def _wayback_timestamp(**kwargs):
"""Return a formatted timestamp."""
return "".join(
str(kwargs[key]).zfill(2) for key in ["year", "month", "day", "hour", "minute"]
)
|
def solver_problem2(input_list):
"""walk through the route and return aim"""
horizon = 0
depth = 0
aim = 0
for direction, distance in input_list:
if direction == "forward":
horizon += distance
depth = depth + aim * distance
elif direction == "down":
aim += distance
elif direction == "up":
aim -= distance
return horizon * depth
|
def get_attachment_name(attachment_name):
"""
Retrieve attachment name or error string if none is provided
:param attachment_name: attachment name to retrieve
:return: string
"""
if attachment_name is None or attachment_name == "":
return "demisto_untitled_attachment"
return attachment_name
|
def cardLuhnChecksumIsValid(card_number):
""" checks to make sure that a number passes a luhn mod-10 credit card checksum """
card_number = ''.join(card_number.split()) # remove all whitespace
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not (( count & 1 ) ^ oddeven ):
digit = digit * 2
if digit > 9:
digit = digit - 9
sum = sum + digit
return ( (sum % 10) == 0 )
|
def _get_masks(tokens, max_seq_length):
"""Mask for padding"""
if len(tokens) > max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens) + [0] * (max_seq_length - len(tokens))
|
def strip_domain_address(ip_address):
""" Strip domain from ip address """
mask_index = ip_address.find('/')
if mask_index > 0:
return ip_address[:mask_index].split('%')[0] + ip_address[mask_index:]
else:
return ip_address.split('%')[0]
|
def count_all(obj):
"""
Return the number of elements in obj or sublists of obj if obj is a list.
Otherwise, if obj is a non-list return 1.
@param object|list obj: object to count
@rtype: int
>>> count_all(17)
1
>>> count_all([17, 17, 5])
3
>>> count_all([17, [17, 5], 3])
4
"""
if not isinstance(obj, list):
return 1
elif obj == []:
return 0
else:
return sum([count_all(item) for item in obj])
|
def list_of_lists(string):
"""list_of_list
Parse a string of the form "1,2,3 4,3,2 ..."
:param string:
"""
if string:
return [float(x) for x in string.strip().split(",")]
else:
return string
|
def get_gender(gender: str) -> str:
"""
:param gender:
:return:
"""
gen = 'male'
if gender == "0":
gen = 'male'
elif gender == "1":
gen = 'female'
elif gender == "2":
gen = "d"
else:
raise IndexError("Unknown gender-index: " + gender)
return gen
|
def get_sequence_header_length(seq_header_len):
"""Returns length of SEQUENCE header."""
if seq_header_len > 255:
return 4
if seq_header_len > 127:
return 3
return 2
|
def lower_case(s):
"""Transforms an input string into its lower case version.
Args:
s (str): Input string.
Returns:
Lower case of 's'.
"""
return s.lower()
|
def escape_codepoints(codepoint):
"""Skip the codepoints that cannot be encoded directly in JSON.
"""
if codepoint == 34:
codepoint += 1 # skip "
elif codepoint == 92:
codepoint += 1 # Skip backslash
return codepoint
|
def isint(num):
"""Test whether a number is *functionally* an integer"""
try:
int(num) == float(num)
except ValueError:
return False
return True
|
def shallow_copy_as_ordinary_list(iterable):
"""Return a simple list that is a shallow copy of the given iterable.
NOTE: This is needed because "copy.copy(x)" returns an SqlAlchemy
InstrumentedList when the given 'x' is such. Then, operations on the
instrumented copy (e.g., remove) cause SqlA-side-effects on the copied
(managed) objects.
"""
shallow_copy_list = []
for x in iterable:
shallow_copy_list.append(x)
return shallow_copy_list
|
def div(html:str)->str:
"""wrap an html snippet in a <div></div>"""
return f'<div>{html}</div>'
|
def get_locus_blocks(glstring):
"""
Take a GL String, and return a list of locus blocks
"""
# return re.split(r'[\^]', glstring)
return glstring.split('^')
|
def calculate_symmetric_kl_divergence(p, q, calculate_kl_divergence):
""" This function calculates the symmetric KL-divergence between
distributions p and q. In particular, it defines the symmetric
KL-divergence to be:
.. math::
D_{sym}(p||q) := \frac{D(p||q) + D(p||p)}{2}
Args:
p, q: a representation of a distribution that can be used by the
function ``calculate_kl_divergence"
calculate_kl_divergence: a function the calculates the KL-divergence
between :math:`p` and :math:`q`
Returns:
float: the symmetric KL-divergence between :math:`p` and :math:`q`
"""
kl_1 = calculate_kl_divergence(p, q)
kl_2 = calculate_kl_divergence(q, p)
symmetric_kl = (kl_1 + kl_2) / 2
return symmetric_kl
|
def marked(obj):
"""Whether an object has been marked by spack_yaml."""
return (hasattr(obj, '_start_mark') and obj._start_mark or
hasattr(obj, '_end_mark') and obj._end_mark)
|
def type_match(haystack, needle):
"""Check whether the needle list is fully contained within the haystack
list, starting from the front."""
if len(needle) > len(haystack):
return False
for idx in range(0, len(needle)):
if haystack[idx] != needle[idx]:
return False
return True
|
def invert_yang_modules_dict(in_dict: dict, debug_level: int = 0):
"""
Invert the dictionary of
key:RFC/Draft file name,
value:list of extracted YANG models
into a dictionary of
key:YANG model,
value:RFC/Draft file name
Arguments:
:param in_dict (dict) input dictionary
:param debug_level (int) debug level; If > 0 print some debug statements to the console
:return: inverted output dictionary
"""
if debug_level > 0:
print('DEBUG: invert_yang_modules_dict: dictionary before inversion:\n{}'.format(str(in_dict)))
inv_dict = {}
for key, value in in_dict.items():
for yang_model in in_dict[key]:
inv_dict[yang_model] = key
if debug_level > 0:
print('DEBUG: invert_yang_modules_dict: dictionary after inversion:\n{}'.format(str(inv_dict)))
return inv_dict
|
def get_nested_item(d, list_of_keys):
"""Returns the item from a nested dictionary. Each key in list_of_keys is
accessed in order.
Args:
d: dictionary
list_of_keys: list of keys
Returns: item in d[list_of_keys[0]][list_of_keys[1]]...
"""
dct = d
for i, k in enumerate(list_of_keys):
assert (
k in dct
), f"Key {k} is not in dictionary after seeing {i + 1} keys from {list_of_keys}"
dct = dct[k]
return dct
|
def CRL_focalpoint(energy,lens_configuration):
"""
CRL_focalpoint(energy,lens_configuration):
lens_confguration is a dictionary of the form
[lens_radius1:numer lenses, lens_radius2: number_lenses, ...]
returns the focal length
"""
focal_distance=0.0
return focal_distance
|
def column_names_window(columns: list, window: int) -> list:
"""
Parameters
----------
columns: list
List of column names
window: int
Window size
Return
------
Column names with the format: w_{step}_{feature_name}
"""
new_columns = []
for w in range(1, window + 1):
for c in columns:
new_columns.append(f"w_{w}_{c}")
return new_columns
|
def titlecase(input_str):
"""Transforms a string to titlecase."""
return "".join([x.title() for x in input_str.split('_')])
|
def _get_effective_padding_node_input(stride, padding, effective_padding_output):
"""Computes effective padding at the input of a given layer.
Args:
stride: Stride of given layer (integer).
padding: Padding of given layer (integer).
effective_padding_output: Effective padding at output of given layer
(integer).
Returns:
effective_padding_input: Effective padding at input of given layer
(integer).
"""
return stride * effective_padding_output + padding
|
def get_range(min_val, max_val):
"""
Returns a range of values
"""
return range(min_val, max_val)
|
def any_in(a_set, b_set):
"""
Boolean variable that is ``True`` if elements in a given set `a_set` intersect
with elements in another set `b_set`. Otherwise, the boolean is ``False``.
Parameters
___________
a_set : list
First set of elements.
b_set : list
Second set of elements.
Returns
________
not set(a_set).isdisjoint(b_set) : bool
Boolean that is ``True`` if there is a non-empty intersection between both sets.
Otherwise, the boolean is ``False``.
"""
return not set(a_set).isdisjoint(b_set)
|
def check_compatibility(test_stem, reference_stems, compatibility_matrix):
""" Checks if a given test stem is compatible with stems in another set of reference stems
When folding RNA by adding stems, this function can used be to check if the added stem crosses or overlaps
the stems already present in the RNA
"""
compatible = True
for stem in reference_stems:
if compatibility_matrix[stem, test_stem] == 0:
compatible = False
break
return(compatible)
|
def get_dihedrals(bonds):
""" Iterate through bonds to get dihedrals.
Bonds should contain no duplicates.
"""
dihedrals = []
for i1, middle_bond in enumerate(bonds):
atom1, atom2 = middle_bond
atom1_bonds, atom2_bonds = [], []
for i2, other_bond in enumerate(bonds):
if atom1 in other_bond:
atom1_bonds.append(other_bond)
elif atom2 in other_bond:
atom2_bonds.append(other_bond)
for bond1 in atom1_bonds:
for bond2 in atom2_bonds:
atom0 = [b for b in bond1 if b != atom1][0]
atom3 = [b for b in bond2 if b != atom2][0]
dihedral = (min(atom0,atom3), atom1, atom2, max(atom0,atom3))
# Make sure dihedral is not a loop
if len(set(dihedral)) == 4:
dihedrals.append(tuple(dihedral))
return sorted(dihedrals)
|
def city_functions(city, country, population=''):
"""Generate a neatly formatted city."""
if population:
return (city.title() + ', ' + country.title() + ' - population ' +
str(population) + '.')
return city.title() + ', ' + country.title() + '.'
|
def first_index(lst, predicate):
"""Return the index of the first element that matches a predicate.
:param lst: list to find the matching element in.
:param predicate: predicate object.
:returns: the index of the first matching element or None if no element
matches the predicate.
"""
for i in range(len(lst)):
if predicate(lst[i]):
return i
return None
|
def memoized(cache, f, arg):
"""Memoizes a call to `f` with `arg` in the dict `cache`.
Modifies the cache dict in place."""
res = cache.get(arg)
if arg in cache:
return cache[arg]
else:
res = f(arg)
cache[arg] = res
return res
|
def temp_validation(value):
"""
:param value: temperature value given by the system
:return: Boolean
"""
min_value = 0
max_value = 45
return True if (value > min_value) and (value < max_value) else False
|
def dim_returns(k, inverse_scale_factor):
"""
A simple utility calculation method.
Given k items in posession return the benefit of a K + 1th item given some
inverse scale factor.
The formula used is utility = 100% if no items are in posession or
utility = 1 / inverse_scale_factor * (k + 1)
"""
if k == 0:
return 1;
return (1 / (inverse_scale_factor * (k + 1)))
|
def addtime(output, unit, t):
"""add a formatted unit of time to an accumulating string"""
if t:
output += ("%s%d %s%s" %
((", " if output else ""),
t, unit, ("s" if t > 1 else "")))
return output
|
def get_cad_srt(cad, component, placeholder):
"""
Parse component dictionary of component EDA2CADTransform objects.
Get CAD Scale, Rotation, Translation about part's local coordinate system.
"""
if cad is not None:
scale = [component.get("scale")['X'],
component.get("scale")['Y'],
component.get("scale")['Z']]
rotation = [component.get("rotation")['X'],
component.get("rotation")['Y'],
component.get("rotation")['Z']]
translation = [component.get("translation")['X'],
component.get("translation")['Y'],
component.get("translation")['Z']]
else:
placeholder = True
scale = [0.0, 0.0, 0.0]
rotation = [0.0, 0.0, 0.0]
translation = [0.0, 0.0, 0.0]
return scale, rotation, translation, placeholder
|
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
h = {}
for i, c in enumerate(s):
if c in h:
h[c] = -1
else:
h[c] = i
for c in s:
if h[c] != -1:
return h[c]
return -1
|
def set_level(request, level):
"""
Set the minimum level of messages to be recorded, and return ``True`` if
the level was recorded successfully.
If set to ``None``, use the default level (see the get_level() function).
"""
if not hasattr(request, 'dmm_backend'):
return False
request.dmm_backend.set_level(level)
return True
|
def check_convergence(p_in, p_out, tols, abs_flags):
"""
All four input arguments are lists or tuples of the same length.
Compares values in 'p_in' against those in 'p_out', and returns
False if the difference is greater than the corresponding value in
'tols'. If the value in 'abs_flags' is True, the values are
compared in absolutely rather than fractionally.
"""
for i, (pi, po, t, a) in enumerate(zip(list(p_in), list(p_out), tols, abs_flags)):
if a:
if abs(pi - po) > t:
#print 'busted %i (%f -> %f t= %f'%(i, pi, po, t)
return False
else:
d = abs(pi+po)/2
if d < 1e-7:
d = 1e-7
if abs(pi - po) / d > t:
#print 'busted %i (%f -> %f d= %f t= %f'%(i, pi, po, d, t)
return False
return True
|
def bin_to_str(bin_str_arr):
"""
Convert binary number in string to string
:param bin_str_arr: str, whose length must be a multiple of 8
:return: str
"""
res = ''
for i in range(0, len(bin_str_arr), 8):
res += chr(int(bin_str_arr[i:i+8], 2))
return res
|
def score_gamma(x, k, theta):
"""
Compute score function of one-dimensional Gamma distribution.
inputs: x: real number at which the score function is evaluated
k: positive number (shape parameter of Gamma distribution)
theta: positive number (scale parameter of Gamma distribution)
output: score
"""
return (k - 1) / x - 1 / theta
|
def bin_data(array_like, bin_size):
"""
This is an old alias, please use bin_sum_data or bin_mean_data
"""
return([sum(array_like[i:i+bin_size]) for i in range(0, len(array_like), bin_size)])
|
def path_to_str(pathP: list) -> str:
"""Use to get a string representing a path from a list"""
if len(pathP) < 1:
return ""
if len(pathP) < 2:
return pathP[0]
res = f"{pathP[0]} -> "
for i in range(1, len(pathP) - 1):
res += f"{pathP[i]} -> "
return res + f"{pathP[-1]}"
|
def base36_to_int(s):
"""
Convertd a base 36 string to an integer
"""
return int(s, 36)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.