content stringlengths 42 6.51k |
|---|
def cut(num):
"""
Shorten the format of a number to 2 decimal places plus exponent
@param num: the number to be shorten
"""
return "{0:.2e}".format(num) |
def get_span(start_ids, end_ids, with_prob=False):
"""
every id can only be used once
get span set from position start and end list
input: [1, 2, 10] [4, 12]
output: set((2, 4), (10, 12))
"""
if with_prob:
start_ids = sorted(start_ids, key=lambda x: x[0])
end_ids = sorted(end... |
def print_errors_result(result, verbose=False):
"""
"""
spacers = 4
if verbose:
print(f"\nTotal Stats\n{spacers*' '}max. err.: {result[0]:6.3f};")
print(f"{(spacers-2)*' '}c-avg. err.: {result[1]:6.3f};")
print(f"{(spacers-2)*' '}t-avg. err.: {result[2]:6.3f}")
r... |
def alpha_rate(iteration):
"""
alpha learning rate
:param iteration: the count of iteration
:return: alpha
"""
return 150/(300 + iteration) |
def is_ignored(path):
"""checks if file has non-code-file extension"""
ignore_ext = ['.json', '.md', '.ps', '.eps', '.txt', '.xml', '.xsl',
'.rss', '.xslt', '.xsd', '.wsdl', '.wsf', '.yaml', '.yml',
'~', '#']
for ext in ignore_ext:
l = len(ext)
if path[-l:... |
def rev_bits(x: int, width: int = 0) -> int:
"""Return the given integer but with the bits reversed.
Params:
x - integer to reverse
width - width of the integer (in bits)
Returns:
The reversed integer.
"""
if not width:
width = x.bit_length()
rev = 0
f... |
def pf_mobility(phi, gamma):
""" Phase field mobility function. """
# return gamma * (phi**2-1.)**2
# func = 1.-phi**2
# return 0.75 * gamma * max_value(func, 0.)
return gamma |
def string_ijk1_for_cell_kji0(cell_kji0):
"""Returns a string showing indices for a cell in simulator protocol, from data in python protocol."""
return '[{:}, {:}, {:}]'.format(cell_kji0[2]+1, cell_kji0[1]+1, cell_kji0[0]+1) |
def find_nearest_index(data, value):
"""Find the index of the entry in data that is closest to value.
Example:
>>> data = [0, 3, 5, -2]
>>> i = partmc.find_nearest_index(data, 3.4)
returns i = 1
"""
min_diff = abs(value - data[0])
min_i = 0
for i in range(1,len(data)):
diff... |
def isConfigException(exception):
"""This method tries to check if the Exception was raised by the local API code (mostly while reading configuration)"""
errorList = [ValueError, KeyError, FileNotFoundError]
if type(exception) in errorList:
return True
else:
return False |
def unwrap(runner):
"""
Unwraps all delegators until the actual runner.
:param runner: An arbitrarily nested chain of delegators around a runner.
:return: The innermost runner.
"""
delegate = getattr(runner, "delegate", None)
if delegate:
return unwrap(delegate)
else:
re... |
def asset_table_aoi(gee_dir):
"""return the aoi for the reclassify tests available in our test account"""
return f"{gee_dir}/reclassify_table_aoi" |
def is_valid(s):
"""
Using a conventional stack struct, validate
strings in the form "({[]})" by:
1. pushing all openning chars: '(','{' and '[', sequentially.
2. when a closing character like ')', '}' and '] is found
we pop the last opening char pushed into stack
3. check if popped char... |
def get_num_classes(dataset: str):
"""Return the number of classes in the dataset. """
if dataset == "imagenet":
return 1000
elif dataset == "cifar10":
return 10 |
def _get_subnet_id(connection, subnet_name):
"""
:param connection:
:param subnet_name:
:return:
"""
if not subnet_name:
print("WARNING: No subnet was specified.")
return
# Try by name
subnets = connection.describe_subnets(
Filters=[{'Name': 'tag:Name', 'Values'... |
def _mysql_aes_key(key):
"""Format key."""
final_key = bytearray(16)
for i, c in enumerate(key):
final_key[i % 16] ^= key[i]
return bytes(final_key) |
def try_dict(value):
"""Try converting objects first to dict, then to str so we can easily compare them against JSON."""
try:
return dict(value)
except (ValueError, TypeError):
return str(value) |
def word_combine(x):
""" Returns a string that combines a list of words with proper commas and trailing 'and' """
num_words = len(x)
if num_words == 1: return x[0]
combined = ""
i = 1
for item in x:
if i == num_words:
combined += "and " + item
break
if (... |
def checksum(code):
"""Given a byte number expressed in hex ASCII, find mod-256 8-bit checksum."""
return sum(code) % 256 |
def stepx(x, steps, total, margin):
"""Return slices with and without interpolation between batches.
"""
start = 0 if x - margin <= 0 else x - margin
end = total if steps + x + margin >= total else steps + x + margin
#end = end if start > 0 else end + margin
Interpolated = slice(start, end)
... |
def definition_updated_message(payload):
"""
Build a Slack notification about an updated definition.
"""
definition_url = payload['definition']['url']
definition_name = payload['definition']['name']
message = 'The <{}|{}> definition was just updated.'
message = message.format(definition_ur... |
def intify(i):
"""If i is a long, cast to an int while preserving the bits"""
if 0x80000000 & i:
return int((0xFFFFFFFF & i))
return i |
def single_link(first_clustering, second_clustering, distance_function):
"""
Finds the smallest distance between any two points in the two given clusters
:param first_clustering: a set of points
:param second_clustering: a set of points
:param distance_function: a function that compares two points
... |
def StringsExcludeSubstrings(strings, substrings):
"""Returns true if all strings do not contain any substring.
Args:
strings: List of strings to search for substrings in.
substrings: List of strings to find in `strings`.
Returns:
True if every substring is not contained in any string.
"""
for s... |
def shannon(data):
""" Given a hash { 'species': count } , returns the SDI
>>> sdi({'a': 10, 'b': 20, 'c': 30,})
1.0114042647073518"""
from math import log as ln
def p(n, N):
""" Relative abundance """
if n is 0:
return 0
else:
... |
def getid(obj):
"""Get obj's uuid or object itself if no uuid
Abstracts the common pattern of allowing both an object or
an object's ID (UUID) as a parameter when dealing with relationships.
"""
try:
return obj.uuid
except AttributeError:
return obj |
def BackslashEscape(s, meta_chars):
"""Escaped certain characters with backslashes.
Used for shell syntax (i.e. quoting completed filenames), globs, and EREs.
"""
escaped = []
for c in s:
if c in meta_chars:
escaped.append('\\')
escaped.append(c)
return ''.join(escaped) |
def name_without_commas(name):
"""
Takes a name formatted as "[LastNames], [FirstNames]"
and returns it formatted as "[FirstNames] [LastNames]".
If a name without commas is passed it is returned unchanged.
"""
if name and "," in name:
name_parts = name.split(",")
if len(name_pa... |
def new_sleep_data_serie(startdate, enddate, state):
"""Create simple dict to simulate api data."""
return {"startdate": startdate, "enddate": enddate, "state": state} |
def _remove_parenthesis(word):
"""
Examples
--------
>>> _remove_parenthesis('(ROMS)')
'ROMS'
"""
try:
return word[word.index("(") + 1 : word.rindex(")")]
except ValueError:
return word |
def is_santas_turn(turn):
"""Check if the given turn corresponds to Santa."""
return turn % 2 == 0 |
def get_id_prefix(id_prefix=1, proxmox_node_scale=3, node=None):
"""
Default prefix if node name has no number, is 1.
"""
if not node:
return id_prefix
for i in range(1, proxmox_node_scale + 1):
if str(i) in node:
return i
return id_prefix |
def to_unicode(value):
"""
Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
try:
if isinstance(value, (str, type(None))):
return value... |
def tuple_split(string):
"""
Split a string into a list of tuple values
from utils.tools import tuple_split
print tuple_split('')
#[]
print tuple_split('3')
#[3]
print tuple_split('3,4')
#[(3, 4)]
print tuple_split('3,5 6,1 4,2')
#[(3, 5), (6, 1), (4, 2)]
"""
values ... |
def url_feed_prob(url):
"""
This method gets a url and calculateds the probability of it leading to a rss feed
:param url: str
:return: int
"""
if "comments" in url:
return -2
if "georss" in url:
return -1
kw = ["atom", "rss", "rdf", ".xml", "feed"]
for p, t in zip(ra... |
def dot(u, v):
"""
Dot product of 2 N dimensional vectors.
"""
s = 0
for i in range(0, len(u)):
s += u[i] * v[i]
return s |
def split(container, count):
"""
Simple function splitting a container into equal length chunks.
Order is not preserved but this is potentially an advantage depending on
the use case.
"""
return [container[_i::count] for _i in range(count)] |
def convert_truelike_to_bool(input_item, convert_int=False, convert_float=False, convert_nontrue=False):
"""Converts true-like values ("true", 1, True", "WAHR", etc) to python boolean True.
Parameters
----------
input_item : string or int
Item to be converted to bool (e.g. "true", 1, "WAHR" or ... |
def redis_stream_id_subtract_one(message_id):
"""Subtract one from the message ID
This is useful when we need to xread() events inclusive of the given ID,
rather than exclusive of the given ID (which is the sensible default).
Only use when one can tolerate an exceptionally slim risk of grabbing extra e... |
def rectanglesOverlap(r1, r2):
"""Check whether r1 and r2 overlap."""
if ((r1[0] >= r2[0] + r2[2]) or (r1[0] + r1[2] <= r2[0])
or (r1[1] + r1[3] <= r2[1]) or (r1[1] >= r2[1] + r2[3])):
return False
else:
return True |
def add_s8(x, y):
"""Add two 8-bit integers stored in two's complement."""
return (x + y) & 0xff |
def get_job_type_from_image(image_uri):
"""
Return the Job type from the image tag.
:param image_uri: ECR image URI
:return: Job Type
"""
tested_job_type = None
allowed_job_types = ("training", "inference")
for job_type in allowed_job_types:
if job_type in image_uri:
... |
def quote_it(s):
"""Return the argument quoted, suitable for a quoted-string"""
return '"%s"' % (s.replace("\\","\\\\").replace('"','\\"')) |
def text_presence(job_desc, lan_list):
"""
Parameters
----------
job_desc : str
Job Description.
lan_list : list
List of languages.
Returns
-------
dic : dictionary
Dictionary of if each language was in description.
"""
dic = {}
for langua... |
def initialize_dataset(input_data):
""" Input dictionary should be of the form created by parse_star_file function. Returns a new dictionary of the form:
{ 'class001.mrc' : [ (%_it1, %_it2, ...), (res_it1, res_it2, ...), (iteration value1, ...) ] }
"""
new_dictionary = {}
for entry in input_... |
def _equal_room_tp(room, target):
"""
NOTE: Ensure <target> is always from <ALLOWED_TARGET_ROOM_TYPES>!!!!
DO NOT swap the order of arguments
"""
room = room.lower()
target = target.lower()
return (room == target) or \
((target == 'bathroom') and (room == 'toilet')) or \
... |
def get_result_or_same_in_list(function, value):
"""
Return the result if True or the value within a list.
Applies `function` to `value` and returns its result if it evaluates
to True. Otherwise, return the value within a list.
`function` should receive a single argument, the `value`.
"""
... |
def lr_policy(initial_lr, step, N):
"""
learning rate decay
Args:
initial_lr: base learning rate
step: current iteration number
N: total number of iterations over which learning rate is decayed
"""
min_lr = 0.00001
res = initial_lr * ((N - step) / N) ** 2
return max(r... |
def url_joiner(url, path, trailing=None):
"""Join to sections for a URL and add proper forward slashes"""
url_link = "/".join(s.strip("/") for s in [url, path])
if trailing:
url_link += "/"
return url_link |
def valid_ecl(ecl):
"""ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth."""
valid = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
if ecl in valid:
return True
else:
return False |
def scrub_keys(key):
"""Replace periods (restricted by Mongo) with underscores."""
return '_'.join(key.split('.')) |
def robot_angle_to_mount_angle(robot_angle, mount_zero=90):
"""Convert a robot angle to the corresponding mount angle.
Args:
robot_angle - the commanded direction relative to the robot's centerline
mount_zero - the direction, relative to the robot's centerline, that the
mount points when the mount is commanded t... |
def get_tags_from_image_ids(image_ids: list=[]):
"""
Get the tags for the given image_ids
Note that nulls and 'latest' is ignored
:param image_ids:
:return:
"""
tags = []
for image in image_ids:
if ('imageTag') in image:
tag = image['imageTag']
if (tag is... |
def factors(n):
"""
factors(n: int) -> tuple
Expects int, prime or composite
returns a tuple with all prime factors, also 1, and -1 if negative
"""
if not isinstance(n, int): # gotta be int
raise ValueError
if n == 0:
return (0,)
found = [1] # always
if n < 0:
... |
def part2(data):
"""Solve part 2"""
horizontalPos = 0
depth = 0
aim = 0
for command, val in data:
if(command=="forward"):
horizontalPos += int(val)
depth += (aim * int(val))
elif(command=="up"):
aim -= int(val)
elif(command=="down"):
... |
def _no_schultz_repetition(contour, allow_unflagged=False):
"""
Step 10. If all values are flagged and no more than one repetition of values exists, excluding
the first and last values, returns True.
>>> contour_with_extrema = [
... [1, {-1, 1}],
... [0, {-1}],
... [2, {1}],
... [0, {-1}],
... [2, {1}],
... |
def hash_algorithm(hash_string):
"""
Parse the name of the hash method from the hash string.
The hash string should have the following form ``algorithm:hash``, where
algorithm can be the name of any algorithm known to :mod:`hashlib`.
If the algorithm is omitted or the hash string is None, will def... |
def deduplicate(seq):
"""Remove duplicates from list/array while preserving order."""
seen = set()
seen_add = seen.add # For efficiency due to dynamic typing
return [e for e in seq if not (e in seen or seen_add(e))] |
def recommend_random(query, k=10):
"""
Recommends a list of k random movie ids
"""
return [1, 20, 34, 25] |
def get_parsec_params_bounds(xte):
"""
get a dictionary of (lower, upper) bounds pair for parsec parameters
:param xte:
:return:
"""
eps_zero = 1e-6
# eps_inf = np.inf
eps_inf = 1e5
parsec_params_bounds = dict()
parsec_params_bounds["rle"] = (eps_zero, eps_inf)
parsec_params_... |
def compute_size_by_dict(indices, idx_dict):
"""
Computes the product of the elements in indices based on the dictionary
idx_dict.
Parameters
----------
indices : iterable
Indices to base the product on.
idx_dict : dictionary
Dictionary of index _sizes
Returns
-----... |
def sample_width_to_string(sample_width):
"""Convert sample width (bytes) to ALSA format string."""
return {1: 's8', 2: 's16', 4: 's32'}.get(sample_width, None) |
def get_lists_of_predictions(lis, predictor):
"""
n = len(lis)
this function return n-1 lists
such that the i'th list is a predicted list, which has length n (the same length as lis)
which was predicted from the first i + 1 element in lis
:param lis:
:param predictor:
:return:
"""
... |
def _find_location(block, directive_name, match_func=None):
"""Finds the index of the first instance of directive_name in block.
If no line exists, use None."""
return next((index for index, line in enumerate(block) \
if line and line[0] == directive_name and (match_func is None or match_func(lin... |
def _replace_dmaap_template(dmaap, template_identifier):
"""
This one liner could have been just put inline in the caller but maybe this will get more complex in future
Talked to Mike, default value if key is not found in dmaap key should be {}
"""
return {} if (template_identifier not in dmaap or t... |
def findFirstObject(name, dic, rootMode=False):
"""find the first object from the dict"""
if isinstance(dic, dict):
for key in dic.keys():
temp = dic[key]
# check if this is the object we want
if name == key:
if rootMode is True:
re... |
def binom(n, k):
"""
Returns the binomial coefficient (n, k).
Program uses a dynamic programming approach.
"""
coeff = {}
for i in range(n + 1):
coeff[i] = {}
coeff[i][0] = 1
for j in range(k + 1):
coeff[j][j] = 1
for i in range(1, n + 1):
for j in rang... |
def countSetBits(n):
"""Counts the number of bits that are set to 1 in a given integer."""
count = 0
while (n):
count += n & 1
n >>= 1
return count |
def calc_iou(dim: int):
"""
Calculates IoU for two boxes that intersects "querterly" (see ASCII image) in R^dim
x: dimension
"""
I = 0.5**dim
U = 2 - I
return I/U |
def clean_dev(text):
"""clean developer text, using specific rules"""
text = text.replace("Additional work by:", "")
return text |
def dp_edit_distance(str1, str2):
"""
Finds the minimum edit displace between
two strings
I use 1
"""
n = len(str1)
m = len(str2)
optimal_edit_distances = {}
i = n - 1
j = m - 1
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
if str1[i] == str2[j]:
if i == n - 1 a... |
def sum67(nums):
"""Solution to the problem described in http://codingbat.com/prob/p108886
Ex:
>>> sum67([1, 2, 2])
5
>>> sum67([1, 2, 2, 6, 99, 99, 7])
5
>>> sum67([1, 1, 6, 7, 2])
4
:param nums: list
:return: int
"""
sum = 0
between_6_and_7 = False
for n in n... |
def maybe_encode(value):
"""If the value passed in is a str, encode it as UTF-8 bytes for Python 3
:param str|bytes value: The value to maybe encode
:rtype: bytes
"""
try:
return value.encode('utf-8')
except AttributeError:
return value |
def jwt_type_str(repo_type):
"""Return valid JWT type string for given cluster type
Arguments:
repo_type (bool): True/False, depending on wheter it is an EE cluster
or not.
Returns:
String denoting JWT type string.
"""
if repo_type:
return 'RS256'
else:
... |
def wind_direction(degrees):
""" Convert wind degrees to direction """
try:
degrees = int(degrees)
except ValueError:
return ''
if degrees < 23 or degrees >= 338:
return 'N'
elif degrees < 68:
return 'NE'
elif degrees < 113:
return 'E'
... |
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet ... |
def mds_lon_to_xindex(lon, res=1.0):
"""
For a given longitude return the x-index as it was in MDS2/3 in a 1x1 global grid
:param lon: Longitude of the point
:param res: resolution of the field
:type lon: float
:type res: float
:return: grid box index
:rtype: integer
In the... |
def getCoords(vts):
""" Get coordinates of vortices in x, y, z form """
coords = [[], [], []]
for vt in vts:
coords = vt.appCoords(coords)
return coords |
def get_singular_root(check_word, new_word, keywords):
"""
replaces string with a new string if == check_word
"""
if check_word in keywords:
newlist=[x for x in keywords if x != check_word]
newlist.append(new_word)
return newlist
else:
return keywords |
def getOneAfterSpace(string):
"""returns next character after a space in given string
(Helper for countInitials)"""
result = ''
reachedSpace = False
for i in range(len(string)):
if string[i] == ' ':
return string[i+1]
return '' |
def fetch_licenses(fw_conn):
"""Fetch Licenses
Args:
fw_conn (PanDevice): A panos object for device
"""
try:
fw_conn.fetch_licenses_from_license_server()
print('Licenses retrieved from Palo Alto Networks')
return True
except:
print('WARNING: Not able to retri... |
def construct_email(cfg, query, location, posts):
"""Construct an email message.
Args:
cfg: email configuration.
query: search term used.
location: location to search for jobs.
posts: dictionary containing new job listings.
Returns:
message: string containing the em... |
def __exclude_zero(data, labels, delta=0.1):
"""Exclude values <= delta from data and labels
"""
d = []
l = []
for i, x in enumerate(data):
if x > delta:
d.append(x)
l.append(labels[i])
return (d, l) |
def to_locale(language):
"""
Turns a language name (en-us) into a locale name (en_US).
Logic is derived from Django so be careful about changing it.
"""
p = language.find("-")
if p >= 0:
if len(language[p + 1 :]) > 2:
return "{}_{}".format(
language[:p].lower(... |
def _subs(count: int, what: str) -> str:
"""DRY."""
return f'{count} validation error{"" if count == 1 else "s"} for {what}' |
def groupfinder(userid, request):
"""
Default groupfinder implementaion for pyramid applications
:param userid:
:param request:
:return:
"""
if userid and hasattr(request, "user") and request.user:
groups = ["group:%s" % g.id for g in request.user.groups]
return groups
r... |
def depth(t):
"""
Returns the depth of the tree
"""
if t == None:
return -1
return max(depth(t.left)+1, depth(t.right)+1) |
def lcs(X: str, Y: str, m: int, n: int) -> str:
"""
Returns the longest common subtring in X and Y
>>> lcs('ancsfg', 'sfac', 6, 4)
'The longest common substring is sf'
>>> lcs('zxcvbn', 'qwerthj', 6, 7)
'There is no common substring in zxcvbn and qwerthj'
>>> lcs('adgjk', 'jkfhda', 5,... |
def filter_nin(value):
"""
:param value: dict
:return: list
This function will compile a users verified NINs to a list of strings.
"""
result = []
for item in value:
verified = item.get('verfied', False)
if verified and type(verified) == bool: # Be sure that it's not someth... |
def _min(*args):
"""Returns the smallest non-negative argument."""
args = [x for x in args if x > -1]
if args:
return min(args)
else:
return -1 |
def get_unlabelled(cluster):
"""
Return the value contained in the key "unlabelled_files"
"""
return cluster['unlabelled_files'] |
def write_vashishta_potential(parameters):
"""Write vashishta potential file from parameters
Parameters
----------
parameters: dict
keys are tuple of elements with the values being the parameters length 14
"""
lines = []
for (e1, e2, e3), params in parameters.items():
if ... |
def get_locale_identifier(tup, sep='_'):
"""The reverse of :func:`parse_locale`. It creates a locale identifier out
of a ``(language, territory, script, variant)`` tuple. Items can be set to
``None`` and trailing ``None``\s can also be left out of the tuple.
>>> get_locale_identifier(('de', 'DE'... |
def rreplace(string: str, old: str, new: str, count: int = 0) -> str:
"""
Return a copy of string with all occurences of substring
old replace by new starting from the right. If the optional
argument count is given only the first count occurences are
replaced.
"""
reverse = string[::-1]
... |
def range_overlap(a_min, a_max, b_min, b_max):
"""Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max) |
def to_ea(seg, off):
"""
Return value of expression: ((seg<<4) + off)
"""
return (seg << 4) + off |
def to_bool(s, fallback=None):
"""
:param str s: str to be converted to bool, e.g. "1", "0", "true", "false"
:param T fallback: if s is not recognized as a bool
:return: boolean value, or fallback
:rtype: bool|T
"""
if not s:
return fallback
s = s.lower()
if s in ["1", "true"... |
def crc16_ccitt(crc, data):
"""
https://stackoverflow.com/a/30357446
"""
msb = crc >> 8
lsb = crc & 255
x = data ^ msb
x ^= (x >> 4)
msb = (lsb ^ (x >> 3) ^ (x << 4)) & 255
lsb = (x ^ (x << 5)) & 255
return (msb << 8) + lsb |
def __overwriteIfSet(overwriteable, overwriter):
"""
Returns overwriteable if overwriter is set, overwriteable otherwise
\nin:
overwriteable=object
overwriter=object
\nout:
overwriter if not None else overwriteable
"""
return overwriteable if overwriter is None el... |
def _get_fk_relations_helper(unvisited_tables, visited_tables,
fk_relations_map):
"""Returns a ForeignKeyRelation connecting to an unvisited table, or None."""
for table_to_visit in unvisited_tables:
for table in visited_tables:
if (table, table_to_visit) in fk_relations_map:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.