content stringlengths 42 6.51k |
|---|
def filt_last(list_, func):
"""Like above but finds last"""
matching = [i for i in list_ if func(i)]
if len(matching) > 0:
return matching[-1]
return None |
def loadingComplete(line):
"""Helper function for joinRoom, checks whether the joining has ended"""
return "End of /NAMES list" not in line |
def _env_pairs_to_dict(ctx, param, value):
"""Converts a space-seperated list of key=value pairs into a Python
dictionary.
"""
d = {}
for pair in [x.split('=', 1) for x in value]:
if len(pair) == 1:
d[pair[0]] = ''
else:
d[pair[0]] = pair[1]
return d |
def get_kwargs_dic(kwargs_str):
"""
Convert a kwarg string to a dictionary of key-values pairs.
:param kwargs_str: key vale arguments in str format. e.g. 'learning_rate=1e-2; feat_name=vgg16:add; ...'
:return: Dictionary of key-value pairs. The keys and values are str and should be processed by its owne... |
def create_numeric_attribute_filter(attribute_name: str, value_min: float, value_max: float) -> dict:
"""
Create a numeric attribute filter to be used in a trace filter sequence.
Args:
attribute_name:
A string denoting the name of the attribute.
value_min:
An integer... |
def cstr(byte):
"""Convert C string bytes to python string.
Written by Luke Campognola
"""
try:
ind = byte.index(b"\0")
except ValueError:
return byte
return byte[:ind].decode("utf-8", errors="ignore") |
def tokenize(text):
"""Convert a string to a list of lemmas."""
out = [""]
for char in text.lower():
if char.isalpha() or char == "'":
out[-1] += char
elif out[-1] != "":
out.append("")
return [string for string in out if string] |
def filter_top_scoring_values(top_node_to_vals, node_to_vals):
"""
From the dict that contains all the nodes in common in both drugs scored, we get the top ones and their values.
"""
filtered_node_to_vals = {}
for item in top_node_to_vals:
if item in node_to_vals:
filtered_node_... |
def userdisplay(userid):
"""This should take a user id and return the corresponding
value to display depending on the users privacy setting"""
usertext = userid
return usertext |
def bytes_to_string(the_input):
""" Take in a list of bytes, and return the string they correspond to. Unlike the prior question, here you should return a raw bitstring and not the hex values of the bytes! As a result, the output need not always be printable. (This should effectively "undo" the question 1.)
Ex... |
def is_us_county(wqp_lookup_code):
"""
Returns True if the WQP county lookup code is for the US.
:param dict wqp_lookup_code:
:rtype: bool
"""
return wqp_lookup_code.get('value', '').split(':')[0] == 'US' |
def renumera_atomos(res,total_provisional):
""" Renumera los atomos de un residuo a partir de total_provisional y
devuelve una cadena de caracteres con el residuo renumerado y la cuenta
total actualizada."""
res_renum,updated_total = '',total_provisional
for atomo in res.split("\n"):
if(atomo == ''): continu... |
def get_update_files(manifest_srv, manifest_client):
""" Get list of the files to update
:param dict manifest_client: a nested dictionary (dict[file] = {'size': , 'mtime': }) in the client-side
:param dict manifest_srv: a nested dictionary (dict[file] = {'size': , 'mtime': }) in the server side
:return... |
def finalize(style):
"""
Update the given matplotlib style according to cartopy's style rules.
Rules:
1. A facecolor of 'never' is replaced with 'none'.
"""
# Expand 'never' to 'none' if we have it.
facecolor = style.get('facecolor', None)
if facecolor == 'never':
style['f... |
def good_fibonacci(n):
"""Return pair of Fibonacci numbers, F(n) and F(n-1)"""
if n <= 1:
return (n, 0)
else:
a, b = good_fibonacci(n-1)
return a +b, a |
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this
class.
:param key:
:param values:
:return:
"""
# need to know a number of gaussians in order to give a sensible guess.
return None |
def fill(s, length=45):
""" """
while len(s) < length:
s += ' '
return s |
def tauPoint(numDeps, tauRos, tau):
"""Return the array index of the optical depth arry (tauRos) closest to a
desired value of optical depth (tau) Assumes the use wants to find a *lienar*
tau value , NOT logarithmic"""
#int index;
help = [0.0 for i in range(numDeps)]
for i in rang... |
def checkpoint_from_distributed(state_dict):
"""
Checks whether checkpoint was generated by DistributedDataParallel. DDP
wraps model in additional "module.", it needs to be unwrapped for single
GPU inference.
:param state_dict: model's state dict
"""
ret = False
for key, _ in state_dict... |
def normalise(word):
"""Normalises words to lowercase and stems and lemmatizes it."""
word = word.lower()
#word = stemmer.stem_word(word)
#word = lemmatizer.lemmatize(word)
return word |
def cropEyeLine(pixels, x, y):
"""
Taglia linea degli occhi
:param pixels:
:param x:
:param y:
:return: cropped image
"""
crop = pixels[0:y][0:x]
# cv2_imshow(crop)
return crop |
def parse_list(ctx, param, value):
"""Parse click CLI list "item1,item2,item3..."."""
if value is not None:
return value.split(',') |
def find_repeated(values):
"""Find repeated elements in the inputed list
Parameters
----------
values : list
List of elements to find duplicates in
Returns
-------
set
Repeated elements in ``values``
"""
seen, repeated = set(), set()
for value in values:
... |
def list_intersection(list1, list2): # or list(set(a) & set(b))
"""Values both in list1 and list2"""
list3 = [value for value in list1 if value in list2]
return list3 |
def fwd_Euler_step(f, told, uold, h):
"""
Usage: unew = fwd_Euler_step(f, told, uold, h)
Forward Euler solver for one step of the ODE problem,
u' = f(t,u), t in tspan,
u(t0) = u0.
Inputs: f = function for ODE right-hand side, f(t,u)
told = current time
uold = c... |
def expand_whole_protocol_and_port(protocol=None, port=None):
"""
Calculate a full protocol and port value from the possibly None protocol
and port values given. This method helps to default port numbers to
connection protocols understood by CodeChecker.
"""
if protocol:
if protocol == ... |
def calc_snap_size(snaps_list, base10=False):
"""Take a list of snapshots and returns the total size of all the snapshots in the list"""
snap_size = 0
for snap in snaps_list:
snap_size = snap_size + int(snap['size'])
return snap_size |
def pascal_triangle(n):
"""Return the nth line in Pascal's triangle."""
if n == 1:
line = [1]
else:
line = [1]
prev = pascal_triangle(n - 1)
line.extend(prev[i] + prev[i + 1] for i in range(len(prev) - 1))
line.append(1)
return line |
def is_corrupt(val: str) -> str:
""" Return unexpected character if corrupt, else empty string """
expected = {')': '(', '}': '{', ']': '[', '>': '<'}
opened = []
for char in list(val):
if char in '({[<':
opened.append(char)
elif char in ')}]>':
if opened and ope... |
def removePrefix(s, prefix='!'):
"""
If the string starts from the prefix, the prefix is removed.
"""
if s.startswith(prefix):
return s[len(prefix):]
else:
return s |
def getGeoLatWidth(prec):
"""
L, dX, dY, dX*dY = 2 11.25 5.625 63.28125
L, dX, dY, dX*dY = 3 1.40625 1.40625 1.9775390625
L, dX, dY, dX*dY = 4 0.3515625 0.17578125 0.061798095703125
L, dX, dY, dX*dY = 5 0.0439453125 0.0439453125 0.0019311904907226562
L, dX, dY, dX*dY = 6 0.010986328125 0.0054931640625 6.03497028... |
def set_last_bit(value, target):
"""Sets target as LSB in given value.
Args:
value: value to encode as LSB.
target: 0 or 1 - bit value to encode.
Returns:
int: encoded value
"""
if target:
out = value | target
else:
out = value >> 1 << 1
return out |
def read_config(config):
"""
Reads config object, providing sensible defaults for properties
that aren't defined.
"""
return {
"input_path": config.get("input_path", "content"),
"output_path": config.get("output_path", "public"),
"theme_path": config.get("theme_path", "theme"... |
def encode(code, readline=False):
""" Adds escape and control characters for ANSI codes
:param code: pick a constant, any constant
:type code: int
:param readline: add readline compatibility, which causes bugs in other formats
:type content: unicode
:return: ansi string
:rtype: unicode
... |
def is_equality(s: str) -> bool:
"""Checks if the given string is the equality relation.
Parameters:
s: string to check.
Returns:
``True`` if the given string is the equality relation, ``False``
otherwise.
"""
return s == '=' |
def get_id_from_payload(payload):
"""
Get the alert id from an update request in Slack
"""
values = payload['view']['state']['values']
for value in values:
for key in values[value]:
if key == 'alert_id':
alert_id = values[value][key]['value']
retur... |
def _search(left, right, predicate):
"""Simple binary search that uses the ``predicate`` function to determine direction of search"""
if right >= left:
mid = left + (right - left) // 2
res = predicate(mid)
if res == 0:
return mid
elif res > 1:
return _s... |
def field_eq(p, e):
"""
Checks the field values of a parsed message for equality against
some ground truth value.
Parameters
----------
p : object with dict-like attributed access
Parsed field contents.
e : object with dict-like attributed access
Expected field contents.
Returns
----------
... |
def range_map(val, in_min, in_max, out_min, out_max, rnd=0):
"""
Takes a value from one range of possible values and maps
it to a value in the second range of possible values
Example 1: range_map(555, 0, 1023, 0, 100)
This will output a value of 54.252199413489734
... |
def receptive_field_conv(kernel, stride, n0=1, n_lyrs=1):
"""
Compute receptive field for convolution layers
Parameters
----------
kernel
kernel size
stride
stride size
n0
receptive field from previous layer
n_lyrs
number of layers
Returns
------... |
def trim_unwanted_words(s):
"""
Remove 'abstract' keyword from text
"""
try:
if s.startswith("Abstract"):
return s[8:]
except:
return s |
def uint82bin(n, count=8):
"""returns the binary of integer n, count refers to amount of bits"""
return ''.join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) |
def isclass(object):
"""Return true if the object is a class."""
return hasattr(object, '__metaclass__') and not hasattr(object, '__class__') |
def list_differences(list_one, list_two):
"""
Compares two lists and returns a list of differences
Parameters
----------
list_one: list
list_two: list
Returns
-------
A list of differences between the two given lists.
"""
difference_list = list(set([entry for entry in list... |
def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v=list(d.values()) #no identation error..do not change
k=list(d.keys())
return k[v.index(max(v))] |
def _get_obj_attrs_map(obj, attrs):
"""
Get the values for object ``attrs`` and return as a dict. This
ignores any attributes that are None and in Py2 converts any unicode
attribute names or values to str. In the context of serializing the
supported core astropy classes this conversion will succee... |
def _adjointwavelet(wavelet):
"""Define adjoint wavelet
"""
waveletadj = wavelet
if 'rbio' in wavelet:
waveletadj = 'bior' + wavelet[-3:]
elif 'bior' in wavelet:
waveletadj = 'rbio' + wavelet[-3:]
return waveletadj |
def greet(name, owner) -> str:
"""
Function that gives a personalized greeting.
This function takes two parameters: name and owner.
:param name:
:param owner:
:return:
"""
if name.lower() == owner.lower():
return 'Hello boss'
return 'Hello guest' |
def _compute_moving_average_closed_form(i, alpha):
"""Compute the moving average for consecutive positive integers with momentum alpha."""
return (alpha ** (i + 1) - (i + 1) * alpha + i) / (1 - alpha) |
def ptcrb_cleaner_multios(item):
"""
Discard multiple entries for "OS".
:param item: The item to clean.
:type item: str
"""
if item.count("OS") > 1:
templist = item.split("OS")
templist[0] = "OS"
item = "".join([templist[0], templist[1]])
return item |
def find_relative_radius(level_diff):
"""
Find the relative radius of a node with respect to the root node, which is
assumed to have side-length 1.
"""
return 0.5 * (1 << level_diff) |
def concat(value, arg):
"""Add the arg to the value."""
try:
arg = str(arg) if arg else ''
return str(value) + arg
except Exception:
return str(value) |
def kgV(int1, int2):
"""gibt das kleinste gemeinsame Vielfache von 2 Zahlen aus"""
a = max(int1, int2)
b = min(int1, int2)
i = 1
while True:
prod = a*i
if prod%b == 0:
return prod
break
i = i+1 |
def clean_hotel_smart_deal(string):
"""
"""
if string is not None:
r = 1
else:
r = 0
return r |
def brook(x):
"""Brook 2014 CLUES derived differential subhalo mass function
Keyword arguments:
x -- array of subhalo halo masses
"""
tr = -0.89*((x/1.e10)/38.1)**-0.89
return tr |
def min_max_keys(d):
"""Return tuple (min-keys, max-keys) in d.
>>> min_max_keys({2: 'a', 7: 'b', 1: 'c', 10: 'd', 4: 'e'})
(1, 10)
Works with any kind of key that can be compared, like strings:
>>> min_max_keys({"apple": "red", "cherry": "red", "berry": "blue"})
('apple', 'ch... |
def reduce_size(clauses):
""" reduce the size of clauses
If one variable only appears as either positive or negative, this clause can be removed as we can easily
satisfy this clause by setting this variable always true or false.
Iteratively remove these clauses to reduce the problem size
... |
def abs_sqd(x):
"""Element-wise absolute value squared."""
return x.real**2 + x.imag**2 |
def a(k_m, P_m, C_Pm):
"""Thermal diffusivity
Keyword arguments:
k_m -- Thermal conductivity of the melt
P_m -- Melt density
C_Pm -- Specific heat of the melt
"""
a = k_m / (P_m * C_Pm)
return a |
def is_valid_hex_str(hex_str):
"""
Function to check given string is valid hex string or not
Parameter
- hex_str is string
Returns True if valid hex string otherwise False
"""
try:
int(hex_str, 16)
return True
except (ValueError, TypeError):
# Throws TypeError... |
def id_from_name(name):
"""Extract the id from the resource name.
Args:
name (str): The name of the resource, formatted as
"${RESOURCE_TYPE}/${RESOURCE_ID}".
Returns:
str: The resource id.
"""
if not name or not '/' in name:
return name
return name[name.inde... |
def _stix_type_of(obj_or_type):
"""
Get a STIX type from the given value: if a string is passed, it is assumed
to be a STIX type and is returned; otherwise it is assumed to be a mapping
with a "type" property, and the value of that property is returned.
:param obj_or_type: A mapping with a "type" p... |
def is_type(var,types=[int,float,list]):
"""
Check type
"""
for x in range(len(types)):
if isinstance(var,types[x]):
return True
return False |
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 whitespace_smart_split(command):
"""
Split a command by whitespace, taking care to not split on
whitespace within quotes.
>>> whitespace_smart_split("test this \\\"in here\\\" again")
['test', 'this', '"in here"', 'again']
"""
return_array = []
s = ""
in_double_quotes = False
... |
def fitdict(target_keys, input):
"""
Assigns values of the required words in target_keys to
a new list, indexed indentically with sortedKeys()
Meant to be used to assign an object values to the merged
frequency set
"""
list = [0] * len(target_keys)
count = 0
for x in target_keys:
... |
def valid_substitution(strlen, index):
"""
skip performing substitutions that are outside the bounds of the string
"""
values = index[0]
return all([strlen > i for i in values]) |
def model_format_args(model, pars):
"""Format the model and parameter args to save in output file.
Change to int, str and float.
model in [temp, logg, fe/h, alpha]
pars in order (R, band, vsini, sample).
Can now also optionally handle a 5th parameter RV.
"""
temp = int(model[0])
logg ... |
def tex_coord(x, y, n=4): # N is number of textures - 1
""" Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m |
def complement (matrix):
"""Applique un complement a 100 sur la matrice"""
for y, y_elt in enumerate(matrix):
for x, x_elt in enumerate(y_elt):
matrix[y][x] = 100 - x_elt
return matrix |
def Z_S(n, f, k):
"""
The cycle index of the symmetric group has recurrence
Z(S_n, f(x)) = 1/n \sum_{i=1}^n f(x^i) Z(S_{n-i}, f(x)).
This function finds the coefficient of x^k in Z(S_n, f(x))
"""
# Special case to avoid division by zero
if n == 0:
return 1 if k == 0 else 0
# ... |
def get_headers(oauth_token: str) -> dict:
"""Common headers for all requests"""
return {
'Authorization': f'OAuth {oauth_token}'
} |
def normalize_data(data):
"""
The template reads a json from PubSub that can be a single object
or a List of objects. This function is used by a FlatMap transformation
to normalize the input in to individual objects.
See:
- https://beam.apache.org/documentation/transforms/python/elementwise/fla... |
def pg_connection_string(pg_base_connection_string: str, pg_db_name: str):
"""
A full Postgres connection string with the auto-generated test database name appended.
eg. postgresql+asyncpg://virtool:virtool@localhost/test_2
"""
return f"{pg_base_connection_string}/{pg_db_name}" |
def getIDsFromListofDicts(LoD):
"""
:param LoD: list of dictionaries [{'id': 14, 'name': 'Fantasy'}, {'id': 28, 'name': 'Action'}, {'id': 12, 'name': 'Adventure'}]
:return: ids from this list
"""
res = [el['id'] for el in LoD]
return res |
def time_correct(mjd, zed):
"""Corrects for time dilation.
Keyword arguments:
mjd -- Python list, contains measurements epochs in MJDs.
zed -- float, redshift to use for correction.
"""
return [el/(1.+zed) for el in mjd] |
def v6_int_to_packed(address):
"""Represent an address as 16 packed bytes in network (big-endian) order.
Args:
address: An integer representation of an IPv6 IP address.
Returns:
The 16-byte packed integer address in network (big-endian) order.
Raises:
ValueError: If address is... |
def freebsd_translator(value):
"""Translates a "freebsd" target to freebsd selections."""
return {"@com_github_renatoutsch_rules_system//system:freebsd": value} |
def _defined(message):
"""Returns whether the message is defined (not empty)."""
# NOTE(skearnes): Add the first bool check to avoid mysterious segfaults.
return bool(str(message)) and message != type(message)() |
def get_yearweek(yearweekstr: str) -> tuple:
"""Transform string of form '2020-W10' into tuple (2020, 10)
"""
return tuple(map(int, yearweekstr.split('-W'))) |
def get_zip_file_link(package_name, version, file_extension="tar.zst", arch="x86_64"):
"""
https://mirror.msys2.org/msys/x86_64/libutil-linux-2.35.2-1-x86_64.pkg.tar.zst
"""
base = "https://mirror.msys2.org/msys/x86_64"
return f"{base}/{package_name}-{version}-{arch}.pkg.{file_extension}" |
def param2type(request, method, param, data_type, defval=None):
""" get http request paramter
Args:
request: HttpRequest instance
method: string of HTTP method
param: string of parameter
data_type: type of parameter
defval: default value if parameter do not exist in requ... |
def ensure_scripts(linux_scripts):
"""Creates the proper script names required for each platform
(taken from 4Suite)
"""
from distutils import util
if util.get_platform()[:3] == "win":
return linux_scripts + [script + ".bat" for script in linux_scripts]
return linux_scripts |
def compare_identifiers(datapoints, identifiers):
"""Check that dataset labels are the same as experiment labels."""
for key, value in datapoints.items():
if identifiers[str(key)] != list(value):
return False
return True |
def convert_to_dictionary(days_and_tasks_list, daynames: list):
""" Populates days_and_tasks_dict with tasks from days_and_tasks_list.
Ignores any text before first day heading.
"""
days_and_tasks_dict = dict.fromkeys(daynames, "")
current_day = ""
for i in days_and_tasks_list:
if i ... |
def _replace(string_value, token, replace_token_string):
"""
Replace the token in the string value with the replace token string. This replace method
replaces the python replace because if the string only contains the token, python throws an exception
:param token: in the string to replace
:param st... |
def _bit_is_set(bit_str: str, i: int) -> bool:
"""
Private helper function to check whether the i-th bit in the given bit
string is set.
:param bit_str: str
:param i: int
:return: bool
"""
return bit_str[i] == '1'
# Running time complexity: O(1) |
def check_power_of_2(val):
"""power of 2 no.s have only a bit set
so, if we subtract 1 from given 2's power val and take & with val
results to zero , so we can say it is power of two
"""
if not val:
# for val == 0
return False
if not val & (val - 1):
return True
... |
def get_counter(given_name):
"""
Assuming the given name adheres to the naming convention of crab this
will extract the counter element of the name.
:param given_name: Name to extract from
:type given_name: str or pm.nt.DependNode
:return: int
"""
parts = given_name.split('_')
for... |
def append_fp_postfix(type_str, input_val_list):
"""Generates and returns a new list from the input, with .0f or .0 appended
to each value in the list if type_str is 'float', 'double' or 'sycl::half'"""
result_val_list = []
for val in input_val_list:
if (type_str == 'float'
or ty... |
def parse_evidence(evidence):
"""
From an evidence string/element return a dictionary or obs/counts
Updated where to handle 0 coverage in an 'N' call! In this case we set
N = -1
:param evidence: an evidence string. It looks something like this -
Ax27 AGCAx1 AGCAATTAATTAAAAT... |
def merge_two_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
https://stackoverflow.com/a/26853961/4480674
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return r... |
def getparam(obj, name, default=None):
"""
Descend the object hierarchy to find a matching
parameter and return the value. The descent stops
when an object has no parent attribute.
"""
while obj:
if hasattr(obj, 'params') and name in obj.params:
return obj.params... |
def verifytest(calced, expected, descr):
"""
verifytest is used to verify test results
"""
if type(calced) != type(expected):
if type(expected) == str:
calced = "%s" % calced
if calced != expected:
print("ERROR in %s: got %s, expected %s" % (descr, calced, expected))
... |
def write_png(buf, width, height):
# by ideasman42, 2013-10-04, stackoverflow.com
""" buf: must be bytes or a bytearray in py3, a regular string in py2. formatted RGBARGBA... """
import zlib, struct
# reverse the vertical line order and add null bytes at the start
width_byte_4 = width * 4
raw_d... |
def aspcap_windows_url_correction(targetname):
"""
NAME:
target_name_conversion
PURPOSE:
to convert targetname to string used to get ASPCAP windows url
INPUT:
targetname (string)
OUTPUT:
converted name (string)
HISTORY:
2017-Nov-25 - Written - Henry Leung ... |
def valid_gain(gain):
"""
Use this parse an argument as if it were a float and get back a valid gain as a float.
Raises ValueError if passed an un-parse-able value.
"""
try:
my_gain = round(float(gain), 1)
except TypeError:
raise ValueError("Could not parse value as into a valid ... |
def get_contact_info_keys(status_update):
"""Returns the contact info method keys (email, sms)
used to send a notification for a status update if the notification
exists. Returns [] if there is no notification
"""
if hasattr(status_update, 'notification'):
return list(status_update.notificat... |
def _bold(msg):
"""
_bold(msg)
arguments:
msg -- the message to be in bold
returns the message in bold
"""
return u'\033[1m%s\033[0m' % msg |
def mod_exp(base, exponent, modulus):
"""
Computes s = (base ^ exponent) mod modulus
(Bruce Schneier: "Applied Cryptography" pp. 244)
"""
s = 1
while exponent != 0:
if exponent & 1:
s = (s * base) % modulus
exponent >>= 1
base = (base * base) % modulus
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.