content stringlengths 42 6.51k |
|---|
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i |
def flow_configs(port_configs):
"""This fixture demonstrates adding flows to port configurations."""
for config in port_configs:
f = config.flows.flow()[-1]
f.tx_rx.device.tx_names = [config.devices[0].name]
f.tx_rx.device.rx_names = [config.devices[1].name]
f.name = "%s --> %s"... |
def char(cA, cB):
"""Returns the appropriate single qubit pauli character when merging."""
if cA == "I":
return cB
return cA |
def colorbar_abs(float, color_list):
"""
returns RGB triplet when given float between 0 and 1
input:
- float float between 0 and 1
- color_list list of RGB triplets (lists of 3 floats)
output:
- RGB list of 3 floats
"""
index = int(round(float * (len(color_list)... |
def get_recursively(search_dict, field, no_field_recursive=False):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
if no_field_recursive ... |
def str_2_sec(timein):
"""
Convert time in days / hrs / mins etc to total seconds used)
"""
splitdays = timein.split('-')
if len(splitdays) == 2:
# Have list of days and time
secs = 24*60*60*int(splitdays[0]) + str_2_sec(splitdays[1])
elif len(splitdays) == 1:
# Just have... |
def getClass(obj):
"""
Return the class or type of object 'obj'.
Returns sensible result for oldstyle and newstyle instances and types.
"""
if hasattr(obj, '__class__'):
return obj.__class__
else:
return type(obj) |
def get_query_string(params) -> str:
"""
Gets the query string of a URL parameter dictionary.abs
:param params: URL params.
:return: Query string.
"""
if not params:
return ''
return '?' + '&'.join([str(k) + '=' + str(v) for k, v in params.items()]) |
def angle_wrap(s):
"""Return s surrounded by angle brackets, added only if necessary"""
# This is the inverse behavior of email.utils.unquote
# (which you might think email.utils.quote would do, but it doesn't)
if len(s) > 0:
if s[0] != '<':
s = '<' + s
if s[-1] != '>':
... |
def upper_bound(x):
"""Return the upper bound of interval x."""
"*** YOUR CODE HERE ***"
return x[-1] |
def average(num):
"""Gets the average of the numbers in a list"""
total = 0
for n in num:
total += n
return (total / (len(num))) |
def clamp(val, low, high):
"""Return val, within [low,high]"""
if val < low:
return low
elif val > high:
return high
return val |
def plural(num):
""" Gets the English plural ending for an ordinal number. """
return "" if num == 1 else "s" |
def setbit(byte, offset, value):
"""
Set a bit in a byte to 1 if value is truthy, 0 if not.
"""
if value:
return byte | (1 << offset)
else:
return byte & ~(1 << offset) |
def tickets(number, day, premium_seating):
"""
The cost of the cinema ticket.
Normal ticket cost is $10.99
Wednesdays reduce the cost by $2.00
Premium seating adds an extra $1.50 regardless of the day
Parameters:
----------
number: int
integer value representing the number o... |
def get_eff_k(k1, k2):
"""
Returns effective bulk modulus
Parameters
----------
k1: float
First bulk modulus
k2 : float
Second bulk modulus
Returns
-------
float
Effective bulk modulus
"""
return 2. * k1 * k2 / (k1 + k2) |
def duplicate(somelist):
"""
biore binary search na srodku listy
sprawdzam
:param somelist:
:return:
"""
emptylist = []
for i in somelist:
if len(emptylist) == 0:
emptylist.append(i)
else:
if i in emptylist:
return i
em... |
def translate(tile, offset):
"""
Move a tile. This returns a moved copy; the original is unchaged.
Parameters
----------
tile : tuple
containing y and x slice objects
offset : tuple
translation, given as ``(y, x)``
Returns
-------
tile : tuple
a copy; the in... |
def pretty_duration(seconds):
"""Return a pretty duration string
Parameters
----------
seconds : float
Duration in seconds
Examples
--------
>>> pretty_duration(2.1e-6)
'0.00ms'
>>> pretty_duration(2.1e-5)
'0.02ms'
>>> pretty_duration(2.1e-4)
'0.21ms'
>>> pr... |
def Lipinski(calc, exp, low, high):
"""
Input: listLike calculated and experimental data you want to compare
float low and high limits for the test
returns:
number of correctly predicted values (in or outside range)
number of false positives
number of false negatives
"""
correct = 0
... |
def build_group_name(four_p):
"""
:param four_p: (low click rate, high click rate, hazard rate, interrogation time)
:return: string
"""
#
lowrate = ('{:f}'.format(round(four_p[0], 2))).rstrip('0').rstrip('.')
highrate = ('{:f}'.format(round(four_p[1], 2))).rstrip('0').rstrip('.')
hazard_... |
def checkForOverlappingGrants(grant, frequency_range):
"""Returns True if a grant overlaps with a given frequency range.
If the lowFrequency or the highFrequency of the grant falls within the
low and high frequencies of the given range then the grant is considered
to be overlapping.
Args:
grant: A |Gran... |
def error_exists(checkResult):
"""check if in conditions array exists at least one non-False value (an error)
"""
for value in checkResult:
if value:
return True
return False |
def get_db_path(spider_dir, db_id):
""" Return path to SQLite database file.
Args:
spider_dir: path to SPIDER benchmark
db_id: database identifier
Returns:
path to SQLite database file
"""
return f'{spider_dir}/database/{db_id}/{db_id}.sqlite' |
def interpolation_search(sample_input, lowest, highest, item):
"""
function to search the item in a give list of item
:param sample_input: list of number
:param lowest: the lowest element on our list
:param highest: the highest element on our list
:param item: the item element to search in our l... |
def zigbee2mqtt_device_name(topic, data, srv=None):
"""Return the last part of the MQTT topic name."""
return dict(name=topic.split("/")[-1]) |
def compare_all_to_exported(filelist_a, filelist_b, barrel_name):
""" Check the difference between the list of files """
files_a = set(filelist_a)
files_b = set(filelist_b)
result = sorted(files_a.union(files_b).difference(files_a.intersection(files_b)))
result = ["export * from './{}'".format(elem.... |
def remove_invalid_characters(input_string):
"""
Edit a string by replacing underscores with spaces and removing commas, single quotes and new line characters
:param input_string: the string which needs to be altered
:return: edited string
"""
return input_string.replace(" ", "_").replace(",", "... |
def is_create_required(event):
"""
Indicates whether a create is required in order to update.
:param event: to check
"""
if event['RequestType'] == 'Create':
return True
new = event['ResourceProperties']
old = event['OldResourceProperties'] if 'OldResourceProperties' in event else n... |
def binary_search(array, element):
"""
Binary Search
Complexity: O(logN)
Requires a sorted array.
Small modifications needed to work
with descending order as well.
"""
lower = 0
upper = len(array) - 1
while lower <= upper:
mid = (lower+upper) // 2
... |
def log(x):
"""
Simulation to math.log with base e
No doctests needed
"""
n = 1e10
return n * ((x ** (1/n)) - 1) |
def is_port_free(port, host="localhost"):
"""Checks if port is open on host"""
#based on http://stackoverflow.com/a/35370008/952600
import socket
from contextlib import closing
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
if sock.connect_ex((host, port)) == 0:
... |
def axlbool(value):
""" convert suds.sax.text.Text to python bool
"""
if value is None:
return None
if not value:
return False
if value.lower() == 'true':
return True
return False |
def combination_sum_bottom_up(nums, target):
"""Find number of possible combinations in nums that add up to target, in bottom-up manner.
Keyword arguments:
nums -- positive integer array without duplicates
target -- integer describing what a valid combination should add to
"""
combs = [0] * (ta... |
def aslist(item):
"""
aslist wraps a single value in a list, or just returns the list
"""
return item if type(item) == list else [item] |
def parseDigits(digits: str, base: int) -> int:
"""
Wrapper around the "int" constructor that generates a slightly more
detailed ValueError message if the given string contains characters that
are not valid as digits in the given base.
"""
try:
return int(digits, base)
except ValueEr... |
def pi(p, q):
""" Calculates premium policy for insurance company
Args:
q (float): Coverage amount
p (float): Probability of loss
Returns:
(float): Premium policy of bundle
"""
return (p*q) |
def lists2dict(listA, listB):
""" Given two lists of the same length, merge them in one dictionary """
return dict(zip(listA, listB)) |
def convert_lcs_positions(index):
"""
Given the index of a pick in LCS order, returns the position id corresponding
to that index.
LCS picks are submitted in the following order
Index | Role | Position
0 Top 3
1 Jng 4
2 Mid 2
3 Adc 1
4 S... |
def write_bc(bcdict, bc="bc.dyn"):
"""write node BCs
Args:
bcdict: dict of node BCs, with DOF values
bc: (Default value = "bc.dyn")
Returns:
0
"""
with open(bc, 'w') as bcf:
bcf.write("$ Generated using bc.py\n")
bcf.write('*BOUNDARY_SPC_NODE\n')
f... |
def valid_odd_size(size):
"""
Validates that a kernel shape is of odd ints and of with 2 dimensions
:param size: the shape (size) to be checked
:return: False if size is invalid
"""
if type(size) not in (list, tuple):
return False
if len(size) != 2:
return False
if size[... |
def get_regex(value):
"""Returns regex string based on main parameter"""
return r'({}:\s*)(.+\S)'.format(value) |
def has_possible_route(total_route, sub_routes):
"""
Check how it is possible to construct the total route from the sub_routes (part a, b and c)
Sub_routes has 3 items (0, 1, 2)
"""
# start at idx
state = list()
state.append((total_route, []))
while len(state) > 0:
current_ro... |
def within_percent(a, b, percent):
"""Returns true if a is within some percent of b"""
return percent >= 100*abs(a-b)/b |
def validate_input(input_val):
"""
Helper function to check if the input is indeed a float
:param input_val: the value to check
:return: the floating point number if the input is of the right type, None if it cannot be converted
"""
try:
float_input = float(input_val)
return floa... |
def extract_time_spent_in_region(person_dict_list):
"""
Get the time spent in each region
Parameters
----------
person_dict_list: list
regions people have passed during vaccination lifecycle
Returns
-------
dict
time spent in each region
"""
# seperate the time v... |
def paint_text(text_str, color_str):
"""
Adds markup around given text.
Supports some colors by name instead of hexadecimal.
:param text_str:
:param color_str: (str) Hexadecimal color.
:return: (str)
"""
return '[color={color_str}]{text_str}[/color]'.format(text_str=text_str,
... |
def is_bbox(line):
"""is there a bbox as attribute of a changeset
i.e. min_lat, max_lon, min_lon, max_lin
"""
if 'min_lat' in line:
return True
return False |
def init_hash_counters():
"""
Use counters to create a simple output stats file in tandem with json details
Initialize counters to zero
"""
hash_counters = {}
hash_count_values = ['total samples', 'malware', 'mal_inactive_sig', 'mal_active_sig',
'mal_no_sig', 'grayware... |
def hms2stringTime(h, m, s, precision=5):
""" Convert a sexagesimal time to a formatted string.
Parameters
----------
hour, min, sec : int, float
precision : int
Returns
-------
String formatted HH:MM:SS.SSSSS
"""
if h < 0 or m < 0 or s < 0:
pm = '-'
else:
... |
def is_box_inside(in_box, out_box):
"""
check if in_box is inside out_box (both are 4 dim box coordinates in [x1, y1, x2, y2] format)
"""
xmin_o, ymin_o, xmax_o, ymax_o = out_box
xmin_i, ymin_i, xmax_i, ymax_i = in_box
if (xmin_o > xmin_i) or (xmax_o < xmax_i) or (ymin_o > ymin_i) or (ymax_... |
def edit_distance(list1, list2):
"""
Find the minimum number of insertions, deletions, or replacements required
to turn list1 into list2, using the typical dynamic programming algorithm.
>>> edit_distance('test', 'test')
0
>>> edit_distance([], [])
0
>>> edit_distance('test', 'toast')
... |
def _is_png(filename):
"""Determine if a file contains a PNG format image.
Args:
filename: string, path of the image file.
Returns:
boolean indicating if the image is a PNG.
"""
return '.png' in filename |
def create_flow_control(n):
"""returns a list for flow control. The list can be mutated outside
the function and will remain in memory"""
return [False] * n |
def add_to_stack(a,b):
"""
makes a list of lists of lists. Indices are [image i][antinode j][params within antinode j]
"""
if (a is None):
return [b]
return a + [b] |
def arithmetic_wrangle(x):
"""Do some non trivial arithmetic."""
result = -x**2/x**0.2
return result |
def checkEqual(lst: list)->bool:
"""
Small function to quickly check if all elements in a list have the same value.
Parameter:
- lst : input list
Returns:
Boolean: True if all are equal, False else.
Source: http://stackoverflow.com/q/3844948/
part of the thread: https... |
def add(x,y):
"""
Binary Adddition bing carried out
"""
carry=""
result=""
carry="0"
for i in range(len(x)-1,-1,-1):
a=carry[0]
b=x[i]
c=y[i]
if a==b and b==c and c=='0':
result="0"+result
carry="0"
elif a==b and b==c a... |
def hello(name):
"""
python3 fn.py Yazid
> Hello Yazid!
"""
return 'Hello {name}!'.format(name=name) |
def to_float(MIC):
"""
Ensures input can be compared to float, in case input is
string with inequalities
"""
MIC=str(MIC)
for equality_smb in ['=','<','>']:
MIC = MIC.replace(equality_smb,'')
return float(MIC) |
def is_kind_of_class(obj, a_class):
""" checks class inheritance
Args:
obj: object to evaluate
a_class: suspect father
"""
return isinstance(obj, a_class) |
def _calculate_score_for_underpaid(current_salary, level_salary):
"""
Maximize how much each dollar reduces percent diff from level salary. Higher scores get raise dollars first
:param current_salary:
:param level_salary:
:return:
"""
assert current_salary <= level_salary
absolute_diff =... |
def matrixMultVec(matrix, vector):
"""
Multiplies a matrix with a vector and returns the result as a new vector.
:param matrix: Matrix
:param vector: vector
:return: vector
"""
new_vector = []
x = 0
for row in matrix:
for index, number in enumerate(row):
x += numb... |
def remove_result_attr(result):
"""Remove all attributes from the output"""
filtered_list = []
for tup in result:
lis = list(tup)
removeset = set([2])
filtered_list.append(tuple([v for i, v in enumerate(lis) if i not in removeset]))
return filtered_list |
def mask(bits: int) -> int:
"""
Generate mask of specified size (sequence of '1')
"""
return (1 << bits) - 1 |
def _target_selectors(targets):
"""
Return the target selectors from the given target list.
Transforms the target lists that the client sends in annotation create and
update requests into our internal target_selectors format.
"""
# Any targets other than the first in the list are discarded.
... |
def get_all_species_alive_area(species_list, area):
"""Get all names of species that are alive from a certain area.
Parameters
----------
species_list : list of strings
List of all species.
area : str
name of area for which the species should be returned.
Returns
-------
... |
def setSizeToInt(size):
"""" Converts the sizes string notation to the corresponding integer
(in bytes). Input size can be given with the following
magnitudes: B, K, M and G.
"""
if isinstance(size, int):
return size
elif isinstance(size, float):
return int(size)
try:
... |
def time_format_store_ymdhms(dt, addMilliseconds=True):
"""
Return time format as y_m_d__h_m_s[_ms].
:param dt: The timestamp or date to convert to string
:type dt: datetime object or timestamp
:param addMilliseconds: If milliseconds should be added
:type addMilliseconds: bool
:return: T... |
def to_s3_model(*args):
""" Returns the S3 URL for to a model, rooted under
${REACH_S3_PREFIX}/models/"""
return (
'{{ conf.get("core", "reach_s3_prefix") }}'
'/models/%s'
) % '/'.join(args) |
def get_last_id(provider):
"""Load last known id from file."""
filename = ('last_known_id_{}.txt').format(provider)
try:
with open(filename, 'r') as (id_file):
id = id_file.read()
id_file.close()
if len(id) == 0:
id = 0
return int(id)
... |
def is_clustal_seq_line(line):
"""Returns True if line starts with a non-blank character but not 'CLUSTAL'.
Useful for filtering other lines out of the file.
"""
return line and (not line[0].isspace()) and\
(not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE')) |
def encode_byte(value):
"""Encode a byte type."""
return bytearray([value]) |
def convert_list_type(x, to_type=int):
"""Convert elements in list to given type."""
return list(map(to_type, x)) |
def get_type(name, attr_dict):
""" """
try:
v_type = attr_dict[name]["type"]
if v_type in ["string", str, "str", "String"]:
v_type = None
except KeyError:
v_type = None
return v_type |
def hello_my_user(user):
"""
this serves as a demo purpPOSTose
:param user:
:return: str
"""
return "Hello %s!" % user |
def triangular_number(n: int):
"""
>>> triangular_number(4) # 4 + 3 + 2 + 1
10
"""
assert n >= 0
return n * (n + 1) // 2 |
def try_parse_int(value):
"""Attempts to parse a string into an integer, returns 0 if unable to parse. No errors."""
try:
return int(value)
except:
# Not a bug or error, just for added clarity
print("Not a valid entry. Try again.")
return 0 |
def bounded(num, start, end):
"""Determine if a number is within the bounds of `start` and `end`.
:param num (int): An integer.
:param start (int): A start minimum.
:param end (int): An end maximum.
:rtype is_bounded (bool): Whether number is bounded by start and end.
"""
return num >= star... |
def delete_contact(contact_id):
"""
Deletes the contact for the id sent
Returns an "OK" message with code 200.
If the contact does not exists returns "Unexistent Contact" with code 404
:param contact_id: the contact id
"""
return "Not implemented", 500 |
def aggregate_f(loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore):
"""
Compute aggregate metric for xView3 scoring
Args:
loc_fscore (float): F1 score for overall maritime object detection
length_acc (float): Aggregate percent error for vessel length estimation
... |
def _permission_extract(sciobj_dict):
"""Return a dict of subject to list of permissions on object."""
return {
perm_subj: ["read", "write", "changePermission"][: perm_level + 1]
for perm_subj, perm_level in zip(
sciobj_dict["permission_subject"], sciobj_dict["permission_level"]
... |
def get_shape_kind(integration):
"""
Get data shape kind for given integration type.
"""
if integration == 'surface':
shape_kind = 'surface'
elif integration in ('volume', 'plate', 'surface_extra'):
shape_kind = 'volume'
elif integration == 'point':
shape_kind = 'point'... |
def tokenize(lines, token='word'):
"""Split text lines into word or character tokens."""
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('ERROR: unknown token type: ' + token) |
def get_range(time):
"""An function used to get the correct 4 hour interval for the TIME_BIN column
Takes a dataframe and creates a column with the times binned by every 4 hours
Args:
time (int): A time int representation in the format hhmmss
Ex: noon would be represented as 120000
Re... |
def normalize_color_tuple(h :int, s:int, x:int) -> tuple:
"""
Normalize an HSV or HSL tuple.
Args:
h: `int` in {0, ..., 360} corresponding to hue.
s: `int` in {0, ..., 100} corresponding to saturation.
x: `int` in {0, ..., 100} corresponding to light or value.
Returns:l
T... |
def action_color(status):
"""
Get a action color based on the workflow status.
"""
if status == 'success':
return 'good'
elif status == 'failure':
return 'danger'
else:
return 'warning' |
def is_independent_nfs(role):
"""NFS not on infra"""
return "nfs" in role and not (set(["infra", "etcd", "kubernetes_master"]) & set(role)) |
def str_to_bool(s):
"""
Basic converter for Python boolean values written as a str.
@param s: The value to convert.
@return: The boolean value of the given string.
@raises: ValueError if the string value cannot be converted.
"""
if s == 'True':
return True
elif s == 'False':
... |
def isvector(a):
"""
one-dimensional arrays having shape [N],
row and column matrices having shape [1 N] and
[N 1] correspondingly, and their generalizations
having shape [1 1 ... N ... 1 1 1]
"""
try:
return a.ndim-a.shape.count(1) == 1
except:
return False |
def std_url(url):
"""
Standardizes urls by removing protocoll and final slash.
"""
if url:
url = url.split("//")[-1]
if url.endswith("/"):
url = url[:len(url)-1]
return url |
def extensionOf(path):
"""Answer the extension of path. Answer None of there is no extension.
>>> extensionOf('../../images/myImage.jpg')
'jpg'
>>> extensionOf('aFile.PDF') # Answer a lowercase
'pdf'
>>> extensionOf('aFile') is None # No extension
True
>>> extensionOf('../../aFile') is ... |
def json_set_auths(struct, auth):
"""Recusrsively finds auth in script JSON and sets them.
Args:
struct: (dict) A dictionary representation fo the JSON script.
auth: (string) Either 'service' or 'user'.
Returns:
(struct) same structure but with all auth fields replaced.
"""
if isinst... |
def is_valid_email(email_address):
"""
Given a possible email address, determine if it is valid.
:param email_address: a string with a proposed email address
:return: true if email_address is valid, false if not
"""
valid = False
if '@' in email_address and '.' in email_address: # check... |
def mac_addr(address):
"""Convert a MAC address to a readable/printable string
Args:
address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06')
Returns:
str: Printable/readable MAC address
"""
return ':'.join('%02x' % ord(b) for b in address) |
def first_org_id_from_org_roles(org_roles):
""" Return first Jisc ID found in an objectOrganisationRole."""
for role in org_roles:
if not isinstance(role, dict):
continue
org = role.get('organisation')
if not isinstance(org, dict):
continue
org_id = org.ge... |
def update_effective_sample_size(
effective_sample_size,
batch_size,
forgetting_factor
):
"""
:param effective_sample_size:
:param batch_size:
:param forgetting_factor:
:return:
>>> update_effective_sample_size(1.0,1.0,1.0)
(2.0, 1.0)
"""
updated_sample_size = (
... |
def fib2(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a+b
return result |
def read_uint(data, start, length):
"""Extract a uint from a position in a sequence."""
return int.from_bytes(data[start:start+length], byteorder='big') |
def _get_md_from_url(url):
"""Get markdown name and network name from url."""
values = url.split('/')
return values[-1].split('.')[0] + '.md' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.