content stringlengths 42 6.51k |
|---|
def write_file(content, filename):
"""
Write content to file
"""
with open(filename, 'w') as fd:
fd.writelines(content)
return content |
def b2s(binary):
"""
Binary to string helper which ignores all data which can't be decoded
:param binary: Binary bytes string
:return: String
"""
return binary.decode(encoding='ascii', errors='ignore') |
def main(textlines, messagefunc, config):
"""
KlipChop func to to convert text into unique lines
"""
counter = dict()
for line in textlines():
counter[line] = counter.get(line, 0) + 1
if config['sort']:
countsort = sorted(counter.items(), key=lambda x: x[1], reverse=True)
... |
def break_to_bytes(value):
"""
Breaks a value into values of less than 255 that form value when multiplied.
(Or almost do so with primes)
Returns a tuple
>>> break_to_bytes(200)
(200,)
>>> break_to_bytes(800)
(200, 4)
>>> break_to_bytes(802)
(2, 2, 200)
"""
if value < 25... |
def prime_factors(n, given_primes):
"""Return a list with all prime factors of n."""
factors = []
if n < 2:
return factors
p = 2
while n >= (p * p):
if n % p:
p += 1
else:
if p not in given_primes:
return []
n = n // p
... |
def GetMetricsFromUsers(user):
"""For each user, produce a dict of metric data"""
metrics = []
labelset = {
'user': user['name']
}
# Get last login from now
metrics.append({'metric': 'user_session', 'value': user['sessions'], 'labelset': labelset})
metrics.append({'metric': 'user_l... |
def bert_get_tokenized_string_span_map(text, b_tokens, verbose=False):
"""
Given a string, an a BERT tokenization of the string, returns list of
[
bert_token,
start char index of token in string,
(exclusive) end char index of token in string,
]
There is so... |
def simple_dist(x1: float, x2: float) -> float:
"""Get distance between two samples for dtw distance.
Parameters
----------
x1:
first value
x2:
second value
Returns
-------
float:
distance between x1 and x2
"""
return abs(x1 - x2) |
def calculate_acc(n300, n100, n50, nMiss):
"""
calculate the acc based on number of hits
:param n300: number of 300s
:param n100: number of 100s
:param n50: number of 50s
:param nMiss: number of misses
:return: accuracy
"""
return (50 * n50 + 100 * n100 + 300 * n300) / (300 * (nMiss... |
def calc_superfCubo(c):
"""A area da superficie de um objeto e a area combinada de todos os lados de sua superficie.
Todos os seis lados de um cubo sao congruentes, entao para encontrar a area da superficie de um cubo,
tudo o que voce tem de fazer e encontrar a area da superficie de um dos lados do... |
def bool_yes_no(process, longname, flag, value):
""" Phrase Boolean values as 'YES' or 'NO' """
if value==True:
return "YES"
if value==False:
return "NO"
# Anything else wasn't a bool!
raise ValueError("Flag value '%s' wasn't boolean." % repr(value)) |
def get_value(key, my_dictionary):
"""
Gets the value that corresponds to a key in a
dictionary
:param key: String,
:param my_dictionary: Dict
:return: String
"""
return (my_dictionary[key]) |
def num_digits(n):
"""
Returns the number of digits in the number n
Examples:
>>> num_digits(89556)
5
>>> num_digits(20)
2
>>> num_digits(10**200)
201
>>> num_digits(0)
1
>>> num_digits(1)
1
"""
n = str(... |
def is_iterable(x):
"""
:param x:
:return:
"""
try:
iterator = iter(x)
except TypeError:
return False
else:
return True |
def part_two(data):
"""Part two"""
lengths = [ord(x) for x in data]
lengths.extend([17, 31, 73, 47, 23])
rope = [x for x in range(0, 256)]
rope_length = len(rope)
current_position = skip_size = 0
for _ in range(64):
for length in lengths:
sub_list = []
for i i... |
def split_func(string):
"""
Take a string like 'requiredIf("arg_name")'
return the function name and the argument:
(requiredIf, arg_name)
"""
ind = string.index("(")
return string[:ind], string[ind+1:-1].strip('"') |
def reverse_array_2(arr, start, end):
"""
A method to reverse an array within the given start and end ranges
Space complexity = O(1)
Time complexity = O(n)/2
:param arr: The array to reverse
:param start: The start index within array to reverse
:param end: The end index within array to rev... |
def slope_line(first_point, second_point):
"""
Calculate a value of a line slope for the given two points.
Parameters
----------
first_point, second_point : tuple
A tuple containing xy coordinates (float) on the color-color plane.
Returns
-------
slope : float
A value o... |
def parse_data_pattern_rule(report_json, verdict_field, results_field):
"""
Parses data pattern matches from a given rule in DLP report JSON
Args:
report_json: DLP report json
verdict_field: Name of the verdict field
results_field: Name of the result field
Returns: data pattern ... |
def get_ilo_version(ilo_fw_str):
"""Gets the float value of the firmware version
Converts a string with major and minor numbers to a float value.
:param ilo_fw_tup: String containing the major and minor versions
of the form <major>.<minor>
:returns: float value constructed from ... |
def get_name(item):
"""Returns the full name of an item."""
_prefixes = [item['prefix']]
if 'burning' in item:
if item['burning']:
_prefixes.append('burning')
elif item['burnt']:
_prefixes.append('burnt')
if 'capacity' in item:
_score = item['capacity']/float(item['max_capacity'])
if _score >= ... |
def dict_key(d, k):
"""Returns the given key from a dictionary."""
return d.get(k, "") |
def sort_by_length(arr):
"""Sort list of strings by length of each string."""
return sorted(arr, key=len) |
def getdefault(doc, key, default):
"""Return the value in 'doc' with key 'key' if present and not None.
Return the specified default value otherwise.
"""
value = doc.get(key)
if value is not None:
return value
return default |
def eval_operand(expr, pos=0, direction=1):
"""
>>> eval_operand(EX1)
(1, 1)
>>> eval_operand(EX1[19:])
(6, 2)
>>> eval_operand(EX6)
('(2 + 4 * 9) * (6 + 9 * 8 + 6) + 6', 35)
>>> eval_operand(EX6, 1)
('2 + 4 * 9', 12)
>>> eval_operand(" 36 ")
(36, 4)
>>> eval_operand("... |
def get_initial_lock_expiration(block_number, settle_timeout):
""" Returns the expiration for first hash-time-lock in a mediated transfer. """
# The initiator doesn't need to learn the secret, so there is no need to
# decrement reveal_timeout from the settle_timeout.
#
# The lock_expiration could be... |
def to_int(x, error=0):
"""Convert argument to int."""
try:
return int(x)
except (ValueError, TypeError):
return error |
def to_bytes(text):
"""Return string text as bytes, but return bytes text as is."""
if isinstance(text, str):
return text.encode('utf-8')
elif isinstance(text, bytes):
return text
else:
raise TypeError(f"Expected text to be of type str or bytes, instead got {type(text)}.") |
def parse_source_from_name(file_name: str) -> str:
"""Parses the source id from a DataVault file name.
Using the naming convention used across the different file types in the DataVault
platform, that structures file names according to the '<FILE-TYPE>_<SOURCE-ID>_<DATE>'
format, the function parses the... |
def readFile(filePath):
""" reads a file, returning an array of lines in the file """
lines = [] # or even lines = [l for l in file]
try:
file = open(filePath)
except FileNotFoundError:
print("Invalid File Path Provided")
else:
for l in file:
lines.a... |
def sort_against(list1, list2, reverse=False):
"""
Arrange items of list1 in the same order as sorted(list2).
In other words, apply to list1 the permutation which takes list2
to sorted(list2, reverse).
"""
try:
return [item for _, item in
sorted(zip(list2, lis... |
def str2val(maybe_str, mapping, *args, **kwargs):
""" Map key to value if argument is a string."""
if isinstance(maybe_str, str):
return mapping[maybe_str](*args, **kwargs)
# Object ready instantiated, we can just return it.
return maybe_str |
def escape_invis_chars(input):
"""Escape invisible/control characters."""
return input.encode('ascii', 'escape-invis').decode('utf-8') |
def F(y, t):
"""
Return derivatives for 2nd order ODE y'' = -y.
"""
dy = [0, 0] # preallocate list to store derivatives
dy[0] = y[1] # first derivative of y(t)
dy[1] = -y[0] # second derivative of y(t)
return dy |
def find_permission(stat_mode):
"""This function takes st_mode value from file stat as an argument and returns the file mode in human readable format
"""
mode=''
mode_pattern={'0':'---','1':'--x','2':'-w-','3':'-wx','4':'r--','5':'r-x','6':'rw-','7':'rwx'}
for digit in str(stat_mode):
mode=m... |
def match(list1, list2, nr1, nr2, maxcount=3):
""" return the number matching items after the given positions
maximum maxcount lines are are processed
"""
i = 0
len1 = len(list1)
len2 = len(list2)
while nr1 < len1 and nr2 < len2 and list1[nr1] == list2[nr2]:
nr1 += 1
nr2 ... |
def generate_cipher_response(cipher: str, key_size: int) -> str:
"""Generate a response message
:param cipher: chosen cipher
:param key_size: chosen key size
:return: (cipher, key_size) selection as a string
"""
return "ChosenCipher:{},{}".format(cipher, key_size) |
def lock(server_id, **kwargs):
"""Lock server."""
url = '/servers/{server_id}/action'.format(server_id=server_id)
req = {"lock": None}
return url, {"json": req} |
def _get_add_scalar_output_quant_param(input_scale, input_zero_point, scalar):
"""
Determine the output scale and zp of quantized::add_scalar op
This is used for mobilenet v3
Refer to aten/src/ATen/native/quantized/cpu/qadd.cpp
The names of variables are the same as torch impl
"""
q_min = 0
... |
def _verify_additional_type(additionaltype):
"""Check that the input to additionaltype is a list of strings.
If it is empty, raise ValueError
If it is a string, convert it to a list of strings."""
if additionaltype is None:
return None
if isinstance(additionaltype, str):
additionalt... |
def coi_rate(t):
"""Cost of insurance rate per account value
The cost of insuranc rate per account value per month.
By default, it is set to 1.1 times the monthly mortality rate.
.. seealso::
* :func:`mort_rate_mth`
* :func:`coi_pp`
* :func:`coi_rate`
"""
return 0 ... |
def get_direction(connection_byte, connection_id):
"""given a connection byte and a connection id, which direction is this connection?
the 0th connection of $5 is SOUTH and the 1st connection is EAST"""
connection_options = [0b1000, 0b0100, 0b0010, 0b0001]
results = ["NORTH", "SOUTH", "WEST", "EAST"]
... |
def unfurl(deps, provider = ""):
"""Returns deps as well as deps exported by parent rules."""
res = []
for dep in deps:
if not provider or hasattr(dep, provider):
res.append(dep)
if hasattr(dep, "exports"):
for edep in dep.exports:
if not provider or h... |
def fix_label(label):
"""Fix axis label taken from the command line."""
replace_dict = {'_': ' ',
'degE': '$^{\circ}$E',
'ms-1': '$m s^{-1}$',
'm.s-1': '$m s^{-1}$',
'Wm-2': '$W m^{-2}$',
'1000000 m2.s-1': '$10^... |
def optional_dependency_graph(page, *provided_dependencies):
"""Creates a dependency graph for a page including all dependencies and optional_dependencies
Any optional provided_dependencies will be included as if they were dependencies,
without affecting the value of each keyed page.
"""
graph = {}... |
def lowercase(text):
"""
Lowercase given text
:param text:
:return: lower text
"""
return text.lower() |
def _codes(event, structure):
"""Return the codes associated to an event."""
# List to store resulting codes
coding = list()
# Terminology
etype = event["type"]
namespace = "sempryv"
key_codes = namespace + ":codes"
key_rec = namespace + ":recursive"
# Codes associated to the event
... |
def norm(value, start, stop):
"""
Interpolate using a value between 0 and 1
See also: https://processing.org/reference/norm_.html
"""
return start + (stop-start) * value |
def is_tt_ar(words):
"""Is the word a TT/AR (transmission turnaround / auto response)?"""
return len(words) == 1 and words[0] == 0 |
def is_stochastic_matrix(m, ep=1e-8):
"""Checks that the matrix m (a list of lists) is a stochastic matrix."""
for i in range(len(m)):
for j in range(len(m[i])):
if (m[i][j] < 0) or (m[i][j] > 1):
return False
s = sum(m[i])
if abs(1. - s) > ep:
ret... |
def get_complement(sequence):
"""Get the complement of `sequence`.
Returns a string with the complementary sequence of `sequence`.
If `sequence` is empty, and empty string is returned.
"""
comp={"G":"C", "C":"G", "U":"A", "A":"U"}
ment=str()
if sequence==0:
return ""
... |
def mac_addr_is_unicast(mac_addr):
"""Returns True if mac_addr is a unicast ethernet address.
arguments:
mac_addr - a string representation of a mac address."""
msb = mac_addr.split(":")[0]
return msb[-1] in "02468aAcCeE" |
def next_alphabetic_character(character):
"""
Given an alphabet (any upper or lowercase) returns the next alphabet
>>> next_alphabetic_character('A')
'B'
>>> next_alphabetic_character('a')
'b'
"""
return chr(ord(character) + 1) |
def check_valid_dimension(dim, prev_list):
"""Check the dimension is within the correct range"""
if not 0 < dim < 21:
raise Exception("Please use a dimension between 1 and 20.")
if prev_list and (dim > len(prev_list)):
raise Exception(
"You have not specified enough dimensions "
... |
def keep_accessible_residues(dssp_rsa, threshold):
"""
From the output of DSSP we keep only accessible residues which have an RSA
value > threshold (arbitrary threshold).
Args:
dssp_rsa (dict): A dictionary as keys = residue index and value = RSA.
threshold (int): Relative solvant ... |
def get_validation_description(validation_flag):
"""
Return the validation description from the validation flag
:param validation_flag: the validation flag
:return: the validation description
"""
if validation_flag == -1:
return 'ALTERED'
elif validation_flag == 1:
return 'VA... |
def scrub(input_string):
"""Clean an input string (to prevent SQL injection).
Parameters
----------
input_string : str
Returns
-------
str
"""
return "".join(k for k in input_string if k.isalnum()) |
def read_range(s):
"""
Utility function to allow ranges to be read by the config parser
:param s: string to convert to a list
:type s: string
:return: two element list [lower_lim, upper lim]
:rtype: list
"""
if s[0] != '[' or s[-1] != ']':
raise ValueError("range specified wit... |
def parse_metadata_resource(resource_map=None):
"""
Returns the metadata resource found in a PASTA resource map
"""
metadata_resource = ""
if resource_map:
resources = resource_map.split('\n')
for resource in resources:
if '/metadata/' in resource:
metadat... |
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /... |
def rsuffix(suffix) -> str:
"""Returns a new suffix for some files.
Currently if will replace .m3u or .m3u8 with mp4.
:param suffix: The suffix that should be checked
:return: Returns the old or replaced suffix.
"""
if suffix.startswith('.m3u8') or suffix.startswith('.m3u'):
return '.mp... |
def course_str(course):
"""Format course as a string."""
return (
f"[{course['pk']}] {course['name']} "
f"{course['semester']} {course['year']}"
) |
def get_next_target(page):
"""
Takes a page as input, searches for the first link on that page,
returns that as the value of url and also returns the position
at the end of the quote as the starting point for the next search.
"""
start_link = page.find('<a href=')
if start_link == -1:
... |
def dict_in_list_always(main, sub):
"""
>>> main = [{'c': 'c', 'a': 'a', 'b': 'b'}, {'c': 'c', 'd': 'd'}]
>>> dict_in_list_always(main, {'a': 'a', 'b': 'b', 'c': 'c'})
False
>>> dict_in_list_always(main, {'c': 'c', 'd': 'd'})
False
>>> dict_in_list_always(main, {'a': 'a', 'c': 'c'})
Fals... |
def length(s):
"""
Null (none) safe length function.
:param str s: the string to return length of (None allowed)
:rtype: int
"""
if s is not None:
return len(s)
return 0 |
def num_exact_matches(possible_matches):
"""Returns the number of exact matches in the possible match list."""
count = 0
for score, request in possible_matches:
if score.is_exact_match():
count += 1
return count |
def pos_in_box(pos, lbox):
"""Positions in [-lbox/2, lbox/2)
Args:
pos (np.array): positions in open BC
lbox (float): cubic box side length
Return:
np.array: positions in box centered at 0
"""
return (pos+lbox/2.) % lbox - lbox/2. |
def iou(bbox1, bbox2):
"""
Calculates the intersection-over-union of two bounding boxes.
Args:
bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
Returns:
int: intersection-over-onion o... |
def BlockOffWithStars(string):
"""Puts a star at the beginning and at the end of a string"""
return ("* " + string + " *") |
def date_format(date):
""" '2021-12-29 10:28:23' -> '2021-12-29T10:28:23Z' """
return "T".join(date.split(" ")) + "Z" if "Z" not in date else date |
def parseFloat(num):
"""Parse floats from MongoDB."""
if num and num != 0:
return num / 100
else:
return None |
def strip_folder_name(filename):
"""
Remove initial folder name from the given filename.
"""
return filename.split('/')[-1] |
def xor(a, b):
"""
exclusive or; a or b, but not both
>>> xor(1, 0)
1
>>> xor(0, 1)
1
>>> xor(1, 1)
0
>>> xor(0, 0)
0
"""
return int((a or b) and not (a and b)) |
def parse_kwargs(val):
"""
Given a string with form:
'x=1 y=2'
it parses it to return a dictionary of the form:
{x:1, y:2}
Arguments:
val: str
Returns:
parsed kwargs: dict
"""
kwargs = {}
if val:
for pair i... |
def get_proj_mat_by_coord_type(img_meta, coord_type):
"""Obtain image features using points.
Args:
img_meta (dict): Meta info.
coord_type (str): 'DEPTH' or 'CAMERA' or 'LIDAR'.
Can be case-insensitive.
Returns:
torch.Tensor: transformation matrix.
"""
coord_type... |
def rename_dict_key(_old_key, _new_key, _dict):
"""
renames a key in a dict without losing the order
"""
return { key if key != _old_key else _new_key: value for key, value in _dict.items()} |
def get_launch_cmd(app_name, developer_name):
"""Returns cmd string to launch application"""
return 'bash -c "ubuntu-app-launch {0}.{1}_{0} &"'\
.format(app_name, developer_name) |
def arg_require(args_array, opt_req_list):
"""Function: arg_require
Description: Checks to see if the required options are included.
Arguments:
(input) args_array -> Array of command line options and values.
(input) opt_req_list -> Options that are required.
(output) status -> T... |
def err(text):
"""Create a pretty error string from text."""
return f"\033[91m{text}\033[m" |
def search_for_duplicated_value(sequence):
"""
Using a varient of the binary search. Note that it does not return the first duplicate value
but one of the duplicate values.
O(nlogn) - time
O(1) - space
"""
floor = 0
ceiling = len(sequence) - 1
while floor < ceiling:
mid ... |
def categorize_transcript_recovery(info):
"""
full --- means that every exon in the tID was covered!
fused --- full, but assembled exon match start > 0, meaning
likely fusion of overlapped transcripts
5missX --- means that the assembled one is missing beginning X exons
3missY ---... |
def median_of_two_sorted_array(array1, array2):
"""
:param array1: given array 1
:param array2: given array 2
:return: The median and merged array
Method: Use merge sort
Complexity: O(n)
"""
if len(array1) != len(array2):
return "Invalid input"
i = 0
j = 0
n = len(arr... |
def get_fibonacci_sequence(length: int) -> list:
"""Return the fibonacci sequence to the specified length."""
fibonacci_sequence = [0, 1]
if length == 1:
return [fibonacci_sequence[0], ]
elif length == 2:
return fibonacci_sequence
for _ in range(0, length - 2):
second_to_las... |
def set_hidden_measurement_lists_from_observability(num_nodes, observability, list_bus_id_hiding_priority=None):
"""
Returns the list of the hidden power bus ids and a list of hidden voltage ids
:param num_nodes: number of buses in the grid
:param observability: a fractional number in [0.0, 1.0] which
... |
def bash_quote(s):
"""
POSIX-compatible argument escape function designed for bash. Use this to quote variable
arguments that you send to `container.bash("...")`.
Note that pipes.quote and subprocess.list2cmdline both produce the INCORRECT value to use in
this scenario. Do not use those. Use this.
... |
def distance(feasible_ind, original_ind):
"""A distance function to the feasibility region."""
return sum((f - o)**2 for f, o in zip(feasible_ind, original_ind)) |
def is_on(param: str) -> bool:
"""
Returns True if parameter in "on" values
On values:
- true
- t
- on
- yes
- y
- 1
"""
values = ["true", "t", "on", "yes", "y", "1"]
if str(param).lower() in values:
return True
else:
return Fal... |
def is_item_exist(data, item) -> bool:
"""
:param data:
:param item:
:return:
"""
if item in data:
return True
return False |
def is_ordinal(symbol):
"""
is the given symbol an ordinal that is prefixed by "#"?
"""
if symbol:
return symbol[0] == "#"
return False |
def is_instance_id(instance):
""" Return True if the user input is an instance ID instead of a name """
if instance[:2] == 'i-':
return True
return False |
def get_morse_pairs(nspcs):
"""Compute pairs for BVS-Morse from nspcs, which means only anion-cation pairs.
"""
pairs = []
for i in range(2,nspcs+1):
pairs.append((1,i))
return pairs |
def even(n : int) -> bool:
""" """
return (n % 2) == 0 |
def has_seven(k):
"""Returns True if at least one of the digits of k is a 7, False otherwise.
>>> has_seven(3)
False
>>> has_seven(7)
True
>>> has_seven(2734)
True
>>> has_seven(2634)
False
>>> has_seven(734)
True
>>> has_seven(7777)
True
>>> from construct_check... |
def generateGenotype(candidates):
"""Voting algorithm for generating of the genotype of the SV.
Args:
candidates (list of SVariant): List with all candidate SV variants.
Returns:
str: Genotype of the variant.
"""
gt0 = 0
gt1 = 0
for candidate in candidates:
if("0/1"... |
def scale_value(value):
""" Scale sensor value between 0 and 60. """
if value > 1000:
value = 1000
elif value < 300:
value = 300
new_value = (value - 300.0) / 700.0
return round(new_value * 60.0) |
def quaternion_conjugate(q):
"""Conjugate of a quaternion.
Parameters
----------
q : list
Quaternion as a list of four real values ``[w, x, y, z]``.
Returns
-------
list
Conjugate quaternion as a list of four real values ``[cw, cx, cy, cz]``.
References
----------
... |
def proto_select_attribute_in(node, attribute, values):
"""
Return True if the given attribute of the node is in a list of values.
To be used as a selector, the function must be wrapped in a way that it can
be called without the need to explicitly specify the 'attribute' and
'values' arguments. Thi... |
def sum_root_helper(root, partial_sum):
"""
Helper to keep track of partial sums as
getting remainder of root to leaf sums
"""
if root is None:
return 0
partial_sum = partial_sum * 2 + root.val
if not root.right and not root.left:
return partial_sum
return sum_root_help... |
def split_list(l, sizes):
"""
Split a list into several chunks, each chunk with a size in sizes
"""
chunks = []
offset = 0
for size in sizes:
chunks.append(l[offset:offset + size])
offset += size
return chunks |
def sgn(x):
"""Retorna el signo de x"""
if x > 0:
return 1
elif x == 0:
return 0
else:
return -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.