content stringlengths 42 6.51k |
|---|
def draw_dot(image=None, coordinates=None,
radius=None, color=None):
"""
Generate a dot on a given image canvas at the given coordinates
:param image: Pillow/PIL Image Canvas
:param coordinates: coordinate pair that will be the center of the dot
:param radius: radius size of the dot
... |
def get_attribute(obj: dict, path: list):
"""
Get attribute iteratively from a json object.
:param obj: object to iterate on
:param path: list of string to get sub path within json
:return: the value if the path is accessible, empty string if not found
"""
current_location = obj
for tok... |
def equal_weight(x, y):
"""Return integer one (dummy method for equally weighting)."""
# everything gets 1 vote
return 1 |
def _acceptance_tolerance_band(
upper_acceptance_limit,
lower_acceptance_limit,
gradient_upper_acceptance_limit,
gradient_lower_acceptance_limit,
delta_product_change_reversal_point,
max_31_0,
min_31_0,
):
"""
inner loop of acceptance_tolerance_band
:param upper_acceptance_limit:... |
def space_timesteps(num_timesteps, section_counts):
"""
Create a list of timesteps to use from an original diffusion process,
given the number of timesteps we want to take from equally-sized portions
of the original process.
For example, if there's 300 timesteps and the section counts are [10,15,20... |
def build_select_unnamed(table, to_select, where, join='AND'):
"""
Build an select request with multiple parameters.
Parameters
----------
table : str
Table where query will be directed.
to_set : iterable
The list of columns to select
where : iterable
The list of con... |
def break_long_string(string: str, max_len: int = 70, indent: int = 0) -> str:
"""Break long string into shorter strings of max_len (with indent added)"""
import numpy as np
string = " ".join(
string.split(" ")
) # convert multiple consecutive white spaces to single
content = string.split(... |
def highlight_example(text, highlighted):
"""'Highlights' ALL the highlighted parts of the word usage example with * characters.
Args:
text: The text of the example
highlighted: Indexes of the highlighted parts' indexes
Returns:
The highlighted word usage example
"""
def ... |
def _rzfill(string, to_len):
"""right-pad a string with zeros to the given length"""
if len(string) > to_len:
raise ValueError("string is already longer than to_len")
return string + '0' * (to_len - len(string)) |
def alcohol_by_volume_alternative(og, fg):
"""
Alcohol by Volume Alternative Calculation
:param float og: Original Gravity
:param float fg: Final Gravity
:return: Alcohol by Volume decimal percentage
:rtype: float
Alternate Formula:
A more complex equation which attempts to provide gr... |
def _run(test, num_samples=None, num_iters=None, verbose=None,
measure_memory=False):
"""Helper function that constructs tuple with arguments for run method."""
return (
test, num_samples, num_iters, verbose, measure_memory) |
def string_empty(string: str) -> bool:
"""Return True if the input string is None or whitespace."""
return (string is None) or not (string and string.strip()) |
def prefix_match(query, db):
"""Naive implementation of "is seq prefix of one in expecteds or vice versa"."""
for entry in db:
min_len = min(len(query), len(entry))
if query[:min_len] == entry[:min_len]:
return True
return False |
def fib_fast(n):
"""Source: http://www.nayuki.io/res/fast-fibonacci-algorithms/fastfibonacci.py
Further reading: http://www.nayuki.io/page/fast-fibonacci-algorithms
"""
if n == 0:
return (0, 1)
else:
a, b = fib_fast(n / 2)
c = a * (b * 2 - a)
d = a * a + b * b
... |
def complete_url(string):
"""Return complete url"""
return "http://www.bhinneka.com" + string |
def _get_boundary(vs, boundary_string):
""" Return slice representing boundary
Parameters
----------
boundary_string
Identifer for boundary. May take one of the following values:
SURFACE: [:, :, -1] only the top layer
BOTTOM: bottom_mask as set by veros
else... |
def batch_statistics(batch):
"""
Computes the total number of task and the number of labeled tasks in a batch.
Args:
batch: identifier of a batch
Returns: total number of tasks in batch, number of labeled tasks in batch
"""
lc = 0
for task in batch["tasks"]:
if task["is_lab... |
def get_player(equipment, hit_points):
"""Get player based on equipment and hit_points."""
values = {'Damage': 0, 'Armor': 0}
for _, attributes in equipment:
for attribute in ('Damage', 'Armor'):
values[attribute] += attributes[attribute]
return {'Hit Points': hit_points,
... |
def list_union(l1,l2):
"""Return union of elements in two lists"""
return list(set().union(l1,l2)) |
def qmap(f, q):
"""
Apply `f` post-order to all sub-terms in query term `q`.
"""
if hasattr(q, '_fields'):
attrs = []
for field in q._fields:
attr = getattr(q, field)
attrs.append(qmap(f, attr))
cls = type(q)
obj = cls(*attrs)
return f(obj... |
def list_append_all_newline(list_item: list) -> list:
"""
Append a newline character to every list_item in list object.
:param list_item: A list object to append newlines to.
:return list: A list object with newlines appended.
"""
return list(map(lambda x: f'{x}\n', list_item)) |
def extract_pairs_from_lines(lines):
"""Extract pairs from raw lines."""
collected_pairs = []
for i in range(len(lines) - 1):
first_line = lines[i].strip()
second_line = lines[i+1].strip()
if first_line and second_line:
collected_pairs.append([first_line, second_line])
... |
def get_compression_effort(p_in: int, p_out: int, flow_rate: int) -> float:
"""Calculate the required electricity consumption from the compressor given
an inlet and outlet pressure and a flow rate for hydrogen."""
# result is shaft power [kW] and compressor size [kW]
# flow_rate = mass flow rate (kg/da... |
def sort_dict(in_struct):
"""Recursively sort a dictionary by dictionary keys. (saves WS the trouble)"""
if isinstance(in_struct, dict):
return {k: sort_dict(in_struct[k]) for k in sorted(in_struct)}
elif isinstance(in_struct, list):
return [sort_dict(k) for k in in_struct]
# return ... |
def get_neighbors_and_bond_types(atom_idx, list_of_bonds, atomic_symbols, bond_types):
""" Returns the bonds for the current atom. """
if not len(list_of_bonds) == len(bond_types):
raise ValueError(('list_of_bonds(%d) and bond_types(%d) should be of the same ' +
'length.')%(len(list_of_bon... |
def octetstr_2_string(bytes_string):
"""Convert SNMP OCTETSTR to string.
Args:
bytes_string: Binary value to convert
Returns:
result: String equivalent of bytes_string
"""
# Initialize key variables
octet_string = bytes_string.decode('utf-8')
# Convert and return
resu... |
def motion_dollar(input_line, cur, count):
"""Go to end of line and return position.
See Also:
`motion_base()`.
"""
pos = len(input_line)
return pos, False, False |
def listify(x):
"""Turn argument into a list.
This is a convenience function that allows strings
to be used as a shorthand for [string] in some arguments.
Returns None for None.
Returns a list for a list or tuple.
Returns [x] for anything else.
:param x: value to be listified.
"""
... |
def has_colours(stream):
"""Check if terminal supports colors."""
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
... |
def shift_to_the_left(array, dist, pad=True, trim=True):
"""Shift array to the left.
:param array: An iterable object.
:type array: iterable object
:param dist: how far you want to shift
:type disk: int
:param pad: pad array[-1] to the right.
:type pad: boolean (default True)
:param tri... |
def generate_primes(n: int):
"""
We iterate until we found the right length by checking if remainders with current primes are !=0
"""
res = [2]
length = 1
curr = 3
while length < n:
# Implicit int -> bool there + using the all function.
if all([curr%e for e in res]):
... |
def sortsplit(array, size):
"""Returns array split into different lists in round-robin order.
A fun way to split up a list in round-robin order into separate lists.
Args:
array : list
List of items to be split into separate lists.
size : type
Number of lists in whic... |
def bubble_sort(A, show_progress=False):
"""
Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in wrong order.
"""
for i in range(len(A) - 1):
swapped = False
for j in range(0, len(A) - i - 1):
if A[j] > A[... |
def find_min(list_, i):
"""
Return the index of the smallest item in list_[i:].
@param list list_: list to search
@param int i: index to search from
@rtype: int
>>> find_min([1, 2, 3], 1)
1
"""
smallest = i
# for j in range(i + 1, len(list_)):
list_len = len(list_)
for j... |
def u_to_l_ratio(data):
"""
:param data_rdd: wikipedia content to be pre-processed
:return: upper to lower case transformed content
"""
chars = list(data)
upper_count = sum([char.isupper() for char in chars])
lower_count = sum([char.islower() for char in chars])
return round((1 + (upper_... |
def zero_one_loss(f_x,y_true):
"""
Compute the zero-one loss given the returned value f_x from
a linear discrimination function on the feature x and its label y
"""
if f_x*y_true>=0:
return 0
else:
return 1 |
def dms(dec):
"""converts decimal degree coordinates to a usgs station id
:param dec: latitude or longitude value in decimal degrees
:return: usgs id value
.. note:: https://help.waterdata.usgs.gov/faq/sites/do-station-numbers-have-any-particular-meaning
"""
DD = str(int(abs(dec)))
... |
def get_events_per_second_api(replay, mods):
"""Gets coordinates and key pressed per second for API"""
events = []
time = 0
replay_events = replay.split(",")
for event in replay_events:
values = event.split("|")
try:
time += float(values[0])
except ValueError:
... |
def set_config_paths(config, private_config, builder_path, builder_private_path):
"""
hook up the actual location of the config files, based on our continuum config
"""
new_config = {}
new_private_config = {}
for key in config.keys():
new_config[key] = builder_path + "/" + config[key]
... |
def sort_process_stats_rows(process_stats, column, top, reverse=True):
"""
Sorts process statistics by specified column.
Args:
process_stats: A list of process statistics.
column: An int representing a column number the list should be sorted by.
top: An int representing a process count to be printed.... |
def findRadius(houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
import bisect
heaters.sort()
dis=[]
for h in houses:
i = bisect.bisect(heaters, h)
if i==0:
dis.append(heaters[0]-h)
if i==len(heaters):
... |
def split_nonsyllabic_prob(string, onsets, codas):
"""
Guesses split between onset and coda in list with no found syllabic segments
Parameters
----------
string : iterable
the phones to search through
onsets : iterable
an iterable of possible onsets
codas : iterable
... |
def strip_www_from_domain(domain):
"""Strip www. from beginning of domain names.
Args:
domain: string with a full domain, eg. www.google.com
Returns:
string: Domain without any www, eg: google.com
"""
if domain.startswith('www.'):
return domain[4:]
return domain |
def get_folder(experiment_id: int):
"""Get the folder-name based on the experiment's ID."""
assert type(experiment_id) == int
return f"experiment{experiment_id}" |
def defuzz_data(dataset, change, cmpr):
""" Remove crap entries according to cmpr's return """
index = 1
while index < (len(dataset) - 1):
pre = dataset[index - 1]
cur = dataset[index]
post = dataset[index + 1]
if cmpr(change, pre, cur, post):
del dataset[index]
... |
def anagram_prime(s1, s2):
"""Write a method to decide if two strings are anagrams or not."""
# O(n) time, O(1) space
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
product1 = 1
for char1 in s1:
product1 *= prime... |
def _death_birth_i(state_old, state_new):
"""
Parameters
----------
state_old : dict or pd.Series
Dictionary or pd.Series with the keys "s", "i", and "r".
state_new : dict or pd.Series
Same type requirements as for the `state_old` argument in this function
apply.
Returns... |
def text_string(value, encoding='utf-8'):
"""Convert a string, which can either be bytes or unicode, to
unicode.
Text (unicode) is left untouched; bytes are decoded. This is useful
to convert from a "native string" (bytes on Python 2, str on Python
3) to a consistently unicode value.
"""
if... |
def flatten(*args):
"""Recursively flattens a list containing other lists or
single items into a list.
Examples::
>>> flatten()
[]
>>> flatten(2)
[2]
>>> flatten(2, 3, 4)
[2, 3, 4]
>>> flatten([2, 3, 4])
[2, 3, 4]
>>> flatten([[2,... |
def exp_len(exp):
"""Given expresion in tuple format, returns expression length"""
if type(exp) == str:
return 1
else:
return sum(exp_len(x) for x in exp) |
def _merge_dicts(user, default):
"""Merge corpus config with default config, letting user values override default values."""
if isinstance(user, dict) and isinstance(default, dict):
for k, v in default.items():
if k not in user:
user[k] = v
else:
u... |
def startstrip(string: str, part: str) -> str:
"""
Remove ``part`` from beginning of ``string`` if ``string`` startswith ``part``.
Args:
string (str): source string.
part (str): removing part.
Returns:
str: removed part.
"""
if string.startswith(part):
return st... |
def prep_next_item_dataset(
k,
item_sequence,
user_negative_items,
candidate_sample_prob=None,
):
"""Converts raw user-item dataset to a dataset with a dictionary of features.
The produced dataset uses the kth item from the end as the next item to be
predicted and items before that as the input s... |
def chisquare(y1, y2, yerr):
"""
Figure out the chi square value for the model, given some data points,
model points, and errors
@params
y1 - data points
y2 - model points
yerr - data point errorbars
"""
chisq= 0.0
for i in range(len(y1)):
chisq = chisq +... |
def _uuid_prefix(uuids, step=4, maxlen=32):
"""Get smallest multiple of `step` len prefix that gives unique values.
"""
full = set(uuids)
for n in range(step, maxlen, step):
prefixes = {u[:n] for u in uuids}
if len(prefixes) == len(full):
return n
return maxlen |
def to_float(s):
"""
Converts a percentage back into a float (essentially the inverse of to_percentage()
Parameters
----------
s: str
Returns
-------
float
Examples
--------
s = "33.33%"
--> 0.3333
"""
n = float(s[:-1])/100
return n |
def freq_by_date(d, time_frame, bin_size):
"""
Takes in a dictionary of novel objects mapped to relative frequencies, and
returns a dictionary with frequencies binned by decades into lists
List name is mapped to the list of frequencies
list names key:
date_to_1810 - publication dates before and... |
def str_is_float(value):
"""Test if a string can be parsed into a float.
:returns: True or False
"""
try:
_ = float(value)
return True
except ValueError:
return False |
def unique(seq, idfun=repr):
"""
Returns a list of unique items in a sequence of items. There are lots of ways to
do this; here is one.
"""
seen = {}
return [seen.setdefault(idfun(e),e) for e in seq if idfun(e) not in seen] |
def tostring(array):
"""
1D array to string
"""
return ",".join([str(x) for x in array]) |
def update_topic(args_dict, topics, topic_data):
"""
Update topics with different kind of data
"""
updated_topics = {}
topic_dict = {key: value for key, value in topics.items()
if args_dict[topic_data[key]] is not None}
for key, value in topic_dict.items():
if value in ... |
def replace_empty_string(sample):
"""replace empty strings with a non empty string to force
type guessing to use string"""
def replace(cell):
if cell.value == '':
cell.value = 'empty_string'
return cell
return [[replace(cell) for cell in row] for row in sample] |
def get_url(entry):
""" Return URL from response if it was received otherwise requested URL. """
try:
return entry["response"]["url"]
except KeyError:
return entry["request"]["url"] |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'guest' and password == 'password' |
def gen_Location(coordinate_str):
"""Generate a Location object."""
Area = {
"@type": "Location",
"Location": coordinate_str
}
return Area |
def find_domain_range(record):
"""Find domain and range info of a record in schema"""
response = {"domain": [], "range": []}
if "http://schema.org/domainIncludes" in record:
if isinstance(record["http://schema.org/domainIncludes"], dict):
response["domain"] = [record["http://schema.org/d... |
def c2_normal_to_sub_bn(key, model_keys):
"""
Convert BN parameters to Sub-BN parameters if model contains Sub-BNs.
Args:
key (OrderedDict): source dict of parameters.
mdoel_key (OrderedDict): target dict of parameters.
Returns:
new_sd (OrderedDict): converted dict of parameters.... |
def assert_extension(path, extension):
"""
Assert that a path is ends with an extension, or add it to the result path.
:param path: the path to be checked.
:param extension: the extension the path should ends with.
:return: the result path, None if input is None.
"""
if path is None:
... |
def nextInteger(user_list):
"""
"""
# Min value of item
if any(x < -1000000 for x in user_list):
raise Exception('Items exceeds the minimum integer size of -1,000,000.')
sys.exit()
# Max value of item
if any(x > 1000000 for x in user_list):
raise Exception('Items exceeds... |
def strip_and_split(line):
"""
Helper function which saves a few lines of code elsewhere
:param line:
:return:
"""
line = line.strip().split()
stripped_line = [subline.strip() for subline in line]
return stripped_line |
def seconds_to_timestamp(seconds):
"""
Convert from seconds to a timestamp
"""
minutes, seconds = divmod(float(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%06.3f" % (hours, minutes, seconds) |
def _p(pp, name):
"""
make prefix-appended name
:param pp: prefix
:param name: name
:return: pp_name
"""
return '%s_%s' % (pp, name) |
def get_participant_ids(slots):
"""Get the participant ids for a the set's slots
there should be two for singles and four for doubles"""
participant_ids = []
for slot in slots:
entrant = slot['entrant']
participant_ids.append(entrant['id'])
return participant_ids |
def calculate_president_bop(data, votes):
"""
A function for calculating the presidential balance-of-power.
"""
data['total'] += votes
majority = data['needed_for_majority'] - votes
if majority < 0:
majority = 0
data['needed_for_majority'] = majority
return data |
def double_quoted(keywords):
"""
Usage:
{% double_quoted str1 str2 as str_1_2 %}
"""
quoted = '"{}"'.format(keywords)
return quoted |
def precipitable_water(ta, ea):
"""
Estimate the precipitable water from Prata (1996) :cite:`Prata:1996`
"""
return 4650*ea/ta |
def compatible(cluster_a, value_a, cluster_b, value_b):
"""
Checks compatibility of clusters of variables.
Compatibility means that values agree on common
variables.
"""
for node in list(cluster_a):
position_a = cluster_a.index(node)
if node in list(cluster_b):
positi... |
def get_attr(attrs, key):
""" Get the attribute that corresponds to the given key"""
path = key.split('.')
dict_ = attrs
for part in path:
if part.isdigit():
part = int(part)
# Let it raise the appropriate exception
dict_ = dict_[part]
return dict_ |
def mean_inplace(tensor_1, tensor_2):
"""
function for meaning softmax outputs from two networks,
Cuurently not able to use as inplace changes to the tensor
cause problems with backpropagation
:param tensor_1:
:param tensor_2:
:return:
"""
for i in range(len(tensor_1)):
... |
def has_license(lines):
"""Check if first two lines contain a license header."""
if len(lines) < 2:
return False
return (
"SPDX-FileCopyrightText:" in lines[0] and "SPDX-License-Identifier:" in lines[1]
) |
def build_relabel_dict(x):
"""Relabel the input ids to continuous ids that starts from zero.
The new id follows the order of the given node id list.
Parameters
----------
x : list
The input ids.
Returns
-------
relabel_dict : dict
Dict from old id to new id.
"""
re... |
def list_to_dict(node_list: list):
"""
Convert the list to a dictionary,
Create a dictionary, key is a element in the list,
value is a element which next the key, if no exists, the value is None.
Args:
node_list (list): normal, list of node
Returns:
schema (dict): a dictionary
... |
def get_game_ids(cursor, tournament=None, patch=None):
"""
get_game_ids queries the connected db for game ids which match the
input tournament and patch strings.
Args:
cursor (sqlite cursor): cursor used to execute commmands
tournament (string, optional): id string for tournament (ie "2... |
def checkAnchorOverlap(xa, xb, ya, yb):
"""
check the overlap of a region for the same chromosome
"""
if (ya <= xa <= yb) or (ya <= xb <= yb) or (ya <= xa <= xb <= yb):
return True
if (xa <= ya <= xb) or (xa <= yb <= xb) or (xa <= ya <= yb <= xb):
return True
return False |
def dirname(path):
"""
Returns path without the last component, like a directory name in a filesystem path.
"""
return path[:-1] |
def find_ch_interest_dict(show_channel_dict : dict, usr_pref_dict : dict):
"""Pass in show_channel_dict {show:channels} and usr_pref_dict {show: rating}. Returns dictionary {channel : total rating}"""
ch_interest_dict = {}
for show in usr_pref_dict:
if show in show_channel_dict:
if show_... |
def nf_type(cwl_type):
"""Convert a CWL variable type into Nextflow.
"""
if "File" in cwl_type:
return "file"
else:
return "var" |
def follow_abspath(json, abspath):
"""json: an arbitrarily nested python object, where each layer
is a list, dict, or tuple.
abspath: a list of keys or array indices to be followed.
**Returns:** the child of json[abspath[0]][abspath[1]]...[abspath[-1]]"""
out = json
for elt in abspath:
... |
def programme_list_heading_should_be_rendered(programmes):
"""
Used by programme_schedule_list.pug alone.
A horribly convoluted way of hiding empty headings in the programme listings
such as the one below the programme schedule table.
The listing is implemented by using the same programme data as ... |
def split_sentence(corpus: list):
"""split corpus
:param corpus: list type sentence
:return: word_list: two-dimensional list
"""
word_list = list()
for i in range(len(corpus)):
word_list.append(corpus[i].split(' '))
return word_list |
def _getMeasurementType1_1(domains):
"""Determine whether measurement results are for web or mail"""
measurementType = 'web'
status = 'failed'
for testDomain in domains:
if (testDomain['status'] == 'ok'):
for category in testDomain['categories']:
if (category['categor... |
def fix_url(url):
"""prefix url without http://."""
if '://' not in url:
url = 'http://' + url
return url |
def remover_repetidos(tpl):
"""
Remove os elementos repetidos de um tuplo
Parametros:
tpl (tuplo): tuplo a remover os elementos repetidos
Retorna:
res (tpl): tuplo sem elementos repetidos
"""
res = ()
for el in tpl:
if el not in res:
res... |
def delete_segment(seq, start, end):
"""Return the sequence with deleted segment from ``start`` to ``end``."""
return seq[:start] + seq[end:] |
def get_currency_to_uah_nbu_exchange_rate(
nbu_exchange_rates: list,
currency_code: str
) -> dict:
"""Fetch exchange rate of UAH to specific foreign currency from NBU
Note:
in case NBU returned several blocks of information about single
currency, method returns only single block of info... |
def parse_scaling(scaling_args):
"""Translate a list of scaling requests to a dict prefix:count."""
scaling_args = scaling_args or []
result = {}
for item in scaling_args:
key, values = item.split('=')
values = values.split(',')
value = int(values[0])
blacklist = frozense... |
def get_crashes_archive_name(cycle: int) -> str:
"""Return as crashes archive name given a cycle."""
return 'crashes-%04d.tar.gz' % cycle |
def get_screenres(fallback=(1920, 1080)):
"""
Return the resolution (width, height) of the screen in pixels.
If it can not be determined, assume 1920x1080.
See http://stackoverflow.com/a/3949983 for info.
"""
try:
import tkinter as tk
except ImportError:
return fallback
... |
def get_speed(message_fields):
""" get_speed
return the speed as float in km/h from a message.as_dict()['fields'] object
Args:
message_fields: a message.as_dict()['fields'] object (with name 'record')
Returns:
the speed as float in km/h, or 0. if not found
"""
for message_field... |
def remove_anchor(url: str) -> str:
"""
Removes anchor from URL
:param url:
:return:
"""
anchor_pos = url.find('#')
return url[:anchor_pos] if anchor_pos > 0 else url |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.