content stringlengths 42 6.51k |
|---|
def sbox(block):
"""Bitsliced implementation of the s-box"""
a = (block[0] & block[1]) ^ block[2]
c = (block[1] | block[2]) ^ block[3]
d = (a & block[3]) ^ block[0]
b = (c & block[0]) ^ block[1]
return [a,b,c,d] |
def textmark(string, mark=""):
"""
Excerpt of content
>>> textmark('<p>Hello</p><!----><p>World</p>')
'<p>Hello</p>'
>>> textmark('<p>Hello</p><!--ex--><p>World</p>', 'ex')
'<p>Hello</p>'
>>> textmark('<p>Hello</p><!----><p>World</p><!--test-->', 'test')
'<p>Hell... |
def lr_schedule(epoch):
"""
schedule a dynamic learning rate
:param epoch:
:return:
"""
lr = 0.001
if (epoch > 75):
lr = 0.0005
elif (epoch > 100):
lr = 0.0003
return lr |
def get_full_asetup(cmd, atlas_setup):
"""
Extract the full asetup command from the payload execution command.
(Easier that generating it again). We need to remove this command for stand-alone containers.
Alternatively: do not include it in the first place (but this seems to trigger the need for further... |
def is_integer(s):
""" Using exceptions for this feels... wrong..."""
try:
int(s)
return True
except ValueError:
return False |
def cloudtrail_snapshot_or_ami_made_public(rec):
"""
author: spiper
description: Alert on AWS API calls that make EBS snapshots,
RDS snapshots, or AMIs public.
playbook: (a) identify the AWS account in the log
(b) identify what resourc... |
def diff(first, second):
"""Takes the set diff of two lists"""
second = set(second)
return [item for item in first if item not in second] |
def densenet_params(model_name):
""" Map densenet_pytorch model name to parameter coefficients. """
params_dict = {
# Coefficients: growth_rate, num_init_features, res
"densenet121": (32, 64, 224),
"densenet161": (48, 96, 224),
"densenet169": (32, 64, 224),
"densenet201... |
def ewma(p_mean, val, alpha=0.8):
"""computes exponentially weighted moving mean"""
return p_mean + (alpha * (val - p_mean)) |
def get_type_hint(q_list: list):
"""
Uses the first word of the question to return the likely response format
of the question's answer.
Args:
-----
q_list: a list of strings containing the questions
Returns:
--------
A list of strings containing whether the questions are ex... |
def fix_date(date):
"""
fix date value from user input
Args:
date: date value - user input
Returns:
an array with fixed date value or original date
"""
if date:
if date.count(":") == 2:
return [
date,
"{0} 23:59:59".format(
... |
def GetFlakeIssue(flake):
"""Returns the associated flake issue to a flake.
Tries to use the flake's issue's merge_destination, and falls back to the
issue itself if it doesn't merge into any other ones.
Args:
flake: A Flake Model entity.
Returns:
A FlakeIssue entity if it exists, otherwise None.... |
def count_to_palindrome(arr: list) -> int:
"""
Time Complexity: O(n)
"""
i, j = 0, len(arr) - 1
total: int = 0
while i < j:
if arr[i] == arr[j]:
i += 1
j -= 1
continue
elif arr[i] < arr[j]:
i += 1
arr[i] += arr[i - 1]
... |
def kinetic_energy(vehicle_mass, v):
"""
Calculates the rotational energy stored in a tire
:param vehicle_mass: The tire moment of inertia
:param v: The velocity of the vehicle (m/s)
:return: The energy in Joules stored as rotational kinetic energy
"""
return vehicle_mass * (v ** 2) / 2 |
def subplot_index(nrow, ncol, k, kmin=1):
"""Return the i, j index for the k-th subplot."""
i = 1 + (k - kmin) // ncol
j = 1 + (k - kmin) % ncol
if i > nrow:
raise ValueError('k = %d exceeds number of rows' % k)
return i, j |
def increment(x):
"""adds 1 to x"""
return(x+1) |
def compile_references(d):
"""get the references from the Excel sheet for each year in the decade.
return them in a list."""
refs = []
for e, date in enumerate(d["dates"]):
if d["references"][e] not in refs:
refs.append(d["references"][e])
return refs |
def create_put_request(item):
"""Create a PutRequest object."""
return {'PutRequest': {'Item': item}} |
def cdp_version_decode( cdp_version ):
"""
Decode a CDP version string of the form 'xx.yy.zz' into
xx -> cdprelease, yy --> cdpversion and zz -> cdpsubversion.
Strings of the form 'xx.yy' or 'xx' are also decoded (with the
missing version numbers returned as None).
If an empty or inval... |
def find_center_point(corners):
"""
use points that are on the diagonal to calculate the center points
corners - array of 4 [x,y] arrays.
corner[0] = [x0,y0]
corner[0][0] = x0
corner[0][1] = y0
"""
center_x = (corners[0][0] + corners[2][0])//2
center_y = (corners[0][1] + cor... |
def check(result, response):
"""
Returns a string of correct, incorrect, or invalid
after comparing the conversion result and response of
the student rounded to the ones place.
"""
try:
if result is None:
return "invalid"
elif response is not None:
return ... |
def get_trials_per_job_mpi(njobs, ntrials):
"""
split for mpi
"""
return int(round(float(ntrials)/njobs)) |
def apply_to_list(op, inputs):
"""Apply operator `op` to list `inputs` via binary tree
"""
n = len(inputs)
if n == 1:
return inputs[0]
m0 = apply_to_list(op, inputs[: n // 2])
m1 = apply_to_list(op, inputs[n // 2 :])
return op(m0, m1) |
def hello(name,origin):
""" This is the first hello world for python function/modules """
return "helo " + str.strip(str(name)) +" van "+ str.strip(str(origin)) |
def is_numeric(string):
"""
Determine whether the string is a number.
:param string: String to test.
:return: True if the string is a number. False otherwise.
"""
try:
float(string)
return True
except ValueError:
return False
pass |
def human_readable(value):
"""
Returns the number in a human readable format; for example 1048576 = "1Mi".
"""
value = float(value)
index = -1
suffixes = 'KMGTPEZY'
while value >= 1024 and index + 1 < len(suffixes):
index += 1
value = round(value / 1024)
if index == -1:
... |
def weighted_match_score(vector1, vector2):
"""Calculate matching score that considers both the relative intensities of the matching peaks
(i.e. is is 100 vs 98, or 100 vs 2?) and also the number of matches versus the total number of peaks in each vector
"""
vector1_weighted_pairwise_match = 0
vect... |
def linear_mapping(_from, _to, x):
"""
Lets use a simple linear function that maps the ends of one scale onto ends
of another. Obviously, we need that
f(left_min) -> right_min and
f(left_max) -> right_max,
and points in between are mapped proportionally.
"""
return _to[0] + (... |
def string_to_int(s):
"""Convert a string of bytes into an integer, as per X9.62."""
result = 0
for c in s:
if not isinstance(c, int):
c = ord(c)
result = 256 * result + c
return result |
def endswith(value, arg):
"""Usage, {% if value|endswith:"arg" %}"""
return value.endswith(arg) |
def cidr_to_netmask(cidr):
"""
:param cidr:
:return:
"""
cidr = int(cidr)
mask_addr = (0xffffffff >> (32 - cidr)) << (32 - cidr)
return (str((0xff000000 & mask_addr) >> 24) + '.' +
str((0x00ff0000 & mask_addr) >> 16) + '.' +
str((0x0000ff00 & mask_addr) >> ... |
def sum_multiples_three_five(number):
"""
number: random integer
return: the sum of all multipliers of 3 and 5 below number
"""
multipliers = []
n = 0
while n < number:
if n % 3 == 0 or n % 5 == 0:
multipliers.append(n)
n += 1
return sum(multipliers) |
def translate(value, from_min, from_max, to_min, to_max):
"""
Translates the value passed as a parameter into a corresponding value
in the right range.
"""
# Figure out how 'wide' each range is
left_span = from_max - from_min
right_span = to_max - to_min
# Convert the left range into a ... |
def is_wd_id(var):
"""
Checks whether a variable is a Wikidata id
"""
if var[0] == "Q" and var.split("Q")[1].isnumeric(): # check if it's a QID
return True
if var[0] == "P" and var.split("P")[1].isnumeric(): # check if it's a PID
return True
return False |
def LCS(X,Y):
"""
Return length of longest common subsequence of X and Y.
Used to measure how much has changed in student ordering when
an optimization is done.
Algorithm straight from CLRS (Chapter 13--Dynamic Programming)
"""
m = len(X)
n = len(Y)
C = [[0 for j in range(n+1)] fo... |
def has_changes(statements):
""" See if a list of SQL statements has any lines that are not just comments """
for stmt in statements:
if not stmt.startswith('--') and not stmt.startswith('\n\n--'):
return True
return False |
def Power_Calc(Vcell, i):
"""
Calculate power.
:param Vcell: Vcell Voltage [V]
:type Vcell : float
:param i: cell load current [A]
:type i : float
:return: cell power [W] as float
"""
try:
result = Vcell * i
return result
except TypeError:
print(
... |
def safeForKids(haveKids, kidFriendly):
"""Determines if the user is travelling with kids or not, as if the country is kid friendly, anyone can go, but
if it is no kid friendly, then only people travelling without kids can go there
Parameters:
haveKids: The user's input as to if they have kids or ... |
def valid_name_request(count):
"""A method for validating a request to get unique names.
Parameters
----------
filename : str
The filename to read.
"""
if 0 < count <= 1000:
return True |
def parse_pos_line(cell_line):
"""
Parse single line in the cell block.
Return element, coorindates and a dictionary of tags
"""
import re
cell_line = cell_line.strip()
s = re.split(r"[\s]+", cell_line, maxsplit=4)
if len(s) < 4:
raise ValueError("Cannot understand line: {}".for... |
def get_base_layout(figures):
"""Generate a layout with the union of multiple figures' layouts.
Parameters
----------
figures : list
List of Plotly figures to get base layout from.
"""
if not isinstance(figures, list):
raise TypeError("Invalid figures '{0}'. "
... |
def _union_1d(first, second, size):
"""Computes if slice first and second overlap for the size of the dimension"""
first_min, first_max, _ = first.indices(size)
second_min, second_max, _ = second.indices(size)
if first_max >= second_min and second_max >= first_min:
return slice(min(first_min, se... |
def check_request_params(data, params):
"""
Checks that a JSON request contains the proper parameters.
Parameters
----------
data : json
The JSON request
params: list
The parameters that should appear in the JSON request
Returns
-------
str
A message det... |
def contains_alpha(string):
"""
Return True if the input 'string' contains any alphabet
"""
return any([c.isalpha() for c in string]) |
def memoized_fibonacci(n):
"""Returns the nth fibonacci number
Time complexity: O(n)
Parameters
----------
n : int
the nth fibonacci position
Returns
-------
int
the nth fibonacci number
-------
>>> memoized_fibonacci(0)
0
>>> memoized_fibonacci(1)
... |
def signed_area(coords):
"""Return the signed area enclosed by a ring using the linear time
algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0
indicates a counter-clockwise oriented ring."""
try:
xs, ys = tuple(map(list, zip(*coords)))
except ValueError:
# Attempt t... |
def get_altitude(pressure: float, sea_level_hPa: float = 1013.25) -> float:
"""
the conversion uses the formula:
h = (T0 / L0) * ((p / P0)**(-(R* * L0) / (g0 * M)) - 1)
where:
h = height above sea level
T0 = standard temperature at sea level = 288.15
L0 = standard temperatur elapse rate = ... |
def ident_values_changed(func_args, ident):
"""Check for changes to state or attributes on ident vars."""
var_name = func_args.get("var_name", None)
if var_name is None:
return False
value = func_args["value"]
old_value = func_args["old_value"]
for check_var in ident:
var_piece... |
def _interpolate(val, vmin, vmax):
"""Interpolate a color component between to values as provided
by matplotlib colormaps
"""
interp = (val - vmin[0]) / (vmax[0] - vmin[0])
return (1 - interp) * vmin[1] + interp * vmax[2] |
def to_lower_case(name):
"""Returns a lower-case under-score separated format of the supplied name, which is supposed to be camel-case:
>>> ToScriptName("AbcABC01ABCAbc")
"abc_abc01abc_abc"
"""
script_name = ""
for i in range(len(name)):
if i > 0 and (name[i-1:i].islower() or name[i-1:i]... |
def default_none(value, default):
"""
Returns |value| if it is not None, otherwise returns |default|.
"""
return value if value != None else default |
def unconvert_rounded_offset(y):
"""
>>> from undervolt import convert_offset, unconvert_offset
>>> domain = [ 1024 - x for x in range(0, 2048) ]
>>> all( x == unconvert_rounded_offset(convert_rounded_offset(x)) for x in domain )
True
"""
x = y >> 21
return x if x <= 1024 else - (2048 - ... |
def hours_to_minutes(time):
"""
input: 'HH:MM', output: same time in minutes
"""
time = time.split(':')
return int(time[0])*60 + int(time[1]) |
def update_final_dict_to_have_no_mappings(final_dict):
"""
This function removes all mappings from the dictionary and only element
values are retained
"""
for element in final_dict:
if final_dict[element] is not None and final_dict[element] is not False and "=" in final_dict[element]:
... |
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message, response_card):
"""Builds the response to elicit slot clarification"""
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ElicitSlot',
'intentName': intent_name,
... |
def counting_sheep(sheeps) -> int:
"""This function count True in list."""
count = 0
for sheep in sheeps:
if sheep:
count += 1
return count |
def _get_string(dictionary, key, del_if_bad=True):
"""
Get a string from a dictionary by key.
If the key is not in the dictionary or does not refer to a string:
- Return None
- Optionally delete the key (del_if_bad)
"""
if key in dictionary:
value = dictionary[key]
i... |
def answer(word):
"""
initialize an answer space.
:param word: string
:return: string
"""
ans = ''
for i in range(len(word)):
ans += '-'
return ans |
def get_subindex(string, ch):
"""
Finds all indexes of the specified character in the string.
"""
return [c for (c, i) in enumerate(string) if i == ch] |
def remove_underscores(s):
"""
:param s:
:return:
"""
return s.replace('_', ' ') |
def common_characters(w1, w2):
"""
Parameters:
----------
w1: str
w2: str
Returns:
--------
int:
Number of characters common between two strings
"""
ws1 = set(w1)
ws2 = set(w2)
return len(ws1.intersection(ws2)) |
def null_distance_results(string1, string2, max_distance):
"""Determines the proper return value of an edit distance function when
one or both strings are null.
"""
if string1 is None:
if string2 is None:
return 0
else:
return len(string2) if len(string2) <= max_d... |
def _fixiternum(s):
"""
Fix the string by adding a zero in front if double digit number, and two
zeros if single digit number.
"""
if len(s) == 2:
s = '0' + s
elif len(s) == 1:
s = '00' + s
return s |
def encode(content: int) -> bytearray:
"""Encode an integer into a SDNV
:param content: Integer to encode
:return: Bytearray containing the encoded value
"""
if content < 0 or type(content) != int:
raise ValueError("Invalid content")
flag = 0
ret_array = bytearray()
while True:... |
def format_value(value):
"""
Formats a value for output.
Arguments:
value (?): The value to format.
Returns:
If the value is a list, returns a comma-separated string of the items
in the list. If the value is a dictionary, returns a comma-separated
string-representation of the key-value-pairs. Else returns... |
def create_attribute_names(attribute_names):
"""Create attribute names
Args:
attribute_names (str): Attribute names
Returns:
str: Expression attribute names
"""
expression_attribute_names = {}
for attribute_name in attribute_names:
expression_attribute_names[f"#{attribute... |
def extract_confidence(result): # pragma: no cover
"""Extracts the confidence from a parsing result."""
return result.get('intent', {}).get('confidence') |
def standardize_old_hpo_objects(hpo_objects, old_hpo_objects):
"""
In the case where an HPO exists in a 'newer' iteration of
an analytics report but not in the 'older' analytics
report, this function places a copy of the 'new' HPO
object into the old HPO objects list.
This placement is to ensur... |
def cubic_cutoff(r_cut: float, ri: float, ci: float):
"""A cubic cutoff that goes to zero smoothly at the cutoff boundary.
Args:
r_cut (float): Cutoff value (in angstrom).
ri (float): Interatomic distance.
ci (float): Cartesian coordinate divided by the distance.
Returns:
(... |
def compute_perfect_tree(total):
"""
Determine # of ways complete tree would be constructed from 2^k - 1 values.
This is a really subtle problem to solve. One hopes for a recursive solution,
because it is binary trees, and the surprisingly simple equation results
from the fact that it is a complete ... |
def int_from_code(code):
"""
:type code: list
:rtype: int
"""
num = 0
for i, v in enumerate(reversed(code), 1):
num *= i
num += v
return num |
def all_none(*args):
"""Shorthand function for ``all(x is None for x in args)``. Returns
True if all `*args` are None, otherwise False."""
return all(x is None for x in args) |
def adder_function_json(args):
"""Dummy function to execute returning a dict."""
loc, scale = args
return {'result': loc + scale} |
def get_task(task_id, tasks_object):
"""
Find the matching task.json for a given task_run.json 's task_id
:param task_id: task_run.json['task_id']
:type task_id: int
:param tasks_object: tasks from json.load(open('task.json'))
:type tasks_object: list
:return: a JSON task object from task... |
def isspace(char):
""" Indicates if the char is a space, tabulation or new line """
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
return False |
def set_led_ring(amount: float):
"""Return count and color based on credit float amount
the ring LED has 8 elements and are set based on credit amounts:
credits LEDs lit Color
=============== =================== ===========================
0 - 0.24 8 re... |
def mangle_struct_typename(s):
"""Strip leading underscores and make uppercase."""
return s.lstrip("_").upper() |
def regroup_pre_validation_checks(workflow_config_dict):
"""
Checks if provided configuration is correct for regroup
validation.
Returns valid regroup filename if found, error list otherwise
"""
if (workflow_config_dict["run_reference_alignment"] != "yes"):
return '', [] # return defaul... |
def count_set_bits(n: int) -> int:
""" Count bits == 1 """
count = 0
while (n):
count += n & 1
n >>= 1
return count |
def undotify(dotdict):
"""
Expand a dictionary containing keys in "dot notation".
This support both standard dict or OrderedDict, or any dict subclass.
For example::
.. code-block:: python3
dotdict = {
'key1.key2.key3': 'string1',
'key1.key2.key4': 1000,
... |
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
returns: a dictionary
"""
freq = {}
for x in sequence... |
def to_unicode(text, encoding='utf-8', errors='strict'):
"""Force text to unicode"""
if isinstance(text, bytes):
return text.decode(encoding, errors)
return text |
def str2bool(option):
"""Convert a string value to boolean
@param option: yes, true, 1, no, false, 0
@type option: String
@rtype: Boolean
"""
option = option.lower()
if option in ("yes", "true", "1"):
return True
elif option in ("no", "false", "0"):
return False
els... |
def selection_sort(my_list):
"""Define the selection sort algorithm."""
if len(my_list) < 2:
return my_list
for index in range(0, len(my_list)-1, +1):
index_of_min = index
for location in range(index, len(my_list)):
if my_list[location] < my_list[index_of_min]:
... |
def conv2d_size_out(size, kernel_size, stride):
"""
common use case:
cur_layer_img_w = conv2d_size_out(cur_layer_img_w, kernel_size, stride)
cur_layer_img_h = conv2d_size_out(cur_layer_img_h, kernel_size, stride)
to understand the shape for dense layer's input
"""
return (size - (kernel_size... |
def _nearest(pivot, items):
"""Returns nearest point
"""
return min(items, key=lambda x: abs(x - pivot)) |
def cmdEcho(args, flags, context):
"""
Echo arguments to output
"""
# NOTE: args must be a list of Strings or literals
msg = ' '.join(map(lambda x: str(x), args))
return msg |
def get_neighbors(y, x, H, W):
""" Return indices of valid neighbors of (y, x).
Return indices of all the valid neighbors of (y, x) in an array of
shape (H, W). An index (i, j) of a valid neighbor should satisfy
the following:
1. i >= 0 and i < H
2. j >= 0 and j < W
3. (i, j) !=... |
def dec2hex(number):
"""return a decimal number into its hexadecimal form"""
return hex(number)[2:] |
def add_binary(a, b):
"""
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done
before, or after the addition. The binary number returned should be a string.
:param a: an integer value.
:param b: an integer value.
:return: the binary valu... |
def factorial (n):
"""Factorial, computed recursively.
What is the base case?
How can you express n! recursively, in terms of itself?
Params: n (int): n >= 1
Returns: n!
"""
if n == 1:
return 1
else:
return n*factorial(n-1)
return n |
def add3(a, b, c=2):
"""exec a + b + c = ?"""
print('exec add3')
ret = a + b + c
print('add3: %s + %s + %s = %s' % (a, b, c, ret))
return ret |
def unscratch_win(x, ndx, n, scr=-1):
"""
:param x: Vector of info (e.g. win price) for starters only
:param ndx: Indexes of starters
:param n: Original number of runners
:param scr:
:return:
"""
p = [scr for _ in range(n)]
for ndx,xi in zip(ndx,x):
p[ndx] = xi
... |
def get_num_classes(dataset: str):
"""Return the number of classes in the dataset. """
if dataset == "imagenet":
return 1000
elif dataset == "cifar10":
return 10
elif dataset == "mnist":
return 10 |
def format_time(time_to_go):
"""Return minutes and seconds string for given time in seconds.
:arg time_to_go: Number of seconds to go.
:returns: string representation of how much time to go.
"""
if time_to_go < 60:
return '%ds' % time_to_go
return '%dm %ds' % (time_to_go / 60, time_to_... |
def shorter_name(key):
"""Return a shorter name for an id.
Does this by only taking the last part of the URI,
after the last / and the last #. Also replaces - and . with _.
Parameters
----------
key: str
Some URI
Returns
-------
key_short: str
A shortened, but more... |
def get_product_variants(variants, sku):
"""Returns a list of variants for a product."""
product_variants = [
variant for variant in variants
if variant["Product SKU"] == sku and variant["Variant Enabled"] == "Y"
]
product_variants.sort(key=lambda variant: variant["Variant Sort"])
re... |
def is_whitespace(c: str) -> bool:
"""Return True if c is a whitespace, False otherwise."""
return c == " " or c == "\t" or c == "\n" |
def _indented_repr(o):
"""Returns repr(o), with any lines beyond the first one indented +2."""
return repr(o).replace("\n", "\n ") |
def validate_ruletype(ruletype):
"""
Validate RuleType for ResolverRule.
Property: ResolverRule.RuleType
"""
VALID_RULETYPES = ("SYSTEM", "FORWARD")
if ruletype not in VALID_RULETYPES:
raise ValueError("Rule type must be one of: %s" % ", ".join(VALID_RULETYPES))
return ruletype |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.