content stringlengths 42 6.51k |
|---|
def display_change(total_bill,amount_tendered):
"""
(float,float) -> float
Returns the difference as the variable "difference" in value between total_bill and amount_tendered, thus indicating
how much change is owed to the customer, or still owed to the MinMax store. The variable "difference" is formatt... |
def getSlope(p1, p2):
""" Returns the slope between the two given points. """
(x1, y1) = p1
(x2, y2) = p2
if x1 == x2:
return 99999999
return (y2 - y1) / (x2 - x1) |
def partition(array: list, beginning: int, end: int) -> int:
"""
Go through the array from left to right. If the number in
position i is bigger than the pivot (i.e. the last number
of the array) and the number in position j is smaller than
or equal to the pivot, then swap the two numbers and increas... |
def _retrieve_source_rankings(source_data):
"""Auxiliary function to collect SNIP and SJR data.
Returns list of lists in the form [mergedstatname, stat],
where mergedstatname - dictionary key joined with associated period
"""
out = []
for key in source_data:
stats = source_data[key]
... |
def ceildiv(x, y):
"""ceil(x/y)"""
return -(-x // y) |
def safe_get(dictionary, key):
"""
Safely get value from dictionary
"""
if key in dictionary:
return dictionary[key]
return None |
def pss(x, cost_ratio, ref_size):
"""
Returns: Size of a power-sizing model estimate as per the formula:
tsize = (cost_ratio)^-x * ref_size
"""
return ref_size * (cost_ratio) ** -x |
def isiterable(obj):
"""Checks if an object is iterable
Parameters
----------
obj: object
Object to check
Returns
-------
is_iterable: bool
Boolean variable indicating wether the object is iterable
Example
-------
>>> from pymatting import *
>>> l = []
... |
def hamming(set_1: set, set_2: set) -> float:
""" Return: HAMMING distance """
return len(set_1.symmetric_difference(set_2)) |
def get_duration_string(seconds):
"""
Get a string representation of the duration from seconds
:param float seconds:
:return str:
"""
# noinspection PyBroadException
try:
if seconds > 0:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
if h > 0:
... |
def calculate_deviation_square(error, sl):
"""
Calculate square deviation, e.g. between (observed) error and significance level
Parameters
----------
error :
observed error rate
sl :
significance level
Returns
-------
square deviation
"""
return (error - sl)... |
def CombineAcceptInfo(accept_info1, accept_info2):
"""Merge the state held in two dfa nodes.
When merging two independently built tries during incremental trie buildup,
we need to merge the state held in the two nodes from the different tries
(of the same prefix). If either of the dfa nodes are accepting, then... |
def get_goal_name(description):
"""Get goal name from description.
Parameters
----------
description : string
Goal description in the format "T.1.1 - Berika projekten med
25 nya resurser".
Returns
-------
str
Goal name in the format "T.1.1".
"""
return descr... |
def list2cmdline(lst):
""" convert list to a cmd.exe-compatible command string """
nlst = []
for arg in lst:
if not arg:
nlst.append('""')
elif (' ' in arg) or ('\t' in arg) or ('&' in arg) or ('|' in arg) or (';' in arg) or (',' in arg):
nlst.append('"%s"' % arg)
... |
def aio_s3_uri(aio_s3_bucket_name, aio_s3_key) -> str:
"""A valid S3 URI comprised of 's3://{bucket}/{key}'
:return: str
"""
return f"s3://{aio_s3_bucket_name}/{aio_s3_key}" |
def get_difference(first_adapter, second_adapter):
"""
If the connection between the adapters is valid, the joltage difference is returned.
"""
difference = second_adapter - first_adapter
return difference if difference in [1, 2, 3] else None |
def rescale(arr, vmin, vmax):
""" Rescale uniform values
Rescale the sampled values between 0 and 1 towards the real boundaries
of the parameter.
Parameters
-----------
arr : array
array of the sampled values
vmin : float
minimal value to rescale to
vmax : float
... |
def select_node_detail(node):
""" Print and build dict of uplinks for submenu once site is selected."""
uplink_list = {}
print(f"Select how to setup tunnel to {node['name']}")
print(f"1 Build SSH tunnel via SteelConnect Manager")
for index, uplink in enumerate(node['uplinks'], start=2):
prin... |
def model(session, Type='String', RepCap='', AttrID=1050512, buffsize=2048, action=['Get', '']):
"""[Model Inquiry <string>]
The model number or name reported by the physical instrument.
"""
return session, Type, RepCap, AttrID, buffsize, action |
def transform_ldap_user_attr_map(_value=None):
"""
Define the default user attribute mappings for active directory and OpenLDAP
These defaults have worked for me so far. If need be it can be added as module
parameters if writing in defaults doesn't work for most people
"""
attr_map_assignment = ... |
def _tanh_to_sigmoid(x):
"""
range [-1, 1] to range [0, 1]
:param x:
:return:
"""
return x * 0.5 + 0.5 |
def is_palindrome(n):
"""
Fill in the blanks '_____' to check if a number
is a palindrome.
>>> is_palindrome(12321)
True
>>> is_palindrome(42)
False
>>> is_palindrome(2015)
False
>>> is_palindrome(55)
True
"""
x, y = n, 0
f = lambda: y * 10 + (x % 10)
while x... |
def create_data_model(input_data, start_index=0):
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = input_data
data['num_vehicles'] = 1
data['depot'] = start_index
return data |
def quote_path(path: str) -> str:
"""
Quote a file path if it contains whitespace.
"""
if " " in path or "\t" in path:
return f'"{path}"'
else:
return path |
def is_level_correct(level):
"""Checking that insert level is correct ("EASY", "MEDIUM", "HARD")"""
levels = ["EASY", "MEDIUM", "HARD"]
if level in levels:
return True
else:
return False |
def format_object_str(object_type: str, object_str, object_id) -> str:
"""Returns a string with object type and a string representation of the object and/or the primary key"""
result = f'{object_type}'
if object_str:
result += f' "{object_str}"'
if object_id:
result += f' ({object_id})'
... |
def find_codon_diff(protein, mutated_protein):
"""
Function to find the effect the SNP had on the protein.
First compares the length of the proteins to see if the SNP caused a premature
stop codon, otherwise, returns the new codon.
"""
if len(protein) == len(mutated_protein):
for i in ra... |
def calcul_max(l: list) -> int:
""" returns the sum of the 2 highest elements of l """
_l = list(l)
max1 = max(_l)
_l.remove(max1)
max2 = max(_l)
return max1 + max2 |
def encodingToUse(encoding):
"""Tests whether the given encoding is known in the python runtime, or returns utf-8.
This function is used to ensure that a valid encoding is always used."""
if encoding == "CHARSET" or encoding == None:
return 'utf-8'
return encoding |
def make_unique(name, reserved_names):
"""Return a slug ensuring name is not in `reserved_names`.
:param name: The name to make unique.
:param reserved_names: A list of names the column must not be included in.
"""
while name in reserved_names:
name += '_'
return name |
def qualified_name(obj):
"""
Return a qualified name for `obj` (type or function).
"""
if obj.__name__ == "__builtin__":
return obj.__name__
else:
return "%s.%s" % (obj.__module__, obj.__name__) |
def text_alignment(x: float, y: float):
"""
Align text labels based on the x- and y-axis coordinate values.
This function is used for computing the appropriate alignment of the text
label.
For example, if the text is on the "right" side of the plot, we want it to
be left-aligned. If the text i... |
def sum_matching_digits(pairs):
"""Sum the digits that match the second item of the pair
Note that matching digits are single counted, not double.
For example:
[(1, 1)] -> 1
[(1, 1), (2, 2)] -> 3
"""
return sum(a for a, b in pairs) |
def _UpdateFertileSlotsShape(unused_op):
"""Shape function for UpdateFertileSlots Op."""
return [[None, 2], [None], [None]] |
def fizzbuzz(n: int) -> str:
"""
Outputs 'fizz', if the input is dividable by 5.
Outputs 'buzz', if the input is dividable by 7.
Outputs 'fizzbuzz', if the input is dividable by 5 and 7.
Example:
>>> fizzbuzz(35)
'fizzbuzz'
>>> fizzbuzz(36)
''
:param n: Positive... |
def smartQuote(stringToQuote):
"""Quote a string, allowing for strings that already are."""
localCopy = stringToQuote
if localCopy != None:
# Check beginning
if localCopy[0] != '"':
localCopy = '"' + localCopy
# Check end
if localCopy[-1] != '"':
local... |
def mean (p, include_zeros = True):
"""Sums all the channels and divide by their quantity (by default, counts zeros as well)"""
d = s = 0
for c in p:
s += c
d += include_zeros or c != 0
return s//d |
def LineRoughlyEqual(s1, s2):
"""Check whether disasms lines are equal ignoring whitespaces and comments."""
# strip comments.
# These are mainly used by objdump to print out the absolute address
# for rip relative jumps.
# e.g.
# 0x400408: ff 35 e2 0b 20 00 pushq 0x200be2(%rip) # 0x600ff0
s1,... |
def matrix_as_list(matrix, value=True):
"""Turn a matrix into a list of coordinates matching the given value."""
rows, cols = len(matrix), len(matrix[0])
cells = []
for row in range(rows):
for col in range(cols):
if matrix[row][col] == value:
cells.append((row, col))
... |
def select_merged_rings(selected_rings, indices, ranges):
"""Select indices and ranges for merged rings
This utility function filters the indices and ranges and returns
new (indices, ranges) that were selected in the selected_rings.
"""
new_indices = []
new_ranges = []
for ring in selected_... |
def analysis_sum(x, y):
"""Sum two integers."""
result = x + y
return result |
def cles(lessers, greaters):
"""
Common-Language Effect Size
Probability that a random draw from `greater` is in fact greater
than a random draw from `lesser`.
Args:
lesser, greater: Iterables of comparables.
"""
numerator = 0
lessers, greaters = sorted(lessers), sorted(greaters)
... |
def kmin(l1, l2, k):
"""
Return the k smaller elements of two lists of tuples, sorted by their first
element. If there are not enough elements, return all of them, sorted.
Params:
l1 (list of tuples): first list. Must be sorted.
l2 (list of tuples): second list. Must be sorted.
... |
def _predict_url(args):
"""
(Optional) Helper function to make prediction on an URL
"""
message = 'Not implemented (predict_url())'
message = {"Error": message}
return message |
def group(data, num):
""" Split data into chunks of num chars each """
return [data[i:i+num] for i in range(0, len(data), num)] |
def process_rf(strength: int) -> str:
"""Process wifi signal strength and return string for display."""
if strength >= 90:
return "Low"
if strength >= 76:
return "Medium"
if strength >= 60:
return "High"
return "Full" |
def write_symbol_table(table, filename):
"""Save symbol table to filename and return the number of symbols written.
The table is written to a text file in the CP/M .sym file format. No file
is created if the table is empty."""
symbol_count = len(table)
if symbol_count == 0:
return symbo... |
def km2ft(km):
"""
Pass kms to foot
INPUTS
km : float of kms
"""
if km is not None:
return (km/1.609)*5280
else:
return None |
def parse(fpaths, other=None):
"""Parse namespace_packages.txt files."""
result = set(other or [])
for fpath in fpaths:
with open(fpath, 'r') as fp:
for line in fp:
if line:
result.add(line.strip())
return result |
def visparamsListToStr(params):
""" Transform a list to a string formated as needed by
ee.data.getMapId
:param params: params to convert
:type params: list
:return: a string formated as needed by ee.data.getMapId
:rtype: str
"""
n = len(params)
if n == 1:
newbands = '{}'... |
def main4(args):
"""Plugin registered for the other collector"""
return 'main4', args |
def make_dict(in_text):
"""
Create a counter of the string
"""
my_dict = dict()
for c in in_text:
if c in [' ', '\n']:
continue
if c not in my_dict.keys():
my_dict[c] = 1
else:
my_dict[c] += 1
return my_dict |
def escape(value: str) -> str:
"""Escape single quotes."""
return value.replace("'", "''") |
def make_win_metric(metric, win):
""" Format the name of a windowed metric. """
return f"{metric}-windowed-minRtt{win}" |
def filename_to_label(filename):
""" dewisott """
if filename.endswith(".h5"):
filename = filename[:-3]
return filename |
def take_one(ls):
""" Extract singleton from list """
assert len(ls) == 1
return ls[0] |
def sub_tracks(t_list_a, t_list_b):
"""
:param t_list_a:
:param t_list_b:
:return:
"""
tracks = {}
for t in t_list_a:
tracks[t.track_id] = t
for t in t_list_b:
tid = t.track_id
if tracks.get(tid, 0):
del tracks[tid]
return list(tracks.values()) |
def escape(string, size=55):
"""Escape string for dot file"""
if not size or not string:
return ""
if len(string) > size:
half_size = (size - 5) // 2
string = string[:half_size] + " ... " + string[-half_size:]
return "" if string is None else string.replace('"', '\\"') |
def fstat_cl(line):
"""
Extracts integer changelist from an fstat line, unless it starts
with '#' or is empty, in which case the returned changelist is 0.
WARNING: Can not detect 5-col/7-col format and will just return
line as is.
Returns a tuple: changelist, line
"""
line = l... |
def compare_lists(list_a, list_b):
"""Compare the content of tho lists regardless items order."""
if len(list_a) != len(list_b):
return False
if not list_a:
return True
value, *new_a = list_a
if value not in list_b:
return False
new_b = list(filter(lambda x: x != value, l... |
def build_person(first_name,last_name,age=None):
"""Return a dictionary of information about a person"""
person = {'first':first_name,'last':last_name}
if age:
person['age']=age
return person |
def titlesplit(src='', linelen=24):
"""Split a string on word boundaries to try and fit into 3 fixed lines."""
ret = ['', '', '']
words = src.split()
wlen = len(words)
if wlen > 0:
line = 0
ret[line] = words.pop(0)
for word in words:
pos = len(ret[line])
... |
def format_float(f):
"""Format a Python float in a friendly way.
f -- float or int
This is intended for values like komi or win counts, which will be either
integers or half-integers.
"""
if f == int(f):
return str(int(f))
else:
return str(f) |
def get_test_case_and_alg(basename):
"""
Extracts the changefile name and algorithm name
from the basename of the file, e.g.
changefile100Lazy Floyd-Warshall.out yields the output
(changefile100, Lazy Floyd-Warshall)
"""
# Skip "changefile" in the search of an integer
i = 10
while True:
try:
# Check if we... |
def checksum(number):
"""Calculate the checksum."""
return int(number) % 11 |
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) |
def dns_sortkey(name):
"""Get the sort key of a domain name"""
reversed_parts = name.lower().split('.')[::-1]
# Make sure the uppercase domain got before the lowercase one, for two same domains
# BUT a.tld stays before subdomain.a.tld, so do not append to the list
return (reversed_parts, name) |
def get_len_of_range(start, stop, step):
"""Get the length of a (start, stop, step) range."""
n = 0
if start < stop:
n = ((stop - start - 1) // step + 1);
return n |
def _format_lazy(format_string, *args, **kwargs):
"""
Apply str.format() on 'format_string' where format_string, args,
and/or kwargs might be lazy.
"""
return format_string.format(*args, **kwargs) |
def normalize(countries_list):
"""
Given the list, 'countries_list', containing the filenames, the function
returns a normalized list with uppercase version of all the filenames in it.
"""
normalized_list = []
for item in countries_list:
normalized_list.append(item.upper())
return n... |
def capitalize(s: str) -> str:
"""Capitalize the first character of a string."""
if s == '':
return ''
else:
return s[0].upper() + s[1:] |
def validate_base_url(base_url):
"""
Validate the URL entered by the user
:param base_url: the raw url entered by the user
:return: the checked and cleaned URL
"""
instance_url = base_url
instance_url = instance_url.lower()
# ends with a slash? lets remove this
if instance_url.endsw... |
def list_events(service, selected_calendars, user_defined_begin_date, user_defined_end_date):
"""
Given a google 'service' object and list of selected calendars, return a list of
events from the selected calendars within the submitted date range.
Each event is represented by a dict.
"""
page_tok... |
def make_wkt_polygon(x_min, y_min, x_max, y_max):
"""Creates a well known text (WKT) polygon geometry for insertion into database"""
return f"POLYGON(({x_min} {y_min}, {x_min} {y_max}, {x_max} {y_max}, {x_max} {y_min}, {x_min} {y_min}))" |
def big_vote_power(karma):
"""See
https://github.com/LessWrong2/Lesswrong2/blob/devel/packages/lesswrong/lib/voting/new_vote_types.ts
for the vote power implementation. See also the blog post at
https://lw2.issarice.com/posts/7Sx3CJXA7JHxY2yDG/strong-votes-update-deployed#Vote_Power_by_Karma"""
if k... |
def poly_learning_rate(base_lr, curr_iter, max_iter, power=0.9):
"""poly learning rate policy"""
lr = base_lr * (1 - float(curr_iter) / max_iter) ** power
return lr |
def make_carousel_column(text, actions, title=None, image_url=None,
resource_id=None, default_action=None,
i18n_image_urls=None, i18_resource_ids=None,
i18n_texts=None, i18n_titles=None):
"""
create carousel message column content.
... |
def cleave(sequence, index):
"""
Cleaves a sequence in two, returning a pair of items before the index and
items at and after the index.
"""
return sequence[:index], sequence[index:] |
def transform_gcp_vpcs(vpc_res):
"""
Transform the VPC response object for Neo4j ingestion
:param vpc_res: The return data
:return: List of VPCs ready for ingestion to Neo4j
"""
vpc_list = []
# prefix has the form `projects/{project ID}/global/networks`
prefix = vpc_res['id']
projec... |
def conv_output_length(input_length, filter_size,
stride, border_mode, pad=0):
"""
Helper function to compute the output size of a convolution operation
"""
if input_length is None:
return None
if border_mode == 'valid':
output_length = input_length - filter_si... |
def _is_prime(n):
"""
Return True iff n is prime
Source: http://stackoverflow.com/a/1801446
"""
if n in (2, 3):
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
... |
def get_photos_by_attribute(photos, attribute, values, ignore_case):
"""Search for photos based on values being in PhotoInfo.attribute
Args:
photos: a list of PhotoInfo objects
attribute: str, name of PhotoInfo attribute to search (e.g. keywords, persons, etc)
values: list of values to ... |
def pulse_series_dose(t, X1, X2=0., pulse_width=0.1, interval=0.1):
"""Pulse function for dose administration, with X1 and X2 amounts
alternately administered.
:param t: current time point
:type t: float
:param X1: amount of dose administered in high pulse
:type X1: float
:param X2: amo... |
def color_string_to_rgb(color):
"""Convert color string to a list of RBG integers.
Args:
color: the string color value for example "250,0,0"
Returns:
color: as a list of RGB integers for example [250,0,0]
"""
return [*map(int, color.split(","))] |
def max_key(value, key):
"""Returns the maximum value in a 'column' in a list of dictionaries or objects.
Positional arguments:
value -- list of dictionaries or objects to iterate through.
Returns:
Sum of the values.
"""
values = [r.get(key, 0) if hasattr(r, 'get') else getattr(r, key, 0) ... |
def extract_percentage(string):
"""
Extract number from string following this pattern:
78.80% -> 78.8
Also will round to 2 decimal places
"""
try:
trimmed = string.strip().replace(",", "").replace(" ", "")
number = float(trimmed[:-1])
return round(number, 2)
except Va... |
def degrees_to_cardinal(degrees):
"""Convert degrees >= 0 to one of 16 cardinal directions."""
CARDINALS = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
degrees = float(degrees)
if degrees < 0: return None
i = (degrees + 11.25)/22.5
ret... |
def _find_threshold(t, thresholds):
"""
find the appropriate cut-off
:param t:
:param thresholds:
:return:
"""
for index in range(len(thresholds) - 1):
if thresholds[index] <= t < thresholds[index + 1]:
return index
return len(thresholds) - 1 |
def validate_data(data):
"""
Validate that the request from Slack contains all the data we need
:param dict data:
:return bool:
"""
if not data.get("response_url"):
return False
if not data.get("token"):
return False
if not data.get("command"):
return False
i... |
def escape_special_char(string):
"""
Is called on all paths to remove all special characters but it's not good.
Should be moved in core
Should be called only in get_wrapper_path and unescape_special_char in get_entry
and in script += 'menu_click... in menu_click as it's already done
... |
def in_rich_compare(item, list):
""" Tests whether the item is in the given list. This is mainly to work
around the rich-compare bug in pysvn. This is not identical to the "in"
operator when used for substring testing.
"""
in_list = False
if list is not None:
for thing in list:... |
def ipath(i):
"""Returns path names '/test 1', '/test 2', ... """
return f"/test {i}" |
def _guess_platform_tag(epd_platform):
""" Guess the platform tag from the given epd_platform.
Parameters
----------
epd_platform : EPDPlatform or None
"""
if epd_platform is None:
return None
else:
return epd_platform.pep425_tag |
def get_provenance_record(ancestor_files, caption, statistics,
domains, plot_type='bar'):
"""Get Provenance record."""
record = {
'caption': caption,
'statistics': statistics,
'domains': domains,
'plot_type': plot_type,
'themes': ['phys'],
... |
def mlo(i, j): # pragma: no cover
"""Auxiliary function for La Budde's algorithm.
See `arXiv:1104.3769 <https://arxiv.org/abs/1104.3769v1>`_.
.. note::
The La Budde paper uses indices that start counting at 1 so this function
lowers them to start counting at 0.
Args:
matrix (... |
def swap_links(F1, F2):
"""
Obtains the fidelity of a link produced using entanglement swapping assuming Werner states
:param F1: type float
Fidelity of link 1
:param F2: type float
Fidelity of link 2
:return: type float
Fidelity of the link produced by swapping link 1 and 2
... |
def combine_metrics(metrics_data):
"""
Merge all metrics dictionaries in list into a single object.
"""
combined_metrics = metrics_data[0]
for d in metrics_data[1:]:
combined_metrics.update(d)
return combined_metrics |
def div_roundup(a, b):
""" Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) / int(b) |
def to_path_list(key_list):
"""
Turns a list of s3.boto.path.Key objects
into a list of strings representing paths.
Args:
key_list(List(s3.boto.path.Key))
Returns:
List(basestring)
"""
new_list = [key.name for key in key_list]
return new_list |
def get_index(obj, iterable):
"""
Find the index of the first instance of an obj in a list. Needed to prevent
Python from using __eq__ method which throws errors for ndarrays
"""
index = 0
for element in iterable:
if element is obj:
return index
index += 1
raise V... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.