content stringlengths 42 6.51k |
|---|
def positive_number_to_smt(number):
"""
Print a floating-point number in decimal notation (i.e., prevent scientific notation).
This code is taken from https://stackoverflow.com/a/45604186.
:param number: floating-point number
:return: string in decimal notation
"""
number_as_two_strings = st... |
def is_pangram(sentence):
"""
return true if 'sentence' is an pangram
"""
sentence = sentence.lower()
return all(sentence.find(c) != -1 for c in 'abcdefghijklmnopqrstuvwxyz') |
def err(error_dictionary):
"""
Formats the error response as wanted by the Flask app
:param error_dictionary: name of the error dictionary
:return: tuple of error message and error number
"""
return {'error': error_dictionary['message']}, error_dictionary['code'] |
def toHex(val):
"""Converts the given value (0-255) into its hexadecimal representation"""
hex = "0123456789abcdef"
return hex[int(val / 16)] + hex[int(val - int(val / 16) * 16)] |
def bezier_cubic(p0, p1, p2, p3, t):
"""returns a position on bezier curve defined by 4 points at t"""
return (1-t)**3*p0 + 3*(1-t)**2*t*p1 + 3*(1-t)*t**2*p2 + t**3*p3 |
def escape_path(path):
"""
Escapes any characters that might be problematic in shell interactions.
:param path: The original path.
:return: A potentially modified version of the path with all problematic characters escaped.
"""
return path.replace("\\", "\\\\") |
def process_code_info(analysis, extensions):
"""Processes FileInformation objects into dictionary described below
Structure of the dictionary produced by this tool is:
{
<file_name>: {
"nloc": <file.nloc>,
"average_nloc": <file.average_NLOC>,
"average_tokens": <f... |
def pad(lst, length, padding=' '):
"""
Pad a list up to length with padding
"""
return lst+[padding]*(length-len(lst)) |
def _jinja2_filter_storage_percent_class(value):
"""Formats the storage percentage class for templates"""
value = int(value[:-1])
if value < 95:
return "progress-bar"
elif value < 99:
return "progress-bar progress-bar-warning"
return "progress-bar progress-bar-danger" |
def subtractL(a, b, strict = True): # Multiset a - b.
""" Returns a new list: a - b. """
a = a[:]
for x in b:
try:
a.remove(x)
except ValueError as err:
if strict:
raise err
return a |
def ordenar_extraterrestre(desordenadas, orden_alfabeto):
"""Orders a list of words based on custom alphabet order"""
ordenada = sorted(
desordenadas, key=lambda word: [orden_alfabeto.index(char) for char in word]
)
return ordenada |
def _remove(target, delete):
"""
Removes fields from the target.
:param target: the JSON schema to remove fields from.
:param delete: the JSON schema fields to remove
:return: the target minus the delete fields.
"""
for k, v in delete.items():
dv = target.get(k)
if dv is not ... |
def trim_envelope(env):
"""Trim envelope to global extents
"""
# clip extents if they are outside global bounding box
for c in range(len(env)):
if env[c][0] < -180:
env[c][0] = -180
elif env[c][0] > 180:
env[c][0] = 180
if env[c][1] < -90:
en... |
def c_to_f(temp):
"""
Converts Celsius to Fahrenheit.
"""
return temp * 9/5 + 32 |
def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for c in seq:
# Screen out non-printing characters.
try:
if 32 >= c < 256:
string += chr(c)
except TypeError:
pass
# If no pri... |
def check_unique_name(first_letters, count, name, unique_list, suffix=False):
"""Making sure new_name does not already exist
Args:
first_letters (str): string at the beginning of the name, giving a hint
on what the variable is.
count (int): increment to create a unique id in the nam... |
def ssXXsuffix( i ):
"""Turns an integer into an ssXX ending between .ss01 and .ss20, e.g. 5 -> '.ss05'."""
if i < 1:
i = 1
elif i > 20:
i = 20
return ".ss%0.2d" % i |
def round_down(num,divisor):
"""round_down rows the value down by a divisor value.
Args:
num (int): An integer.
divisor (int): A number to divise by.
Returns:
[int]: A rounded down value byt he divisor.
"""
return num - (num%divisor) |
def add(A, B):
"""
Just writing this comment because it will pop up when asked for help
"""
C=A+B
return C |
def is_html_needed(user_agent):
"""
Basing on `user_agent`, return whether it needs HTML or ANSI
"""
plaintext_clients = ['curl', 'wget', 'fetch', 'httpie', 'lwp-request', 'python-requests']
if any([x in user_agent for x in plaintext_clients]):
return False
return True |
def QCheck(num):
"""Do a quick check if there is an even number in the set...at some point it will be an even number in rotation"""
numstr = str(num)
for i in range(len(numstr)):
if int(numstr[i]) % 2 == 0:
return False
if int(numstr[i]) % 5 == 0:
return False
re... |
def decode(encoded):
""""Take a JSOG-encoded JSON structure and create a new structure which re-links all the references. The return value will
not have any @id or @ref fields"""
# This works differently from the JavaScript and Ruby versions. Python dicts are unordered, so
# we can't be certain to see associated @i... |
def longest_common_substring(data):
"""
Return a longest common substring of a list of strings:
>>> longest_common_substring(["apricot", "rice", "cricket"])
'ric'
>>> longest_common_substring(["apricot", "banana"])
'a'
>>> longest_common_substring(["foo", "bar", "baz"])
... |
def count_by(x, n):
""" Return a sequence of numbers counting by `x` `n` times. """
return range(x, x * n + 1, x) |
def isSol(res):
"""
Check if the string is of the type ai bj ck
"""
if not res or res[0] != 'a' or res[-1] != 'c':
return False
l = 0
r = len(res)-1
while res[l] == "a":
l+=1
while res[r] == "c":
r-=1
if r-l+1 <= 0:
return False
... |
def jaccard(set1,set2):
""" Calculates Jaccard coefficient between two sets."""
if(len(set1) == 0 or len(set2) == 0):
return 0
return float(len(set1 & set2)) / len(set1 | set2) |
def get_sender_id(data: dict) -> str:
"""
:param data: receives facebook object
:return: User id which wrote a message, type -> str
"""
sender_id = data['entry'][0]['messaging'][0]['sender']['id']
return sender_id |
def altz_to_utctz_str(altz):
"""As above, but inverses the operation, returning a string that can be used
in commit objects"""
utci = -1 * int((altz / 3600)*100)
utcs = str(abs(utci))
utcs = "0"*(4-len(utcs)) + utcs
prefix = (utci < 0 and '-') or '+'
return prefix + utcs |
def remove_invalid_fields(field):
"""For a record definition, remove all the invalid fields, otherwise return itself
Column type is a dict of the form {name: str, type: str, mode: str, fields: str?}"""
if field.get('type', 'INVALID') == 'RECORD':
field['fields'] = [remove_invalid_fields(subfield)... |
def log_dir_name(learning_rate, num_dense_layers,
num_dense_nodes, activation):
"""
Function to log traning progress so that can be viewed by TnesorBoard.
"""
# The dir-name for the TensorBoard log-dir.
s = "./19_logs/lr_{0:.0e}_layers_{1}_nodes_{2}_{3}/"
# Insert all th... |
def choose_pivot(list, length):
"""
This function choose a pivot from the list
The function check the first, middle and last elements of the list,
and return the middle of there values (not the smallest and not the biggest)
:param list: the unsorted list
:param len: the list length
:retur... |
def solution(A, B):
"""
https://app.codility.com/demo/results/trainingDJQ263-4J9/
:param A: weights
:param B: direction
0 represents a fish flowing upstream - 0 fish ------ left direction
1 represents a fish flowing downstream - 1 fish ------ right direction
:return:
"""
stay_alive... |
def rotate(password, rotate_type, *params):
"""Rotate password
- rotate left/right X steps - means that the whole string
should be rotated; for example, one right rotation would turn
abcd into dabc.
- rotate based on position of letter X - means that the whole string should
be rotat... |
def getSignedVal(num: int, bitSize: int):
"""
Return the signed value of the number.
:param num: unsigned integer value
:param bitSize: length of the value in bits
"""
mask = (2 ** bitSize) - 1
if num & (1 << (bitSize - 1)):
return num | ~mask
else:
return num & mask |
def get_system_name_mappings(column_data):
"""
Given a column_data dict, get dicts mapping the system_name
to the display name, and vice versa.
"""
system_name_to_display_name = {}
display_name_to_system_name = {}
for key, entry in column_data.items():
if entry.get("system_name", No... |
def nth(items, i):
"""
Get the nth item from an iterable.
Warning: It consumes from a generator.
:param items: an iterable
:return: the first in the iterable
"""
for j, item in enumerate(items):
if j == i:
return item |
def format_output(files_filtered):
"""
"""
return " ".join(files_filtered) |
def gate_boundaries(gate_map):
""" Return gate boundaries
Args:
gate_map (dict)
Returns:
gate_boundaries (dict)
"""
gate_boundaries = {}
for g in gate_map:
gate_boundaries[g] = (-2000, 2000)
return gate_boundaries |
def calc_freq(text: str, topics: dict) -> dict:
"""Returns dict of occurrences of keywords for each category"""
text = text.lower()
occurrences = {}
for subject in topics:
freq = 0
index = 0
for keyword in topics[subject]:
while text.find(keyword, index) != -1:
... |
def go_down_right(x: int, y: int) -> tuple:
"""
Go 1 unit in negative y-direction and 1 unit in positive x-direction
:param x: x-coordinate of the node
:param y: y-coordinate of the node
:return: new coordinates of the node after moving diagonally down-right
"""
return x - 1, y + 1 |
def property_mapping_to_dict(cs_data):
"""Converts the property mapping in config strategy data from an
array like [ {'source': 'string'}, {'target': 'string'} ] to
a dict with { 'source-string': 'target-string', ... }.
"""
property_mapping_arr = cs_data['properties']['mapping']
property... |
def selection_largest_first(lst):
"""Find largest element and move to end of list, sort from there."""
for i in range(len(lst) - 1, 0, -1):
max_val=0
for j in range(1, i + 1):
if lst[j] > lst[max_val]:
max_val = j
temp = lst[i]
lst[i] = lst[max_val]
... |
def create_dict_from_guard_rows(col_dict):
"""Create a dictionary of lists from a dictionary of guard values
Parameters
----------
col_dict : `dict`
The dictionary with the guard values
Returns
-------
ret_dict : `dict`
The dictionary we created
"""
ret_dict = {}
... |
def aggregate(iterator, only_no_facts = False):
""" Aggregates the records of this iterator.
Returns a 3-tuple (dict, int, float) with predicate->time, count and total.
"""
predicates = dict()
count = 0
total = float(0)
for (pred, time, facts) in iterator:
if facts == 0 or not o... |
def sum_closest_to_zero(array):
"""
:param array: given integer array
:return: Two elements such that their sum is closest to zero.
Method: 1
Complexity: O(n)
"""
if len(array) == 0:
return 0
array = sorted(array)
min_left = left = 0
min_right = right = len(array) - 1
... |
def recalc_level(level, exp, exp_change):
""" Recalculate level and EXP after exp_change. """
exp += exp_change
if exp >= 0:
required = 1000 * (level + 1)
while exp >= required:
level += 1
exp -= required
required += 1000
else:
while exp < 0 a... |
def frombin(v):
"""MSB to LSB binary form"""
return int("".join(map(str, v)), 2 ) |
def match_entry(x, name, exclude):
""" identify config devices in any line listed in config not containing vdev keyword """
return not any(substring in x for substring in (exclude + (name,))) |
def sanitize_name_for_disk(name: str):
"""
Removes illegal filename characters from a string.
:param name: String to clean.
:return: Name with illegal characters removed.
"""
return "".join(char for char in name if char not in "|<>:\"/?*\\") |
def center_id_from_filename(filename):
"""Given the name of a rollgen PDF output file, return the center_id embedded in that name"""
# Fortunately all filenames are of the format NNNNN_XXXXXX.pdf where NNNNN is the center id
# and everything else comes after the first underscore.
return int(filename[:fi... |
def _naive_B(x, k, i, t):
"""
Naive way to compute B-spline basis functions. Useful only for testing!
computes B(x; t[i],..., t[i+k+1])
"""
if k == 0:
return 1.0 if t[i] <= x < t[i+1] else 0.0
if t[i+k] == t[i]:
c1 = 0.0
else:
c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_... |
def mymap(val, in_min, in_max, out_min, out_max):
"""
Returns the value which was mapped between in_min and in_max,
but now mapped between out_min and out_max.
If value is outside of bounds, it will still be outside afterwards.
"""
return int((val - in_min) * (out_max - out_min) / (in_ma... |
def calculate_precision_recall_F_metrics(algorithm_number, real_number, correct_number):
"""
Result: (precision, recall, F)
"""
if algorithm_number == 0:
precision = 0
else:
precision = float(correct_number) / algorithm_number
if real_number == correct_number: # 0 / 0
re... |
def _starts_with_vowel(char) -> bool:
"""Test to see if string starts with a vowel
Args:
char: character or string
Returns:
bool True if the character is a vowel, False otherwise
Examples:
>>> _starts_with_vowel('a')
True
>>> _starts_with_vowel('b')
Fal... |
def _intTime(tStr):
"""
Converts a time given as a string containing a float into an integer representation.
"""
return int(float(tStr)) |
def fix_kw(kw):
"""Make sure the given dictionary may be used as a kw dict independently on
the python version and encoding of kw's keys."""
return dict([(str(k), v) for k, v in list(kw.items())]) |
def _str(uni):
"""
Make inbound a string
Encoding to utf-8 if needed
"""
try:
return str(uni)
except:
return uni.encode('utf-8') |
def _parse_content_type(content_type):
"""best efforts on pulling out the content type and encoding from Content-Type header"""
try:
content_type = content_type.strip()
except AttributeError:
pass
char_set = None
if content_type.strip():
splt = content_type.split(';')
... |
def PrintToConsole(message):
"""User defined function printing to console."""
print(message)
return 1 |
def iterable(obj):
"""
Check obj if is iterable
:param obj: object
:return: boolean
"""
return hasattr(obj, "__iter__") |
def center_ranges(input_ranges):
"""Given a list of sequences, create a list of new sequences
which are all the same length, by repeating the element
on the ends of any sequences shorter than the max length.
If any of the sequences is empty, they must all be empty
or a ValueError is raised (since th... |
def validate_lbmethod(s, loc, tokens):
"""Validate the load balancing method used for real servers"""
methods = ['gate', 'masq', 'ipip']
if tokens[0] in methods:
return tokens
else:
errmsg = "Loadbalancing method must be one of %s " % ', '.join(methods)
raise ParseFatalException(... |
def ucfirst(string):
"""Return string with first letter in upper case."""
if len(string) < 2:
return string.upper()
else:
return string[:1].upper() + string[1:] |
def new_balance(atype,bal,dr,cr):
"""compute the new balance after transaction"""
if atype in ("E","L","i"):
return bal+cr-dr
if atype in ("A","e"):
return bal+dr-cr
raise ValueError("Bad account type") |
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.rea... |
def list_of_langs(data):
"""Construct list of language codes from data."""
lang_codes = []
for lang_data in data:
lang_codes.append(lang_data.get('value'))
return lang_codes |
def _format_parser(x) -> list:
"""Utility parser formatter.
Parameters
----------
x
Unformated parsed list.
Returns
-------
:
Formatted parsed list.
"""
if isinstance(x, tuple):
return [x]
else:
return [a for item in x for a in _format_parser(ite... |
def epsilon(ab_eps, bb_eps):
""" Perform combining rule to get A+A epsilon parameter.
Output units are whatever those are of the input parameters.
:param ab_eps: A+B epsilon parameter
:type ab_eps: float
:param ab_eps: B+B epsilon parameter
:type ab_eps: float
:rtype... |
def _remove_nones(obj):
"""Return a new object ommitting keys whose value is none."""
return {key: value for key, value in obj.items() if value is not None} |
def compute_coupling_ratio(alphabet1, alphabet2):
"""
Compute the amount of coupling between two alphabets.
@param alphabet1: First alphabet.
@type alphabet1: C{set} of L{Event}
@param alphabet2: Second alphabet.
@type alphabet2: C{set} of L{Event}
@return: Amount of coupling.
@rtyp... |
def get_data(base_url):
"""
This just inserts a hardcoded introspection string for the baseurl.
"""
return [
{
"api_version": "v1",
"available_api_versions": {
"v1": base_url+"v1/",
},
"formats": [
"json",
],
"entry_types_by_format": {
"js... |
def get_duplicates(list_):
"""Returns the duplicates in a list l."""
seen = {}
duplicates = []
for x in list_:
if x not in seen:
seen[x] = 1
else:
if seen[x] == 1:
duplicates.append(x)
seen[x] += 1
return duplicates |
def CGx(N2, Omega, k, l, m, u, f):
"""
Horizontal group speed in x-direction in a flow
"""
# K2 = k**2 + l**2 + m**2
cgx = ((k * m**2 * (N2 - f**2))/((k**2 + l**2 + m**2)**2 * Omega)) + u
return cgx |
def trim_runtime(seconds: float) -> float:
"""Round seconds (float) to the nearest millisecond."""
return round(seconds, 3) |
def epsilon2(arg1, arg2=1000):
"""Do epsilon2
Usage:
>>> epsilon2(10, 20)
-20
>>> epsilon2(30)
-980
"""
return arg1 - arg2 - 10 |
def range_check(low, high):
"""\
Verifies that that given range has a low lower than the high.
>>> range_check(10, 11)
(10.0, 11.0)
>>> range_check(6.4, 30)
(6.4, 30.0)
>>> try:
... range_check(7, 2)
... except ValueError as e:
... print(e)
... |
def apply_mapping(row, mapping=None):
"""Apply the mapping to one row."""
if mapping:
for old, new in mapping:
row[new] = row.pop(old)
return row |
def get_models_from_body_message(body):
"""
Method to get model id, model blob id, model bucket from input rabbitmq
message.
:param body: rabbitmq message body
:type body: dict
:return: models ids, models blob ids, models, buckets
"""
model_id = []
models_blob_ids = []
models_b... |
def normalize_string(string):
"""Removes excess spaces from string.
Returns:
String without excess spaces.
"""
if not string:
return ''
return ' '.join(string.split()) |
def calculate_tensor_size_after_convs(input_size: int, sizes: list, strides: list):
"""helper method to calculate output size of an input into a conv net consisting of conv layers with filter `sizes`
and `strides`"""
t = input_size
for size, stride in zip(sizes, strides):
t = int((t - size) / s... |
def get_complement(sequence):
"""Get the complement of a `sequence` of nucleotides.
Returns a string with the complementary sequence of `sequence`.
If `sequence` is empty, an empty string is returned.
Examples
--------
>>> get_complement('AUGC')
'UACG'
"""
sequence_upper = se... |
def _select_features(example, feature_list=None):
"""Select a subset of features from the example dict."""
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list if f in example} |
def TransformSplit(r, sep='/', undefined=''):
"""Splits a string by the value of sep.
Args:
r: A string.
sep: The separator value to use when splitting.
undefined: Returns this value if the result after splitting is empty.
Returns:
A new array containing the split components of the resource.
... |
def load_marker(i):
"""
Provide marker via index
@param i: index
"""
markers = ["o", "v", "D", "s", "*", "d", "^", "x", "+"]
return markers[i % len(markers)] |
def isList( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'list'.
"""
return isinstance( obj, list ) |
def first(iterable, default=None, key=None):
"""
Return the first truthy value of an iterable.
Shamelessly stolen from https://github.com/hynek/first
"""
if key is None:
for el in iterable:
if el:
return el
else:
for el in iterable:
if key(... |
def client_scope(application, client_role):
"""
:return scope of policy for client role
"""
return {"client_roles": [{"name": client_role(), "client": application["client_id"]}]} |
def is_secure_port(port):
"""
Returns True if port is root-owned at *nix systems
"""
if port is not None:
return port < 1024
else:
return False |
def compute_all_multiples(of_number, below_number):
"""Compute all natural numbers, which are multiples of a natural number below a predefined number."""
# Register the list of said multiples.
multiples = []
for i in range(1, below_number):
if not i % of_number:
multiples.a... |
def is_recoverable_error(status_code: int) -> bool:
"""
True if the passed status_code hints at a recoverable server error. I.e. The same request might
be successful at a later point in time.
"""
if status_code < 400:
# Not an error, therefore not a retrieable error.
return Fa... |
def type_compliance(variable, *args):
""" Private: internal library function, not intended for public use. """
return_list = []
for arg in args:
if isinstance(variable, arg):
return_list.append(True)
else:
return_list.append(False)
return True if True in return_li... |
def dict_list_eq(l1, l2):
"""Compare to lists of dictionaries for equality.
"""
sorted_l1 = sorted(sorted(d.items()) for d in l1)
sorted_l2 = sorted(sorted(d.items()) for d in l2)
return sorted_l1 == sorted_l2 |
def split_num(num, n):
"""
Divide num into m=min(n, num) elements x_1, ...., x_n, where x_1, ..., x_n >= 1 and max_{i,j} |x_i - x_j| <= 1
"""
n = min(num, n)
min_steps = num // n
splits = []
for i in range(n):
if i < num - min_steps * n:
splits.append(min_steps + 1)
... |
def _get_integer(value):
"""Converts a string into an integer.
Args:
value: string to convert.
Returns:
value converted into an integer, or 0 if conversion is not possible.
"""
try:
return int(value)
except ValueError:
return 0 |
def binarySearch(numList, left, right, target):
"""
Binary search for the range of number found in the exponential search algorithm
:param left: the first number in the range of number
:param right: the last number in the range of number
:param numList: a list of number sorted in ascending order
... |
def RPL_ENDOFBANLIST(sender, receipient, message):
""" Reply Code 368 """
return "<" + sender + ">: " + message |
def u16leListToByteList(data):
"""Convert a halfword array into a byte array"""
byteData = []
for h in data:
byteData.extend([h & 0xff, (h >> 8) & 0xff])
return byteData |
def calc_emotion_feat(prev_emo, current_emo):
"""helper function to calculate the difference or the shift between two emotions"""
if prev_emo == current_emo:
return 0
else:
x = current_emo - prev_emo
return x |
def get_char_num(x):
"""
Convert signed integer to number in range 0 - 256
"""
return int((256+x)%256) |
def sizeof_address_blocks(blocks, usage):
"""return the consolidated size (offset == 0) for a list of address blocks"""
if blocks is None:
return 0
end = 0
for b in blocks:
if b.usage != usage:
continue
e = b.offset + b.size
if e > end:
end = e
# return the size
return end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.