content stringlengths 42 6.51k |
|---|
def get_diff_weights(weights, weights2):
""" Produce a direction from 'weights' to 'weights2'."""
return [w2 - w for (w, w2) in zip(weights, weights2)] |
def missing(field, exist=True, null=True):
"""Only return docs missing a value for ``field``"""
return {
"missing": {
"field": field,
"existence": exist,
"null_value": null
}
} |
def tokenize(s):
"""
Tokenize and preprocess strings
"""
s = s.replace("/", " ")
tokens = s.split()
return tokens |
def set_pagesize(query: str, pagesize: int) -> str:
"""Set the number of questions we want from Stackoverflow."""
return query + f"&pagesize={pagesize}" |
def _moog_par_format_plot (driver,plot):
"""
moogpars['plot']
```
plot 1
```
"""
if plot is None:
return ""
val = str(plot)
if driver == 'synth' and val not in ('1','2'):
val = 0 # synth can have values 0,1,2
elif (driver in ('abfind','blends')) and val in ('... |
def x_from_m_b_y(m, b, y):
"""
get x from y=mx+b
:param m: slope (m)
:param b: b
:param y: y
:return: get x from y=mx+b
"""
return (y - b) / m |
def _is_a_camel(s):
"""Checks if a string is camelcased
ref: http://stackoverflow.com/a/10182901/386082
"""
return (s != s.lower() and s != s.upper()) |
def calc_bits(offset, size):
"""
Generates the string of where the bits of that property in a register live
Parameters
----------
offset : int,
size : int,
Returns
----------
ret_str : str, the string
"""
# Generate the register bits
if size == 1:
ret_str ... |
def mean(r):
"""Return the mean (i.e., average) of a sequence of numbers.
>>> mean([5, 10])
7.5
"""
try:
return float(sum(r)) / len(r)
except ZeroDivisionError:
raise ValueError("can't calculate mean of empty collection") |
def video_no_found(error):
"""no such video exists"""
return {'message': 'video does not exist'}, 404 |
def CountScores(outfile, t1, t2,
graph, separator="|",
cds1={}, cds2={},
options={}):
"""count scores between t1 and t2 in graph.
return lists of scores between t1 and within clusters and
the number of not found vertices and links
"""
between_scores ... |
def color565(red, green=0, blue=0):
"""
Convert red, green and blue values (0-255) into a 16-bit 565 encoding.
"""
try:
red, green, blue = red # see if the first var is a tuple/list
except TypeError:
pass
return (red & 0xf8) << 8 | (green & 0xfc) << 3 | blue >> 3 |
def argval(a, L=[]):
"""
Noted: default value only evaluated once and evaluated at the point
of function definition in the defining scope
"""
L.append(a)
return L |
def mime_to_pltfrm(mime_string):
"""
Translates MIME types to platform names used
by tng-cat. Returns: 5gtango|osm|onap
"""
pattern = ["5gtango", "osm", "onap"]
for p in pattern:
if p in str(mime_string).lower():
return p
return None |
def flatten(d, parent_key=''):
"""
flatten data dict
"""
items = []
for key, val in d.items():
new_key = parent_key + ":" + key if parent_key else key
if isinstance(val, dict):
items.extend(flatten(val, new_key).items())
if isinstance(val, list):
... |
def chromatic(dist=1.0):
"""
Chromatic aberration screen filter. Received from someone from the BlenderArtists forums.
Author: Someone from BlenderArtists.org, Modified by SolarLune
Date Updated: 6/6/11
"""
return ("""
uniform sampler2D bgl_RenderedTexture;
void main()
{
vec... |
def end_of_chunk(prev_tag, tag):
"""Checks if a chunk ended between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
Returns:
chunk_end: boolean.
"""
chunk_end = False
if prev_tag == 'E':
chunk_end = True
if prev_tag ... |
def is_suit(s):
"""Test if parameter is one of Club, Diamond, Heart, Spade"""
return s in "CDHS" |
def EscapeMakeVariableExpansion(s):
"""Make has its own variable expansion syntax using $. We must escape it for
string to be interpreted literally."""
return s.replace('$', '$$') |
def dirname(p):
"""Returns the directory component of a pathname"""
i = p.rfind('/') + 1
head = p[:i]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head |
def _get_time_modifier_comment(
time_seconds: int,
suffix: str,
) -> str:
"""Create the comment that explains how the until_time_code or at_time_code
was calculated.
"""
if suffix == 'w':
comment = 'kSuffixW'
elif suffix == 's':
comment = 'kSuffixS'
else:
comment ... |
def get_converter_name(conv):
"""Get the name of a converter"""
return {
bool: 'boolean',
int: 'integer',
float: 'float'
}.get(conv, 'string') |
def numval(v,min,max,step=1):
"""shortcut for creating linear setting descriptions"""
return {"value":v,"min":min,"max":max, "step":step, "type": "range"} |
def is_valid_ot_str_ens(ext):
""" Checks if output type for structure ensemble is correct """
formats = ['gro', 'g96', 'pdb']
return ext in formats |
def _LowerBound(values, value, pred):
"""Implementation of C++ std::lower_bound() algorithm."""
first, last = 0, len(values)
count = last - first
while count > 0:
i = first
step = count // 2
i += step
if pred(values[i], value):
i += 1
first = i
count -= step + 1
else:
... |
def mult(value, arg):
"""Subtracts the arg from the value"""
return int(value)-int(arg) |
def get_square(x):
"""Return square of a number after sleeping for a random time."""
import random
import time
time.sleep(random.random())
return x**2 |
def get_attr(obj, attr, default=None):
"""Recursive get object's attribute. May use dot notation.
"""
if '.' not in attr:
return getattr(obj, attr, default)
else:
L = attr.split('.')
return get_attr(getattr(obj, L[0], default), '.'.join(L[1:]), default) |
def int_ceil(x, y):
"""
equivalent to math.ceil(x / y)
:param x:
:param y:
:return:
"""
q, r = divmod(x, y)
if r:
q += 1
return q |
def mult(v1, m):
"""multiplies a vector"""
return (v1[0]*m,v1[1]*m) |
def convert_rating(rating):
""" Converts a float rating (e.g 3.5) to the number of star and half star
rating symbols from Font Awesome """
star = '<i class="fas fa-star"></i>'
half_star = '<i class="fas fa-star-half-alt"></i>'
rating_split = [int(rating) for rating in str(rating).split('.')]
pr... |
def accum(s):
"""This function takes in a string and returns a longer string with each letter multiplied by the position it holds."""
first = []
other = []
second = []
third = []
answer = []
answer2 = ''
number = 0
for i in s:
first.append(i.lower())
for h in first:
... |
def find_by(predicate, iterable):
"""Returns the first element of iterable that matches the predicate, or None otherwise."""
return next((item for item in iterable if predicate(item)), None) |
def merge_dict_addition(objOne, objTwo):
"""
Merge two objects and add the respective values to get a total of both
"""
if not objOne:
return objTwo
if not objTwo:
return objOne
newObj = {}
for key in objOne:
try:
if isinstance(objOne[key], (int, list, ... |
def boost(d, k=2):
"""Given a distance between 0 and 1 make it more nonlinear"""
return 1 - (1 - d)**k |
def extract_arg(args, index, default=None):
"""
Return n-th element of array or default if out of range
"""
if index >= len(args):
return default
return args[index] |
def user_token(config, request) -> int:
"""Get `--user-token` argument from `CONFIG_FILE` or CLI.
Args:
config: `config` fixture.
request: Pytest `request` fixture.
Returns:
int: Quotecast API's credential : `user_token`.
"""
if config is not None:
return config["u... |
def _get_mode(steps, mode):
""" Gets the correct mode step list by rotating the list """
mode = mode - 1
res = steps[mode:] + steps[:mode]
return res |
def check_numeric_list_limit(limit, spec, limit_field, description=None, spec_field=None):
"""
Checks a numeric limit given a spec and field name where the value in the spec is a
list of numbers.
Args:
limit: The limit definition to uses as the evaluation criteria
spec: The spec to be ... |
def calc_mean(data):
"""This function calculates the mean of a given numerous list and returns it."""
summ = 0
for i in data:
summ += i
mean = summ/len(data)
return mean |
def truncate(value, length):
"""Truncate the value (a string) to the given length."""
if value is None:
return None
return value[:length] |
def compareTriplets(a, b):
"""Comparing each element of a and b"""
a_score = 0
b_score = 0
for i in range(0, len(a)):
if a[i] > b[i]:
a_score += 1
elif a[i] < b[i]:
b_score += 1
else:
a_score = a_score
b_score = b_score
result =... |
def unwrap_distributed(state_dict):
"""
Unwraps model from DistributedDataParallel.
DDP wraps model in additional "module.", it needs to be removed for single
GPU inference.
:param state_dict: model's state dict
"""
new_state_dict = {}
for key, value in state_dict.items():
new_k... |
def is_even(num: int) -> bool:
"""Is num even?
:param num: number to check.
:type num: int
:returns: True if num is even.
:rtype: bool
:raises: ``TypeError`` if num is not an int.
"""
if not isinstance(num, int):
raise TypeError("{} is not an int".format(num))
return num % 2... |
def valid_filename(value):
""" Validate that the string passed as input can safely
be used as a valid file name
"""
if value in [".", ".."]:
raise Exception("Invalid name: %s" % value)
# this is for Windows, but it does not hurt on other platforms
bad_chars = r'<>:"/\|?*'
for bad_c... |
def splitStringMutationInTwo(mutation):
"""
split a mutation in 'string-format', i.e. '2vuj::AB:N25R/AB:N181D' into '2vuj' & 'AB:N25R/AB:N181D'
"""
separator = None
for i in range( len(mutation) ):
if mutation[i:i+2] == "::":
separator = i
if separator == None:
return None,... |
def levenshtein(s1, s2):
"""Calculate the Levenshtein distance between two strings.
This is straight from Wikipedia.
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_... |
def pick_wm_class_1(tissue_class_files):
"""Returns the gray matter tissue class file from the list of segmented tissue class files
Parameters
----------
tissue_class_files : list (string)
List of tissue class files
Returns
-------
file : string
Path to segment_seg_1.nii.... |
def merge_utterance_lines(utt_dict):
"""
For merging adjacent utterances by the same speaker
"""
new_utterances = {}
merged_with = {}
for uid, utt in utt_dict.items():
merged = False
if utt.reply_to is not None and utt.speaker is not None:
u0 = utt_dict[utt.reply_to]
... |
def all_in(L, dic):
"""Given a list and a dictionary checks that
all values in the list are keys in the dictionary"""
for item in L:
if item not in dic:
return False
return True |
def pts_from_rect_outside(r):
""" returns start_pt, end_pt where end_pt is _outside_ the rectangle """
return (r[0], r[1]), ((r[0] + r[2]), (r[1] + r[3])) |
def climbing_stairs_three_iter(steps: int) -> int:
"""Staircase by bottom-up iteration w/ optimized space.
Time complexity: O(n).
Space complexity: O(1).
"""
if steps <= 1:
return 1
if steps == 2:
return 2
# Track the last three staircase results.
a, b, c = 1, 1, 2
... |
def wordCount(cleantext):
"""
This function counts words from a text and returns a dictionary.
Does not fix for punctuation and special characters, so for example 'why' and 'why?' will be counted as two different words. This doesn't matter in the case of youtube subtitles.
INPUT: string... |
def ensure_cstring(pystring):
"""Return a string we can pass to C"""
if isinstance(pystring, bytes):
return pystring
return pystring.encode('utf-8') |
def add_list(lst1, lst2):
"""Add two lists element-wise"""
return [l1 + l2 for l1, l2 in zip(lst1, lst2)] |
def is_pow2(value: int) -> bool:
""" Check if value is power of two. """
return value > 0 and ((value & (value - 1)) == 0) |
def calc_tba_bool(match_data, alliance, filters):
"""Returns a bool representing if match_data meets all filters defined in filters."""
for key, value in filters.items():
if match_data['score_breakdown'][alliance][key] != value:
return False
return True |
def _get_google_score(location_type: str) -> int:
"""
Convert Google location types to a numeric score
See: https://developers.google.com/maps/documentation/geocoding/intro
"""
data = {
# "ROOFTOP" indicates that the returned result is a precise geocode for
# which we have location ... |
def byte_list_to_nbit_le_list(data, bitwidth, pad=0x00):
"""! @brief Convert a list of bytes to a list of n-bit integers (little endian)
If the length of the data list is not a multiple of `bitwidth` // 8, then the pad value is used
for the additional required bytes.
@param data List of bytes.... |
def escape_binary(message):
"""
Escape the binary message using the process described in the GDB server
protocol documentation.
Most bytes are sent through as-is, but $, #, and { are escaped by writing
a { followed by the original byte mod 0x20.
"""
out = ""
for c in message:
d ... |
def unknown_processor_rules(info_data, rules):
"""Setup the default keyboard info for unknown boards.
"""
info_data['bootloader'] = 'unknown'
info_data['platform'] = 'unknown'
info_data['processor'] = 'unknown'
info_data['processor_type'] = 'unknown'
info_data['protocol'] = 'unknown'
re... |
def mergedicts(a, b, path=None):
"""merges b into a"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
mergedicts(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
... |
def UA_wll_ins_amb_plate(A, s_wll, s_ins, lam_wll, lam_ins, alpha_inf):
"""
Calculates the U*A-value for the heat flow to or from a plate with or
without insulation to or from the ambient.
Layers which are considered: wall material, insulation, ambient.
The reference area must always be the cross se... |
def add_lines(name, content, is_file, boundary, lines):
"""Add content to lines with proper format needed for multipart
content type.
:param name: name of the request parameter
:param content: contents of the request parameter
:param is_file: is the parameter a file type (for adding filename)
:... |
def splitHostPort(hostport, rawPort=False):
"""Split hostnames like [dead::beef]:8080"""
i = hostport.rfind(':')
j = hostport.rfind(']')
if i > j:
host, port = hostport[:i], hostport[i+1:]
if not rawPort:
port = int(port)
else:
host = hostport
port = None
... |
def shorten_fqdn(name):
""" Shorten any system account FQDN for readability. """
if '.' in name:
(name, _) = name.split('.', 1)
return name |
def get_path_from_class(cls: type) -> str:
"""Get full path of class, getting rid of internal module names."""
module = cls.__module__
module_elems = (
[]
if module is None
else ([elem for elem in module.split(".") if not elem.startswith("_")])
) # drop internal module names
... |
def _set_group(tree, group):
"""Set the group for a tree of dependencies."""
grouped = {
"dependency": tree["dependency"],
"level": tree["level"],
"version": tree["version"],
"group": group,
"children": [],
}
if tree["children"]:
for child in tree["childr... |
def transpose(mat):
""" transposes a m x n input list and returns the result """
mat_t = []
for j in range(len(mat[0])):
mat_t.append([mat[i][j] for i in range(len(mat))])
return mat_t |
def add(intf, ints):
"""
overpython.add(intf, ints)
Add intf with ints. Raises ValueError if intf/ints is a string.
"""
try:
return float(intf) + float(ints)
except ValueError:
raise ValueError("%s/%s is not a number" % (intf, ints)) |
def factorial(f, n):
""" f = n! , if n = 0 or 1 f = 1 """
return factorial(f * n, n - 1) if n > 1 else f |
def cm2inch(*tupl):
"""Converts inches into mm for figures.
"""
inch = 2.54
if isinstance(tupl[0], tuple):
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl) |
def get_commit_timestamps(commits):
"""Get all commit timestamps for the given ebuild.
Args:
commits (list[Commit]): The commits in question.
Returns:
list[int]: The uprev commit unix timestamps, in order.
"""
return [int(commit.timestamp) for commit in commits] |
def angry_professor(k, a):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/angry-professor/problem
A Discrete Mathematics professor has a class of students. Frustrated with their lack of discipline, he decides to
cancel class if fewer than some number of students are present when class starts.... |
def calculate_image_size(size, target_size):
"""
Returns the size of the image after resizing.
The same code is used in PIL.Image.thumbnail
The results of this function is used by JavaScript
in resize effect while changing image.
"""
x, y = size
# if the width is greater than the target
... |
def transform_scale(score, xref_min, xref_max):
"""transforms score from [0,1] scale to [-1,1]"""
x_new = 2*(score-xref_min)/(xref_max-xref_min) - 1
# x_new = score-0.5
return(x_new) |
def flatten_dictionaries(input):
""" Flatten a list of dictionaries into a single dictionary, to allow flexible YAML use
Dictionary comprehensions can do this, but would like to allow for pre-Python 2.7 use
If input isn't a list, just return it.... """
output = dict()
if isinstance(input, list):... |
def replace_badchars(inputstring):
"""Stringing together '.replace' seems the fastest way
to do this: https://stackoverflow.com/a/27086669"""
blacklist = {':': '', '\\': '', '"': '', '\'': '', '|': '',
' ': '', '/': ''}
for k in blacklist:
inputstring = inputstring.replace(k, bl... |
def create_loss_dict(foreground_weight = 10, n_sigma = 2, w_inst = 1, w_var = 10, w_seed = 1):
"""
Creates `loss_dict` dictionary from parameters.
Parameters
----------
foreground_weight: int
w_inst: int/float
weight on IOU loss
w_var: int/float
... |
def is_in(elt, seq):
"""Similar to (elt in seq), but compares with 'is', not '=='."""
return any(x is elt for x in seq) |
def as_bytes(s):
"""
Convert an unicode string to bytes.
:param s: Unicode / bytes string
:return: bytes string
"""
try:
s = s.encode()
except (AttributeError, UnicodeDecodeError):
pass
return s |
def sanitize(text):
"""Sanitize text.
This attempts to remove formatting that could be mistaken for markdown.
Args:
text (str): text to sanitise.
Returns:
str: sanitised text.
"""
if '```' in text:
text = text.replace('```', '(3xbacktick)')
if '|' in text:
... |
def calc_nominal_interest(val):
"""Simple calc of the nominal interest by 1 year.
val -- the percentual interest
"""
return val / (12 * 100) |
def fibonacci_n(n):
"""
Returns the n-th number in the Fibonacci sequence given by:
f(1) = 1, f(2) = 1, f(n) = f(n - 1) + f(n - 2) for n > 2
The first 10 terms are
1, 1, 2, 3, 5, 8, 13, 21, 34, 55
"""
if n in [1, 2]:
return 1
a = b = 1
k = 2
whi... |
def try_to_convert(value):
"""Tries to convert [value] to an int, returns the original string on fail"""
try:
return int(value)
except:
return value |
def _format_select(formatter, name):
"""Modify the query selector by applying any formatters to it.
Args:
formatter: hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applied to... |
def exp_by_squaring(x, n):
"""Assumes n>=0
See: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
"""
if n == 0:
return 1
if n % 2 == 0:
return exp_by_squaring(x * x, n // 2)
else:
return x * exp_by_squaring(x * x, (n - 1) / 2) |
def is_query_to_be_removed(my_dict, remove_param):
"""
"unit" : {
"in": "query",
"description": "Units",
"type": "string",
"enum": ["C", "F", "K"],
"name": "units",
"x-queryexample" : "/TemperatureResURI?units=C"
}
"""
... |
def binlst_to_int(values) -> int:
"""Returns int values of binary in list form"""
values = values[::-1]
total = 0
for i in range(len(values)):
total += values[i]*2**i
return total |
def all_codes_present(specified_codes, test_codes):
"""The test codes must be a subset of the specified codes.
If no codes are specified, we do everything.
"""
if specified_codes:
print("comparing restriction: {} and test: {}".format(str(specified_codes), str(test_codes)))
s = set(spec... |
def htmlspecialchars(text):
"""Replace html chars"""
return (text.replace("&", "&").replace('"', """).replace(
"<", "<").replace(">", ">")) |
def _match_topic(subscription, topic):
""" Returns if topic matches subscription. """
if subscription.endswith('#'):
return (subscription[:-2] == topic or
topic.startswith(subscription[:-1]))
sub_parts = subscription.split('/')
topic_parts = topic.split('/')
return (len(sub... |
def xf_screenname(name):
"""Insure user screen name is prefixed with '@'."""
return '@' + name if name[0] != '@' else name |
def to_seq (value):
""" If value is a sequence, returns it.
If it is a string, returns a sequence with value as its sole element.
"""
if not value:
return []
if isinstance (value, str):
return [value]
else:
return value |
def _calc_crop(s1, s2):
"""Calc the cropping from the padding"""
a1 = abs(s1) if s1 < 0 else None
a2 = s2 if s2 < 0 else None
return slice(a1, a2, None) |
def _get_command_powershell_script(command):
"""Return a valid CMD command that runs a powershell script."""
return "powershell -NonInteractive -NoLogo -File {}".format(command) |
def get_unique_values(lst):
"""
Converts a provided list of elements to a sorted list of unique elements.
Args:
lst: List of elements.
Returns:
Sorted list of unique elements.
"""
return sorted(list(set(lst))) |
def RemoveRedundantEntries(l):
"""remove redundant entries (and 0s) from list.
One liner?
"""
if len(l) == 0:
return l
l.sort()
last = l[0]
n = [last]
for x in l[1:]:
if x != last and x > 0:
n.append(x)
last = x
return n |
def BinarySearch(lst, val):
"""
Given a list and a value, return the position of the value in the list.
Return -1 if the value is not in the list.
"""
if isinstance(lst, list) is False:
print('TypeError')
return('TypeError')
min = 0
# Minus-one because max will be used ... |
def process_action(original_action):
"""add dummy flight and dummy name in the cases that they are not present."""
if 'flight' not in original_action:
original_action['flight'] = 'dummy_flight'
if 'name' not in original_action:
original_action['name'] = 'dummy_name'
return original_action['name'], origi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.