content stringlengths 42 6.51k |
|---|
def dhugo(p2,d1,p1,g):
"""
Calculates the density on the hugoniot curve
Input:
p2 - Downstream pressure
d1 - Upstream density
p1 - Upstream pressure
g - Adiabatic index
"""
return (d1*((-1 + g)*p1 + (1 + g)*p2))/((1 + g)*p1 + (-1 + g)*p2) |
def _find_next_prime(N):
"""Find next prime >= N"""
def is_prime(n):
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i:
i += 2
else:
return False
return True
if N < 3:
return 2
if N % 2... |
def is_in_range(value, low_lim, up_lim, limits="Inclusive"):
"""Check if a value is bewteen a lower and upper limit"""
if limits == "Inclusive":
if low_lim <= value <= up_lim:
return True
else:
return False
elif limits == "Exclusive":
if low_lim < value < up_lim:
return True
else:
return False |
def broadcastable(shape_1, shape_2):
"""Returns whether the two shapes are broadcastable."""
return (not shape_1 or not shape_2 or
all(x == y or x == 1 or y == 1
for x, y in zip(shape_1[::-1], shape_2[::-1]))) |
def to_list(item):
"""Convert to list.
If the given item is iterable, this function returns the given item.
If the item is not iterable, this function returns a list with only the
item in it.
@type item: object
@param item: Any object.
@rtype: list
@return: A list with the item in it... |
def _is_symmetric(f):
"""Private function to help users not shoot their feet.
Calculates f(AB) and f(BA) and returns True if they are the
same (f() is symmetric), False otherwise (f() is asymmetric).
"""
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
return f(A, B) == f(B, A) |
def euclidean_dist_sq(pt1, pt2):
"""Helper - Euclidean dist between points, squared"""
return ((pt1[0] - pt2[0]) ** 2) + ((pt1[1] - pt2[1]) ** 2) |
def findunique(lst, key):
"""
Find all unique key values for items in lst.
For example find all ``GROUP`` values in a ``LAYER``'s ``CLASS``es
:param list lst: A list of composite dictionaries e.g. ``layers``, ``classes``
:param string key: The key name to search each dictionary in the list
"""
... |
def node_pre_rec_fm(true_nodes, pred_nodes):
""" Return the precision, recall and f-measure.
:param true_nodes:
:param pred_nodes:
:return: precision, recall and f-measure """
true_nodes, pred_nodes = set(true_nodes), set(pred_nodes)
pre, rec, fm = 0.0, 0.0, 0.0
if len(pred_nodes) != 0:
... |
def big_endian_decode(array, word_size):
"""Transform array of words to one integer."""
result = 0
for val in array:
result *= 2 ** word_size
result += val
return result |
def tournament_winner(competitions, results):
"""Finds the tournament winner
Args:
competitions (list): list of competitions
results (list): results of the competition
"""
score_board = {} # keep track of scores of each team
max_score, max_scorer = 0, None
for indx, competi... |
def interpolate(x0, y0, x1, y1, x):
"""
Linear interpolation between two values.
"""
y = (y0 * (x1 - x) + y1 * (x - x0)) / (x1 - x0)
return y |
def _truncate_ids(unit_ids):
"""Drop the last character of each unit ID and return the result as a set.
pulp-admin hard-wraps search results. This can result in wonky output::
Metadata:
Digest: sha256:3e2261c673a3e5284252cf182c5706154471e6548e1b0eb9082c4c
c
An incorrec... |
def average(my_list):
"""calculate mean of a list"""
try:
return sum(my_list) / len(my_list)
except ZeroDivisionError:
aa = 5 |
def add_docusaurus_metadata(content: str, id: str, title: str, hide_title) -> str:
"""
Add docusaurus metadata into content.
"""
return f"---\nid: {id}\ntitle: {title}\nhide_title: {hide_title}\n---\n\n" + content |
def move(cucumbers):
"""Move cucumbers one step. Return True if at least one cucumber moved."""
moved = False
# Move east.
for row in cucumbers:
first, last = row[0], row[-1]
i = 0
while i < len(row) - 1:
if row[i] == '>' and row[i+1] == '.':
row[i], r... |
def f_measure(precision, recall, beta=1.0):
"""Compute the f-measure from precision and recall scores.
Parameters
----------
precision : float in (0, 1]
Precision
recall : float in (0, 1]
Recall
beta : float > 0
Weighting factor for f-measure
(Default value = 1.0... |
def get_metrics_obj(monitorEle):
"""Find the metrics element within the given monitor element."""
if monitorEle is None:
return None
metricsEle = monitorEle['metrics']
if len(metricsEle) < 1:
return None
return metricsEle |
def sfc_sw_cld(swup_sfc, swup_sfc_clr, swdn_sfc, swdn_sfc_clr):
"""Cloudy-sky surface upward shortwave radiative flux."""
return swup_sfc - swup_sfc_clr - swdn_sfc + swdn_sfc_clr |
def black_box_function(x, y):
"""Function with unknown internals we wish to maximize.
This is just serving as an example, for all intents and
purposes think of the internals of this function, i.e.: the process
which generates its output values, as unknown.
"""
return -x ** 2 - (y - 1)... |
def basic_word_sim(word1, word2):
"""
Simple measure of similarity: Number of letters in common / max length
"""
return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2)) |
def get_text_list(list_, last_word='or'):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
u'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
u'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
u'a and b'
>>> get_text_list(['a'])
u'a'
>>> get_text_list([])
u''
"""
if... |
def get_position_below(original_position):
"""
Given a position (x,y) returns the position below the original position, defined as (x,y-1)
"""
(x,y) = original_position
return(x,y-1) |
def reverseVowels(s):
"""
:type s: str
:rtype: str
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
L = list(s)
i = 0
j = len(L) - 1
while i < j:
while i < j and L[i] not in vowels:
i += 1
while j > i and L[j] not in vowels:
j -= 1
L[i], L[j] = L[j], L[i]
i += 1
j -= 1
return '... |
def delete_objects(object_lists, output_xml):
"""
Check if input lists are not empty, write in xml for each list and return update list if some
updates has been made
Parameters:
object_lists : see order in get_specific_obj_type_and_idx()
output_xml (GenerateXML object) : XML... |
def bucketed_list(l, bucket_size):
"""Breaks an input list into multiple lists with a certain bucket size.
Arguments:
l: A list of items
bucket_size: The size of buckets to create.
Returns:
A list of lists, where each entry contains a subset of items from the input
list.
"""
n = max(1, bucke... |
def fibosum(number):
"""
Returns the sum of the Fibonacci sequence
"""
try:
n1, n2 = 0, 1
count = 0
fibonacci_sum = 0
sequence = [0, 1]
if number <= 0:
return False
elif number == 1:
fibonacci_sum = n2
else:
wh... |
def remove_prefix(text: str, *prefixes: str) -> str:
"""Removes the prefix of a string"""
for prefix in prefixes:
if text.startswith(prefix):
text = text[len(prefix):]
return text |
def CheckPermutation(s1: str, s2: str) -> bool:
"""Determines if s1 is a permutation of s2.
>>> CheckPermutation("", "")
True
>>> CheckPermutation("a", "aa")
False
>>> CheckPermutation("ab", "aa")
False
>>> CheckPermutation("ab", "ba")
True
>>> CheckPermutation("racecar", "c... |
def isimage(filename):
"""true if the filename's extension is in the content-type lookup"""
ext2conttype = {"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif"}
filename = filename.lower()
return filename[filename.rfind(".")+1... |
def separator(with_brackets):
"""
This function separate compound to brackets part and un brackets part. Don't use if no brackets in compound!
for example: Fe(NO3)3 -> ('Fe' , 'NO3', 3)
NaCl -> cause error
:param with_brackets:
:return: out brackets part, brackets part, brackets coef... |
def phone_number_validator(phone_number):
"""
Simple Validator to check if number is a valid phone number
:param phone_number:
:return Boolean:
"""
if len(phone_number) != 10:
return False
if phone_number[0] == '0':
return False
try:
int(phone_number)
except V... |
def name_valid(name):
"""
Check if the name if valid
:param name: in a string
:return: True or False
"""
return name.isalpha() |
def generate_subject_output_pattern(subjectid):
""" This function generates output path substitutions for workflows and nodes that conform to a common standard
:param subjectid:
:return:
"""
import os.path
patternList = []
find_pat = "_subject_" + subjectid + "/"
replace_pat = ""
p... |
def filterRowsWithDifferences(rows):
"""
Find all rows with differences in the status column.
"""
if not rows:
# empty table
return []
if len(rows[0].results) == 1:
# table with single column
return []
def allEqualResult(listOfResults):
allStatus = set([r... |
def pop_first_namedgroup(groupdict, value):
"""Search a value in a groupdict and remove the first key found from the dict"""
for k,v in groupdict.items():
if v == value:
groupdict.pop(k)
return k, v, groupdict
return False, value, groupdict |
def norm_color(s):
"""
>>> norm_color('red')
'Red'
>>> norm_color('Dark red')
'Dark Red'
>>> norm_color('dkred')
'Dark Red'
>>> norm_color('trred')
'Trans-Red'
>>> norm_color('trdkblue')
'Trans-Dark Blue'
>>> norm_color('rb')
'Reddish Brown'
>>> norm_color(' trdkb... |
def isen_nozzle_A_ratio(M_E, gamma_var):
"""
Calculates ratio between exit and throat areas in an isentropic nozzle.
Input variables:
M_E : Mach number at exit
gamma_var : Ratio of specific heats
"""
A_ratio = (((gamma_var + 1) / 2)**-((gamma_var + 1) / \
(2 *... |
def cm2inch(*tupl, scale=3):
"""
Convert cm to inch and scale it up.
Parameters:
*tupl: *tuple(floats)
Measures in cm to convert and scale.
scale: float
Scale factor. Default: 3
"""
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(scale * i/inch for i ... |
def add_field_name_to_value(row):
""" Combine the field name and value provided into one string.
Args:
row: the dataframe row containing information about a cell, including the header and contents
Returns:
The field name and value provided combined into one string
"""
... |
def check_public_key(pk):
""" Checks if a given string is a public (or at least if it is formatted as if it is).
:param pk: ECDSA public key to be checked.
:type pk: hex str
:return: True if the key matches the format, raise exception otherwise.
:rtype: bool
"""
prefix = pk[0:2]
l = le... |
def update_email(email):
"""Make email addresses, upper-case."""
return email.upper() |
def cumsum(arr):
""" Cumulative sum. Start at zero. Exclude arr[-1]. """
return [sum(arr[:i]) for i in range(len(arr))] |
def create_url(controller_ip, endpoint):
"""Create endpoint url to POST/PUT/GET/DELTE against."""
return 'https://%s:1080/%s' % (controller_ip, endpoint) |
def get_gui_access(code):
"""Get GUI access from code."""
gui_access = {0: "System default", 1: "Internal", 2: "Disable"}
if code in gui_access:
return gui_access[code] + " (" + str(code) + ")"
return "Unknown ({})".format(str(code)) |
def get_any_index(lst, *values):
"""Returns the index of (the first of) a set of values in lst."""
for value in values:
try:
return lst.index(value)
except ValueError:
pass |
def bytes_to_int(msb, lsb):
"""
Convert two bytes to signed integer (big endian)
for little endian reverse msb, lsb arguments
Can be used in an interrupt handler
:param msb:
:param lsb:
:return:
"""
if not msb & 0x80:
return msb << 8 | lsb # +ve
return - (((msb ^ 255) <<... |
def spread(e1, e2, c):
"""points spread between e1, e2"""
#recommend c between 25 (football, 10 pts = 1.5 scores) and ~15
return (e1-e2)/c |
def tokenize_trg(text):
"""
Tokenizes parse
"""
return text.split() |
def summation(n, term):
"""Return the sum of the first n terms in the sequence defined by term.
Implement using recursion!
>>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
225
>>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
54
>>> summation(5, lamb... |
def extract_labels(nr, nc):
"""[summary]
:param nr: number of rows of the wellplate, e.g. 8 (A-H) for a 96 wellplate
:type nr: [type]
:param nc: number of columns of the wellplate, e.g. 12 (1-12) for a 96 wellplate
:type nc: [type]
:return: lx - list containing the actual row IDs for the select... |
def avg_tribe_fitness(tribe_scores):
"""Calculates average fitness of a tribe.
This function implements a fitness function based on the average
score for evaluating a tribe.
Args:
tribe_scores: A list containing fitness scores of each
member of the tribe. The format is:
... |
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return int(((val - src[0]) / float(src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]) |
def parse_molecular_formula(formula):
"""
Parse a molecular formulat to get the element types and counts.
Args:
formula: molecular formula, f.i. "C8H3F3Br"
Returns:
A list of tuples containing element types and number of occurrences.
"""
import re
matches = re.find... |
def attachURI(metaDict, acc, con, obj):
"""Add URI to dict as `label`"""
if obj != "" and obj is not None:
uri = '/'.join(['', acc, con, obj])
elif con != "" and con is not None:
uri = '/'.join(['', acc, con])
else:
uri = '/' + acc
return {uri: metaDict} |
def milligram_to_grams(x: float) -> float:
"""Convert mass in mg to g.
Args:
x (float): Mass in mg.
Returns:
float: Mass in g
"""
return x * 10**-3 |
def longest_common_subsequence(x, y):
"""longest common subsequence
Dynamic programming
:param x:
:param y: x, y are lists or strings
:returns: longest common subsequence in form of a string
:complexity: `O(|x|*|y|)`
"""
n = len(x)
m = len(y)
# -- compute o... |
def _is_bool(s):
"""Check a value is a CSV bool."""
if s == 'True' or s == 'False':
return True
else:
return False |
def dict_max(dic):
"""
Returns maximum value of a dictionary.
"""
aux = dict(map(lambda item: (item[1],item[0]),dic.items()))
if aux.keys() == []:
return 0
max_value = max(aux.keys())
return max_value,aux[max_value] |
def get_new_coins(coin_seen_dict, all_coins_recheck):
"""
This method checks if there are new coins listed and returns them in a list.
The value of the new coins in coin_seen_dict will be set to True to make them not get detected again.
"""
result = []
for new_coin in all_coins_recheck:
... |
def git_url_user_password(url_https, user, password):
"""
Builds a url (starting with https) and add the user and the password
to skip the authentification.
:param url_https: example ``https://gitlab.server/folder/project_name``
:param user: part 1 of the credentials
... |
def filter_relation(relation, relation_type, relation_subtype, entity_ids):
"""
Function to filter a relation for given: type, subtype and entitiy ids.
Args:
relation (dict): dictionary representing a relation.
relation_type (str): relation type.
relation_subtype (str): relation sub... |
def ssh_cmd(cmd_str, ip, ssh_key=None):
"""construct an ssh command
"""
if ssh_key is None:
ssh_cmd_str = 'ssh %s \'%s\'' % (ip, cmd_str)
else:
ssh_cmd_str = 'ssh -i %s %s \'%s\'' % (ssh_key, ip, cmd_str)
return ssh_cmd_str |
def q_to_batch_size(q, N):
""" Returns the batch size for a given subsampling ratio q. """
return int(N * q) |
def sort_strings(list_of_strings):
"""Return sorted list of strings in an ascending order by treating every string as if it would start with an
uppercase letter.
Examples:
[toast2, Test3, Toast, test33] --> [Test3, test33, Toast, toast2]
Args:
list_of_strings (list): list of string ele... |
def snake2camal(string: str) -> str:
"""
Change string from snake_case to CamalCase
:param string: (str) string to convert
:rtype (str): converted string
"""
return ''.join(word.title() for word in string.split('_')) |
def ranges(int_list):
"""
Given a sorted list of integers function will return
an array of strings that represent the ranges
"""
begin = 0
end = 0
ranges = []
for i in int_list:
# At the start of iteration set the value of
# `begin` and `end` to equal the first element
... |
def insertionsort(lst):
""" Implementation of insertion sort algorithm """
# start from second element of list
for j in range(1, len(lst)):
key = lst[j]
i = j - 1
# insertion j-th into sorted list
while i >= 0 and lst[i] > key:
lst[i + 1] = lst[i]
# se... |
def is_instance(list_or_dict):
"""Checks to if miltiple prefix-list are in the config. If one list is in the configuration, structure is dictionary
If multiple list are in the config, structure will be a list of dictionaries. Convert to list if dictionary"""
if isinstance(list_or_dict, list):
... |
def ms_to_htk(ms_time):
"""
Convert time in ms to HTK (100 ns) units
"""
if type(ms_time)==type("string"):
ms_time = float(ms_time)
return int(ms_time * 10000.0) |
def calculate_which_half(low, high, x):
"""
:param low: numeric value lower boundary
:param high: numeric value higher boundary
:param x: random number drawn between low and high
:return: boolean
"""
lower_half = (high - low) / 2 + low
if x > lower_half:
return True
else:
... |
def _check_upper_bound(x, upper, full_name, short_name,
inclusive_bound=True):
"""Check object satisfies upper bound."""
if inclusive_bound:
if x > upper:
raise ValueError(
"%s must be at most %r "
"(got %s=%r)" %
(full_... |
def hexToBytes(hexStr):
"""
Provide hex sting in format 'ab ab ab...'
Returns the byte values
"""
bInt = [int(hexStr[i*3:i*3+2],16) for i in range(int((len(hexStr)+1)/3))]
return bInt |
def _generate_snitch_text(cluster):
"""Generate the text for the PropertyFileSnitch file"""
i=1
contents = [
"# Auto-generated topology snitch during cluster turn-up", "#",
"# Cassandra node private IP=Datacenter:Rack", "#", ""
]
for z in cluster.keys():
contents.append("# Zo... |
def is_nestable(x):
"""
Returns 1 if x is a tuple or list (sequence types that can nest)
Returns 0 otherwise
>>> is_nestable("string")
0
>>> is_nestable((0,))
1
>>> is_nestable(range(5))
1
"""
return isinstance(x, (tuple, list)) |
def R_max(H, D, gamma, f):
""" Returns the uplift resistance of a pipe in sand.
DNV-RP-F110 2007 - Equation (B.3)
"""
return (1 + f * H / D) * (gamma * H * D) |
def validate_graph(graph):
"""
Takes a graph in the form of a dictionary and verifies that for every edge member there exists a source node.
If no source node is found from existing edge members, one is created with an empty edge [].
:param graph:
:return:
"""
vertices = [vertex for edge in ... |
def make_struct(*args):
"""
Constructs a struct with the provided args.
Examples
--------
>>> make_struct("weldlazy1", "2", "3").code
'{weldlazy1, 2, 3}'
>>> make_struct("weldlazy1").code
'{weldlazy1}'
"""
assert len(args) > 0
return "{" + ", ".join(args) + "}" |
def _flatten_list(l):
"""
"""
assert isinstance(l, (list, tuple))
assert len(l) > 0
assert all([len(l_) > 0 for l_ in l])
return [l__ for l_ in l for l__ in l_] |
def add_and_return_map(map: str, mode: str, buckets: dict, bucket_num: int) -> str:
"""
Adds map to bucket list and returns it
"""
# if next bucket doesntr exists then create it
if bucket_num + 1 not in buckets:
buckets[bucket_num + 1] = {}
# if mode bucket doesnt exist then
if mode... |
def get_frame(name):
"""Get log stack frame."""
return (name, 5, None, None) |
def _sep_lines(*args):
"""Returns a string comprised of all arguments, with newlines inserted
between them."""
return "\n".join(args) |
def interpolate_data(diff, prev_value, current_value):
"""Returns interpolated value.
:param diff: difference between values e.g:
temperature from user: 71 (requested value),
temperature previous: 70,
temperature next: 80,
diff = (temperature_from_user - temperature_previous) / (temperature_nex... |
def roi_size(roi):
"""
returns number of cols and rows
"""
cols = roi[1][0] - roi[0][0] + 1
rows = roi[1][1] - roi[0][1] + 1
return cols, rows |
def set_absolute_intensity(connection, val, await_response=False):
"""Send a serial command over the given connection to set the overall intensity.
val should be in the range [0:1] or [1:100]
"""
if 1 < val <= 100:
val = val / 100
elif val > 100:
print("set_intensity: error: must ... |
def is_start_of_word(lines, i, j):
"""
Checks if there is a word starting at (i,j)
"""
if lines[i][j] == '*':
return False
left = '*' if i == 0 else lines[i-1][j]
right = '*' if (i == len(lines) - 1) else lines[i+1][j]
above = '*' if j == 0 else lines[i][j - 1]
below = '*' if j... |
def analysis_lrn_usages(analysis):
"""
Returns a dictionary of local usages by row.
This index can be used to quicky find a local usage by row.
Example: (let [a 1] |a)
'lrn' stands for 'local row name'.
"""
return analysis.get("lrn_usages", {}) |
def find_closest_index(L,t):
"""
Find the index of the closest value in a list.
Input:
L -- the list
t -- value to be found
Output:
index of the closest element
"""
beginning = 0
difference = abs(L[0] - t)
best = 0
end = len(L)
while beginning < end:
... |
def ringTopology(elementList):
"""Creates a the adjacency list for a ring topology out of a linear list of
all elements in the network.
:param list[string] elementList: A list of all elements in the network.
"""
adjacencyList = {}
for position in range(0, len(elementList)):
if position ... |
def extended_euclid(n, m):
"""Finds the gcd [index 0] of n and m and (n**-1)mod m [index 1](if it exists).
If no inverse, will find solution for a number which multiplies to the gcd'"""
q_list = []
n%=m
##value setup##
if(n < m):##swaps n and m
n ^= m
m ^= n
n ^= m
... |
def get_module_metrics(module_files):
"""Retrieve all the module metrics."""
module_metrics = {}
for file in module_files:
file_metrics = file.metric(
[
"MaxCyclomatic",
"CountDeclClass",
"CountDeclFunc",
"CountLine",
... |
def concatenatePaths(root, subDir):
"""
Combine a root directory with a sub-directory
:param root: str, the root directory
:param subDir: str, the sub-directory
:return: path, str, the full combined path
"""
if (not root.endswith('/')) and (root != ''):
root = root + '/'
if (not subDir.endswith('/')) and (s... |
def first(l):
"""
Returns first element of a pipe
:param datastream: input pipe generator
:return: first element
"""
for x in l:
return x |
def bytesToWord(high, low):
"""Convert two byte buffers into a single word value
shift the first byte into the work high position
then add the low byte
Args:
high: byte to move to high position of word
low: byte to place in low position of word
Returns:
... |
def count_even(obj):
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
@param int|list obj: object to count even numbers from
@rtype: int
>>> count_even(3)
0
... |
def p_bigrams(bis,trans_probs):
"""
Calculates the bigram probability of the string of words bis.
Arguments
bis : sequence of merged words. If there's no copying this is the whole string; otherwise some is missing
trans_probs : markhov chain of transitional probabilities implemented as dict... |
def map_resname_to_id(res_code):
"""
Convert the 3-lettered residue code to single letter
Parameters:
res_code: The three-lettered amino acid code
Returns:
The corresponding single-letter amino acid code
"""
resname_2_id = {'ALA' : 'A', 'ARG' : 'R', 'ASN' : 'N', 'ASP' : 'D',... |
def get_fourier_col_name(k, col_name, function_name="sin", seas_name=None):
"""Returns column name corresponding to a particular fourier term, as returned by fourier_series_fcn
:param k: int
fourier term
:param col_name: str
column in the dataframe used to generate fourier series
:param... |
def pluralize(value, s1='s', s2=None):
"""Like Django's pluralize-filter, but instead of using an optional
comma to separate singular and plural suffixes, it uses two distinct
parameters.
It also is less forgiving if applied to values that do not allow
making a decision between singular and plural.... |
def payoff_put(underlying, strike, gearing=1.0):
"""payoff_put
Payoff of put option.
:param float underlying:
:param float strike:
:param float gearing: Coefficient of this option. Default value is 1.
"""
return gearing * max(strike - underlying, 0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.