content stringlengths 42 6.51k |
|---|
def sort_by_latest_letter(list_of_strings):
"""
>>> sort_by_latest_letter(["abc", "cab", "bca"])
['bca', 'cab', 'abc']
"""
return [sorted_element[::-1] for sorted_element in sorted([element[::-1] for element in list_of_strings])] |
def normalize(title):
"""
Normalizes a page title to the database format. E.g. spaces are converted
to underscores and the first character in the title is converted to
upper-case.
:Parameters:
title : str
A page title
:Returns:
The normalized title.
:Example:
... |
def emptyIndex(index):
"""
Determine whether an index is empty.
@param index: An index.
@type index: L{dict}
@return: true if C{index} is empty, otherwise false.
"""
if not index:
return True
for _ignore_fieldName, fieldIndex in index.iteritems():
for _ignore_fieldValu... |
def _format_local(local_path, local_is_path):
"""Format a path for log output"""
if local_is_path:
return local_path
else:
# This allows users to set a name attr on their StringIO objects
# just like an open file object would have
return getattr(local_path, 'name', '<file obj... |
def tensor2scalar(x):
"""Convert torch.Tensor to a scalar value.
Args:
x (torch.Tensor):
Returns:
scaler
"""
if isinstance(x, float):
return x
return x.cpu().detach().item() |
def float_to_32(value):
""" convert float value into fixed exponent (16) number
returns (int_part,frac_part)
int_part is integer part (16 bit) of value
frac_part is fraction part (16 bit) of value """
value = int(round(value*0x10000,0))
return ((value & 0xffff0000) >> 16, val... |
def _allows_downcast_fallback(super_class):
"""Get the whether downcast can fallback to a dict or not"""
return getattr(super_class, "__deserialize_downcast_allow_fallback__", False) |
def urn_to_url(urn):
""" Turns a urn into a path for a url """
if urn is None:
return None
return urn.replace(":", "/") |
def compress(word):
"""
This function takes a string as an argument and returns a new string
such that each character is followed by its count, and any adjacent
duplicate characters are removed.
"""
result = ""
if len(word) == 0:
return result
else:
count = 1
for ... |
def rel_err_rel_var(O1, O2, x1, x2):
""" Estimate of relative error `abs(x2/(x2-x1)*(O1-O2)/O2)` """
return abs(x2/(x2-x1)*(O1-O2)/O2) |
def binning(experiments, wells=4, prefix='test'):
"""Split set of input experiments into groups.
Parameters
----------
experiments : list of str
List of experiment names.
wells : int
Number of groups to divide experiments into.
Returns
-------
slices : int
Numbe... |
def rc4(buffer, key):
"""
Encrypt / decrypt the content of `buffer` using RC4 algorithm.
Parameters
----------
buffer : bytes
The bytes sequence to encrypt or decrypt.
key : bytes
The key to be used to perform the cryptographic operation.
Returns
-------
A by... |
def split_string(instance_string):
"""
Split a string like app_label.model_name-instance_pk to app_label.model_name, instance_pk
We need to handle multiple `-` inside the instance_pk, this is why this function looks ugly.
"""
content_splitpoint = instance_string.index('-')
if not content_splitpo... |
def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1 |
def get_split(partition_rank, training=0.7, dev=0.2, test=0.1):
"""
This function partitions the data into training, dev, and test sets
The partitioning algorithm is as follows:
1. anything less than 0.7 goes into training and receives an appropiate label
2. If not less than 0.7 subtract 0.7... |
def print_train_time(start, end, device=None):
"""Prints difference between start and end time.
Args:
start (float): Start time of computation (preferred in timeit format).
end (float): End time of computation.
Returns:
float: time between start and end in seconds (higher is longe... |
def n_jobs_cap(n_jobs):
"""
Cap the number of jobs for sklearn tasks on Windows.
https://github.com/scikit-learn/scikit-learn/issues/13354
Args:
n_jobs: int
Returns:
n_jobs
"""
if n_jobs is None or n_jobs < 0 or n_jobs > 60:
# Bug in windows if more than 60 jobs
# https://github.com/scikit-learn/sciki... |
def strip_begin_end_public_key(key):
"""
Strips off newline chars, BEGIN PUBLIC KEY and END PUBLIC KEY.
"""
return key.replace("\n", "")\
.replace("-----BEGIN PUBLIC KEY-----", "").replace(
"-----END PUBLIC KEY-----", "") |
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
i = 0
res = []
while i < len(lines):
P, G = map(int, lines[i].split())
grudges = [tuple(map(int, lines[i + n + 1].split())) for n in range(G)]
i += G + 1
res.append((P, grudges))
return res |
def reject_info_to_report(starid, reject_info):
"""
For a given agasc_id, get all of the related "reject" info in an array
"""
log = []
for entry in reject_info:
if entry['id'] != starid:
continue
log.append(f"Not selected stage {entry['stage']}: {entry['text']}")
ret... |
def limit_sub_bbox(bbox, sub_bbox):
"""
>>> limit_sub_bbox((0, 1, 10, 11), (-1, -1, 9, 8))
(0, 1, 9, 8)
>>> limit_sub_bbox((0, 0, 10, 10), (5, 2, 18, 18))
(5, 2, 10, 10)
"""
minx = max(bbox[0], sub_bbox[0])
miny = max(bbox[1], sub_bbox[1])
maxx = min(bbox[2], sub_bbox[2])
maxy = ... |
def unicode_double_escape(s: str) -> str:
"""Remove double escaped unicode characters in a string."""
return bytes(bytes(s, "ascii").decode("unicode-escape"), "ascii").decode(
"unicode_escape"
) |
def fixedGradient(q, k, dx, U1):
""" Neumann boundary condition
Assume that the resulted gradient at boundary condition is fixed.
Please see any numerical analysis text book for details.
Return: float
"""
Ug = q / k * 2 * dx + U1
return Ug |
def missing_formula(*groups,group_labels = []):
"""
Docstring for function pyKrev.missing_formula
====================
This function compares n lists of molecular formula and outputs a dictionary containing the missing formula in each list.
Use
----
missing_formula(list_1,..,list_n)
Retu... |
def _remove_punctuation(text):
"""
Remove punctuation from a text.
:param text: the text input
:return: the text with punctuation removed
"""
if not hasattr(_remove_punctuation, 'translator'):
import string
_remove_punctuation.translator = str.maketrans('', '', string.... |
def validate_status(status):
"""
Validate status
:param status: The Status of CloudWatchLogs or S3Logs
:return: The provided value if valid
Property: CloudWatchLogs.Status
Property: S3Logs.Status
"""
valid_statuses = ["ENABLED", "DISABLED"]
if status not in valid_statuses:
r... |
def make_question(text, tag, webhook, responses=None, conclude_on=None):
"""Make a question to ask.
Args:
text (str): Question to ask.
tag (str): Question tag for retrieving results.
webhook (str): Webhook to listen for results on.
responses (:obj:`list`, optional): List of resp... |
def null_hurst_measure(measure):
"""Hurst computation parameter from some slope fit.
Parameters
----------
measure: float
the slope of the fit using some method.
Returns
-------
H: float
the Hurst parameter.
"""
# Compute measure
return float(measure) |
def extract_input(event):
"""
Returns the data from an object organized in the manner expected
"""
return event.get("body").get("data") |
def array_plus_array(arr1, arr2):
"""
Finds the sum of two arrays.
:param arr1: an array of integers.
:param arr2: an array of integers.
:return: the sum of the elements of both arrays.
"""
return sum(arr1) + sum(arr2) |
def decoded(qscore):
"""Returns Phred ASCII encoding type of FastQ quality scores.
Older FastQ files may use Phred 64 encoding.
"""
encoding = ''
# Unique set of characters across both Phred encoding types
encodings = { # Pred-33 Encoding characters
'!': '33', '#': '33', '"': '33... |
def format_bytes(size, type="speed"):
"""
Convert bytes to KB/MB/GB/TB/s
"""
# 2**10 = 1024
power = 2**10
n = 0
power_labels = {0 : 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
while size > power:
size /= power
n += 1
formatted = " ".join((str(round(size, 2)), power_lab... |
def pad_vocab_to_eight(vocab):
"""Pads vocabulary so that it is divisible by 8.
Args:
vocab (dict): vocabulary in the form token->id
Returns:
dict: vocab with new tokens added if necessary, such that the total
vocab size is divisible by 8.
"""
v_len = len(vocab)
if v_len % 8 == 0:
return v... |
def format_percent(num):
"""
Format a percentage
"""
return int(round(num)) |
def input_to_dictionary(input):
"""Method to convert Graphene inputs into dictionary"""
dictionary = {}
for key in input:
# Convert GraphQL global id to database id
# if key[-2:] == 'id':
# input[key] = from_global_id(input[key])[1]
dictionary[key] = input[key]
return... |
def get_commit_link(repo_name: str, commit_sha: str) -> str:
"""
Build a commit URL for manual browser access using full repository name and commit SHA1
:param repo_name: full repository name (i.e. `{username}/{repoanme}`)
:param commit_sha: 40 byte SHA1 for a commit
:return: A commit URL
"""
... |
def get_actions_from_policy(data):
"""Given a policy dictionary, create a list of the actions"""
actions_list = []
# Multiple statements are in the 'Statement' list
# pylint: disable=too-many-nested-blocks
for i in range(len(data['Statement'])):
try:
# Statement must be a dict if... |
def recvall(conn, length):
""" Retreive all pixels. """
buf = b''
while len(buf) < length:
data = conn.recv(length - len(buf))
if not data:
return data
buf += data
return buf |
def manhattan_distance_between(a, b):
"""
Compute manhattan distance between 2 points
"""
# return math.sqrt((a[0] - b[0])**2 + (a[1]- b[1])**2)
return max(abs(a[0] - b[0]), abs(a[1] - b[1])) |
def gt_types_to_binary_comparison(calls):
"""From an array of calls, check if a variant position qualifies as a variant.
0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT
Return string of 1s and 0s to represent position"""
binary_calls = []
for call in calls:
if call == 1 or call == 3:
bi... |
def regroup(x, n):
"""
Turns a flat list into a list of lists with sublength n
Args:
x: flat list
i: sublist len
Returns: list of lists
"""
i = 0
new_list = []
while i < len(x):
new_list.append(x[i:i + n])
i += n
return new_list |
def has_math(lines):
"""Test if math appears anywhere in the post."""
for line in lines:
if '$$' in line:
return True
elif '$' in line:
return True
return False |
def is_hangul(string):
"""Check if there is a character in the Hangul syllables block. MUST BE IN UNICODE."""
for i in string:
if 44032 <= ord(i) <= 55215:
return True
return False |
def gen_all_permutations(outcomes, length):
"""
Iterative function that enumerates the set of all permutations of
outcomes of given length.
"""
answer_set = set([()])
for dummy_idx in range(length):
temp_set = set()
for partial_sequence in answer_set:
for item in... |
def _bubbled_up_groups_from_units(group_access_from_units):
"""
Return {user_partition_id: [group_ids]} to bubble up from Units to Sequence.
This is to handle a special case: If *all* of the Units in a sequence have
the exact same group for a given user partition, bubble that value up to the
Sequen... |
def find_x_intercept(gradient:int, y_intercept:int, height:int):
"""
Find x intercept of the line with the bottom of the image from the line parameters
:param gradient: gradient of line
:param y_intercept: y intercept of line
:param height: height of the image
:return: x intercept of line with t... |
def index_to_slice(idx) -> slice:
"""Converts an index to a slice.
Args:
idx: int
The index.
Returns:
slice
A slice equivalent to the index.
"""
return slice(idx, idx+1, None) |
def extension_to_ignore(file, ignore_extensions):
"""check if file need to be ignored
Args:
file (str): file_path or file_name
ignore_extensions (list): Extensions to ignore
Returns:
bol: True to ignore. False to not ignore.
"""
file_lower = file.lower()
if len(ignore_... |
def cascaded(*args):
""" (args:any) -> arg : not None
Returns first non-None arg.
"""
for arg in args:
if arg is not None:
return arg |
def parse_cmd(script, *args):
"""Returns a one line version of a bat script
"""
if args:
raise Exception('Args for cmd not implemented')
# http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
oneline_cmd = '&&'.join(script.split('\n'))
oneline_... |
def default_eval_func(data):
"""
Evaluates the graph for accuracy. Returns the accuracy based on the current
data iteration. The default "accuracy" should always be the first entry in the list
provided to eval_names.
:param data:
:return:
"""
if len(data) > 1:
print('default eval... |
def within_percent(num1, num2, percent: int):
"""Compare two numeric values by percentage difference
Return True if they are mutually within x-percent of each other
Parameters
----------
num1 : int or float
num2 : int or float
percent : int
Percentage difference between the two. Mu... |
def choose(n, r):
"""
Returns the value of nCr
"""
if r > n//2 + 1:
r = n - r
numerator = 1
denominator = 1
for i in range(n, n - r, -1):
numerator *= i
denominator *= (n - i + 1)
return(numerator//denominator) |
def account_info(info):
"""Extract user information from IdP response"""
return dict(
user=dict(
email=info['User.email'][0],
profile=dict(
username=info['User.FirstName'][0],
full_name=info['User.FirstName'][0])),
external_id=info['User.em... |
def pure_python_hello(name:str):
"""Testing a pure python function
Args:
name (str): Just a simple name
"""
return "Hello " + name |
def check_de(current_de, list_of_de):
"""Check if any of the strings in ``list_of_de``
is contained in ``current_de``."""
return any([de in current_de for de in list_of_de]) |
def sandhi(inwords):
"""Returns a string with the following replacements performed on the provided one.
- ~s/ \+ ([^\[])/$1/g; replace + and surround spaces with nothing
- replace aa with A
- replace ii with I
- replace uu with U
- replace Ru with R
"""
i... |
def check_target(i):
"""
Input: {
dict - dictionary with info about supported host and target OS
host_os_uoa - host OS UOA (already resolved)
host_os_dict - host OS dict (already resolved)
target_os_uoa - target OS UOA (already resolve... |
def address_group_name(address):
"""
Return name of dataset group /entry/[group]/name
:param address: str hdf address
:return: str
"""
names = address.replace('\\', '/').split('/')
return names[-2] |
def get_frequency(text: str) -> dict:
"""Get word frequency from text"""
freq_dict = {}
for letter in text:
freq_dict[letter] = freq_dict.get(letter, 0) + 1
return freq_dict |
def currencyformat(value):
"""replaces the value with a currency formated number, 0 for non number"""
try:
float(value)
except:
value = 0
return '{:0,}'.format(int(round(value))) |
def _is_decoy_suffix(pg, suffix='_DECOY'):
"""Determine if a protein group should be considered decoy.
This function checks that all protein names in a group end with `suffix`.
You may need to provide your own function for correct filtering and FDR estimation.
Parameters
----------
pg : dict
... |
def multiply_and_round(num: float, factor: float = 100, precision: int = 2) -> float:
"""
Takes a floating point value (presumably one between 0 and 1), multiplies it with a given factor (default 100)
and rounds it with the given precision.
:param num: number to multiply and round
:param factor: mu... |
def noveltyprimes(n):
"""
"primes" of the form 31337 - 313333337 - see ekoparty 2015 "rsa 2070"
*** not all numbers in this form are prime but some are (25 digit is prime) ***
"""
maxlen = 25 # max number of digits in the final integer
for i in range(maxlen-4):
prime = int("3133" + ("3... |
def init_dict_brackets(first_level_keys):
"""Initialise a dictionary with one level
Arguments
----------
first_level_keys : list
First level data
Returns
-------
one_level_dict : dict
dictionary
"""
one_level_dict = {}
for first_key in first_level_keys:
... |
def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams
Args:
str1(string),str2(string): Strings to be checked if they are anagrams
Returns:
bool: If strings are anagrams or not
"""
if len(str1) != len(str2):
# Clean strings
clean_str_1 = str... |
def decide_flow_name(desc):
"""
Based on the provided description, determine the FlowName.
:param desc: str, row description
:return: str, flowname for row
"""
if 'Production' in desc:
return 'Production'
if 'Consumed' in desc:
return 'Consumed'
if 'Sales' in desc:
... |
def GetDet3(x, y, z):
"""
helper function
"""
d = x[0] * y[1] * z[2] + x[1] * y[2] * z[0] \
+ x[2] * y[0] * z[1] - x[0] * y[2] * z[1] \
- x[1] * y[0] * z[2] - x[2] * y[1] * z[0]
return d |
def replace_if_present_else_append(
objlist,
obj,
cmp=lambda a, b: a == b,
rename=None):
"""
Add an object to a list of objects, if that obj does
not already exist. If it does exist (`cmp(A, B) == True`),
then replace the property in the property_list. The names
are c... |
def _status_decode(status):
"""Decode a 1 byte status into logical and physical statuses."""
logical_status = (status & 0b00001100) >> 2
physical_status = status & 0b00000011
return (logical_status, physical_status) |
def _format_rotator_mode(value):
"""Format rotator mode, and rais appropriate error if it can't be formatted."""
modes = set(['pa', 'vertical', 'stationary'])
if value.lower() not in modes:
raise ValueError("Rotator mode must be in {!r}".format(modes))
return value.lower() |
def fix_user_permissions(permissions):
"""Converts numeric user permissions to a dictionary of permissions"""
fixed_permissions = dict()
for user in permissions:
mode = int(permissions[user])
user_permissions = dict()
user_permissions["member"] = (mode & 0b100 != 0)
user_p... |
def table_row(k, v, html):
"""Output a key-value pair as a row in a table."""
if html:
return ''.join(['<tr><td class="e">', k, '</td><td class="v">', v, '</td></tr>'])
else:
return k + '\n' + v + '\n\n' |
def remove_headers(headers, name):
"""Remove all headers with name *name*.
The list is modified in-place and the updated list is returned.
"""
i = 0
name = name.lower()
for j in range(len(headers)):
if headers[j][0].lower() != name:
if i != j:
headers[i] = he... |
def compute_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_r... |
def check_words(text: str, words: list):
"""Check if the text only contains words from the list.
Args:
- text: The text to check.
- words: The words to check for.
Returns:
- True if the text contains all the words.
"""
for word in words:
if word not in text:
return ... |
def beautify_url(url):
"""
Remove the URL protocol and if it is only a hostname also the final '/'
"""
try:
ix = url.index('://')
except ValueError:
pass
else:
url = url[ix+3:]
if url.endswith('/') and url.index('/') == len(url)-1:
url = url[:-1]
return ur... |
def calculate_factor_values(levels):
"""Calculate values of trial factors.
Parameters
----------
levels : dictionary
The factor levels of the trial.
Returns
-------
dictionary
Calculated factor values.
"""
# Set parameters based on factor levels.
f = {
... |
def isqrt(n):
"""Slightly more efficient than iroot for the special case of r=2"""
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
def get_intersection_union_jaccard(exonmap1, exonmap2):
""" get jaccard between exon map
1.3 and 2.4
jaccard = 2/4 = 0.5
"""
union_sum = 0
intersection_sum = 0
dct1 = dict()
for se in exonmap1:
s, e = se
for i in range(int(s), int(e) + 1):
if not i in... |
def parent_pk_kwarg_name(value):
"""More meaningful parent path variable name
and compatible with drf-spectacular."""
return f"{value}_id" |
def sort_result_artifact_filenames(list_of_artifact_filenames):
"""Sort the result artifact filenames
Sorts the given list of result filenames by parameter index (assumed to be
the beginning of the filename, preceding an underscore e.g.
``00004_*.qza``)
Parameters
----------
list_of_artifa... |
def _restore_case(s, memory):
"""Restore a lowercase string's characters to their original case."""
cased_s = []
for i, c in enumerate(s):
if i + 1 > len(memory):
break
cased_s.append(c if memory[i] else c.upper())
return ''.join(cased_s) |
def all_coin_types_to_string(coin_dict):
"""
Converts all coin elements into a string, no matter their value.
Keyword Arguments:
coin_dict (dict): A dictionary consisting of all 4 coin types.
Returns:
(string): The resulting string.
"""
return f"{coin_dict['plat']}p {coin_dict[... |
def decode_govee_temp(packet_value: int) -> float:
"""Decode potential negative temperatures."""
# See https://github.com/Thrilleratplay/GoveeWatcher/issues/2
# The last 3 decimal digits encode the humidity, so use "// 1000" to mask them out.
if packet_value & 0x800000:
return ((packet_value ^ ... |
def normalize_value(value):
"""
Normalizes the given value, and returns it
"""
return (value * 0.5) + 0.5 |
def outChangeNamespaces(old_namespaces, new_namespaces):
"""If old_namespaces != new_namespaces, close old namespace and open new one."""
str = ""
if old_namespaces != new_namespaces:
if len(old_namespaces) > 0:
str += "\n"
while len(old_namespaces) > 0:
str... |
def scsilun_to_int(lun):
"""
There are two style lun number, one's decimal value is <256 and the other
is full as 16 hex digit. According to T10 SAM, the full 16 hex digit
should be swapped and converted into decimal.
For example, SC got zlinux lun number from DS8K API, '40294018'. And it
should... |
def peel(event):
"""
Remove an event's top-level skin (where its flavor is determined), and return
the core content.
"""
return list(event.values())[0] |
def get_uid_gid(uid, gid=None):
"""Try to change UID and GID to the provided values.
UID and GID are given as names like 'nobody' not integer.
Src: http://mail.mems-exchange.org/durusmail/quixote-users/4940/1/
"""
import pwd, grp
uid, default_grp = pwd.getpwnam(uid)[2:4]
if gid is None:
... |
def GiB(val):
"""Calculate Gibibit in bits, used to set workspace for TensorRT engine builder."""
return val * 1 << 30 |
def validate_acronym(acronym, submission):
""" Validate a submission against the acronym. """
chunks = submission.split(' ')
acronym_len = len(acronym)
# needs to use the right number of words
if len(chunks) != acronym_len:
return False
# first letter of each word needs to match the ac... |
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (inner(word1), inner(word2) ,inner(word3)) |
def discount_opex(opex, global_parameters, country_parameters):
"""
Discount opex based on return period.
Parameters
----------
cost : float
Financial cost.
global_parameters : dict
All global model parameters.
country_parameters : dict
All country specific parameter... |
def join_namespace(namespace, ident):
"""
Joins a namespace and a bare identifier into a full identifier.
>>> join_namespace('a', 'b')
'a:b'
>>> join_namespace('', 'b')
':b'
"""
return ':'.join([namespace, ident]) |
def check_option(val, home):
"""Check whether main menu option is valid."""
try:
# Change option to integer.
val = int(val)
# Option is not in the range.
if val <= 0 or val > 3:
print('Not an option, please try again.\n\n\n')
return val, home
home... |
def gen_cols():
""" Columns to keep from Redfin listings"""
relevant_columns = [
'ADDRESS', 'CITY', 'STATE OR PROVINCE', 'ZIP OR POSTAL CODE', "PRICE",
]
return relevant_columns |
def to_range(x, start, limit):
"""wraps x into range [start, limit]"""
return start + (x - start) % (limit - start) |
def get_callbacks(callback_list):
"""
Returns a list of callbacks given a list of callback specifications.
A list of callback specifications is a list of tuples (callback_name, **callback_params).
Parameters
----------
callback_list: a list of tuples (callback_name, **callback_params)
... |
def hexlify(code):
"""Convert code to hex form."""
return f'0x{hex(code)[2:].upper().zfill(4)}' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.