content stringlengths 42 6.51k |
|---|
def helper(n, order, current_max):
"""
This function help find the biggest digit.
:param n: the input integer
:param order: the number of digits
:param current_max: the currently biggest digit
:return: the biggest digit
"""
# +-(0~9)
if order == 0:
return int(current_max)
# +-(10~99999)
else:
# Get digit... |
def parse_int_list(range_string, delim=',', range_delim='-'):
"""Returns a sorted list of positive integers based on
*range_string*. Reverse of :func:`format_int_list`.
Args:
range_string (str): String of comma separated positive
integers or ranges (e.g. '1,2,4-6,8'). Typical of a custo... |
def luminosidad_solar_a_vatios(Lsol):
"""
se ingresa el valor en luminosidades solares, y se convierte en vatios
"""
vatios=Lsol*3.827e26
return vatios |
def makeQuery(kwargs):
"""
Make query element of URI from a supplied dictionary
"""
return (kwargs and "?"+"&".join([ k+"="+v for (k,v) in kwargs.iteritems()])) or "" |
def is_num_or_str(value):
"""
Check if a var is numeric(int, float) or string
:param value:
:return:
"""
return isinstance(value, (int, float, str)) |
def rotate_y(x, z, cosangle, sinangle):
"""3D rotaion around *y* (roll). *x* and *z* are values or arrays.
Positive rotation is for positive *sinangle*. Returns *xNew, zNew*."""
return cosangle*x + sinangle*z, -sinangle*x + cosangle*z |
def new(size, value=None):
""" Initialize a new square matrix. """
return [[value] * size for _ in range(size)] |
def convert_field_format(fieldAsArray):
"""
Description:
converts the polygon given as nested arrays
to nested tuples.
Parameters:
fieldAsArray: [ [ [x, y], ... ], ... ]
Return:
( ( (x, y), ... ), ... )
"""
return tuple( tuple( tuple(vertex) for vertex in ring) fo... |
def is_valid(exp: str) -> bool:
"""Validate if expression is a valid identifier.
Args:
exp: string to be validated
Returns:
True: if is a valid identifier.
False: if is not a valid identifier.
"""
if not isinstance(exp, str):
return False
length = len(exp)
... |
def descendant(elem, parent):
"""
return True if elem is some descendent of a parent data object
"""
return elem is parent or elem in parent.iterdescendants() |
def cbmc_text_program(log_section):
"""Find program in cbmc text output"""
for line in log_section:
if line.startswith('CBMC version'):
return line
return None |
def UC_Cinv(C_mgl, A_catch):
""" Convert concentration from units of mg/l to kg/mm
Args:
C_mgl: Float. Concentration in mg/l
A_catch: Float. Catchment area in km2
Returns:
Float. Concentration in kg/mm
"""
C_kgmm = C_mgl*A_catch
return C_kgmm |
def _map_range(value, in_min, in_max, out_min, out_max):
"""Map an integer value from a range into a value in another range."""
result = (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
return int(result) |
def fibonacci(number):
"""
Recursive implementation of fibonacci function
Args:
number: number in fibonacci sequence
Returns:
fibonacci number
Examples:
>>> fibonacci_recursive(20)
6765
"""
if number <= 1:
return number
return fibonacci(number... |
def get_upstream(version_str):
"""Given a version string that could potentially contain both an upstream
revision and a debian revision, return a tuple of both. If there is no
debian revision, return 0 as the second tuple element."""
try:
d_index = version_str.rindex('-')
except ValueError:... |
def is_swap(score0, score1):
"""Returns whether the last two digits of SCORE0 and SCORE1 are reversed
versions of each other, such as 19 and 91 and 2 and 20
"""
# BEGIN Question 4
last0, last1 = score0 % 100, score1 % 100
if last0 < last1:
return is_swap(last1, last0)
rev = 0
whi... |
def get_snapshot_with_keys(snapshots, keys):
""" Return the first snapshot that with the given subset of keys"""
sk = set(keys)
for s in snapshots:
if (sk.issubset(set(s.keys()))):
return s
return None |
def monomial_lcm(A, B):
"""Least common multiple of tuples representing monomials.
Lets compute LCM of `x**3*y**4*z` and `x*y**2`::
>>> from sympy.polys.monomialtools import monomial_lcm
>>> monomial_lcm((3, 4, 1), (1, 2, 0))
(3, 4, 1)
which gives `x**3*y**4*z`.
... |
def common_start(stringList):
"""RETURNS: common string that all strings start with in 'stringList'.
"""
if not stringList:
return ""
stringList.sort(key=lambda x: len(x))
result = stringList[0]
rangeL = range(len(result))
for string in stringList[1:]:
if string.startswith(r... |
def get_ordered_values_from_table_by_key(table, reverse=False):
"""
Get value list where the value orders are determined by their keys.
Args:
table: a table of data
reverse: value list in a reversed order
Returns:
- an ordered list of values
"""
keys = [_ for _ in table... |
def build_dataset_values(claim_object, data_value):
""" Build results with different datasets.
Parameters:
claim_object (obj): Onject to modify and add to rows .
data_value (obj): result object
Returns:
Modified claim_boject according to data_value.type
"""
... |
def seconds_to_hms(seconds: int) -> str:
"""
Returns string like "23:01:59" or "297:59:03" from seconds.
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d}" |
def get_hosts_info(res):
"""
This function returns the hostname, cup utilization and memory utilization for all active hosts.
:param res:
:return: macroservice information of hosts.
"""
hosts_info = []
for host in res:
host_info = {'name': host['key'], 'cpu': 1 - float(host['1']['val... |
def insetRect(rect, dx, dy):
"""Inset the rectangle by dx, dy on all sides."""
(xMin, yMin, xMax, yMax) = rect
return xMin+dx, yMin+dy, xMax-dx, yMax-dy |
def s3_bucket_location_constraint(region):
"""Returns the appropriate LocationConstraint info for a new S3 bucket.
When creating a bucket in a region OTHER than us-east-1, you need to
specify a LocationConstraint inside the CreateBucketConfiguration argument.
This function helps you determine the right... |
def str_join(tokens):
"""Join tokens into a long string"""
return ' '.join(tokens) |
def cleanup_value(value):
"""Try and convert the given value to a float."""
value = value.strip()
try:
return float(value)
except Exception:
return value |
def serialize_config( config_data ):
"""
Generate a .ini-formatted configuration string to e.g. save to disk.
"""
return "[syndicate]\n" + "\n".join( ["%s=%s" % (config_key, config_value) for (config_key, config_value) in config_data.items()] ) |
def get_query_types(query_list):
"""
This function is used to parse the query_ticket_grouping_types string from the app.config
:param query_list: the string to parse into ticketType groupingType pairs for querying Securework ticket endpoint
:return: List of json objects. Each json entry is a ticketType... |
def _IsBoundary(i, n, cont, assigned):
"""Is path i a boundary, given current assignment?
Args:
i: int - index of a path to test for boundary possiblity
n: int - total number of paths
cont: dict - maps path pairs (i,j) to _Contains(i,j,...) result
assigned: set of int - which paths are... |
def strip_markup(names, defaults):
"""strip markup ('!') from function argument names and defaults"""
names = tuple(i.strip('!') for i in names)
defaults = dict((k,v) for (k,v) in defaults.items() if not k.startswith('!'))
return names, defaults |
def title_parser(line, method='full'):
"""
Take an MGF TITLE line and return the spectrum title.
Depending on the software tool that was used to write the MGF files and the
search engine, we need to extract different parts of the TITLE field. E.g,
for MaxQuant, everything up until the first space i... |
def create_category_index(categories):
"""Creates dictionary of COCO compatible categories keyed by category id.
Args:
categories: a list of dicts, each of which has the following keys:
'id': (required) an integer id uniquely identifying this category.
'name': (required) string representi... |
def base2int(inp: str, alphabet: str) -> int:
"""\
Convert an string representation to its integer in a given base(length of alphabet)
:param inp: input string to conversion
:param alphabet: alphabet to conversion
:return:
"""
assert isinstance(inp, str), "`input` must be `str`!"
asser... |
def __decode_string(b, start=0):
"""
>>> __decode_string(b'3:foo3:bar')
{'value': 'foo', 'start': 5}
>>> __decode_string(b'3:foo3:bar', start=5)
{'value': 'bar', 'start': 10}
>>> __decode_string(b'0:3:bar')
{'value': '', 'start': 2}
"""
cpos = b.find(b':', start)
if cpos == -1:
... |
def geometry_check(meta):
""" Some of tiles located in latitude band of N (MGRS) have an
incorrect data gometery in the original metadata files. This function flag these tiles
so they are download and correct geometry is extracted for them using sentine-s3 lib """
try:
if meta['latitude_band'] ... |
def summarize_exit_codes(exit_codes):
"""
Take a list of exit codes, if at least one of them is not 0, then return
that number.
"""
for ec in exit_codes:
if ec != 0:
return ec
return 0 |
def indirect_lookup(d, key, max_iterations=10):
"""
Perform a lookup of a *key* in a dictionary *d*,
but also check if there is a key corresponding to
the retrieved value, and, if so, return the
value associated with this key (and so on,
creating a chain of lookups)
"""
# A recursive sol... |
def remove_crud(string):
"""Return string without useless information.
Return string with trailing zeros after a decimal place, trailing
decimal points, and leading and trailing spaces removed.
"""
if "." in string:
string = string.rstrip('0')
string = string.lstrip('0 ')
... |
def solution(array, n_rotations):
"""
Returns the Cyclic Rotation of array with n_rotations positions to the right.
"""
n = len(array)
n_rotations = n_rotations % n if n > 0 else 0
return array[n - n_rotations:] + array[:n - n_rotations] |
def api_symbol_groups(sec_dict):
"""Groups symbols in sec_dict into lists of 100 and returns list of lists."""
symbols = list(sec_dict.keys())
sym_groups = []
count = 0
temp_list = []
for sym in symbols:
temp_list.append(sym)
count += 1
if count % 100 == 0:
sy... |
def damerau_levenshtein_distance_naive(x :str, y :str) -> int:
"""
Inefficient implementation of the Damerau Levenshtein distance (no memoization).
Args:
x: A `str` instance.
y: A `str` instance.
Returns:
The minimal number of insertion/deletion/substitution operations needed to
... |
def assign_sequential_names(ignored, num_seqs, base_name="seq", start_at=0):
"""Returns list of num_seqs sequential, unique names.
First argument is ignored; expect this to be set as a class attribute.
"""
return ["%s_%s" % (base_name, i) for i in range(start_at, start_at + num_seqs)] |
def mk_basic_call(row, score_cols):
"""Call is pathogenic/1 if all scores are met"""
cutoffs = {'is_domain':1, 'mpc':2, 'revel':.375, 'ccr':90}
for col in score_cols:
if row[col] < cutoffs[col]:
return 0
return 1 |
def parse_bool(inpar):
"""
convert CLI True or False string into boolean
:param inpar: input True or False string (True/False or T/F)
:return: outpar (bool)
"""
import sys
msg = 'ERROR [parse_cli] CLI must be either True/False. ' \
'Exiting script...'
try:
if inpar.lo... |
def _is_valid_glob(glob):
"""Check whether a glob pattern is valid.
It does so by making sure it has no dots (path separator) inside groups,
and that the grouping braces are not mismatched. This helps doing useless
(or worse, wrong) work on queries.
Args:
glob: Graphite glob pattern.
Re... |
def get_kernel_hyperparams(kernel_type):
""" Returns the kernel hyperparams for the unit-tests below. """
kernel_hyperparams = {}
kernel_hyperparams["cont_par"] = 2.0
kernel_hyperparams["int_par"] = 3
return kernel_hyperparams |
def normalize_multiline(line):
"""Normalize multiline-related code that will cause syntax error.
This is for purposes of checking syntax.
"""
if line.startswith('def ') and line.rstrip().endswith(':'):
return line + ' pass'
elif line.startswith('return '):
return 'def _(): ' + line... |
def _colorize(text, color):
"""Applies ANSI color codes around the given text."""
return "\033[1;{color}m{text}{reset}".format(
color = color,
reset = "\033[0m",
text = text,
) |
def exactly_one_topping(ketchup, mustard, onion):
"""Return whether the customer wants exactly one of the three available toppings
on their hot dog.
"""
return True if int(ketchup) + int(mustard) + int(onion) == 1 else False |
def to_zero_one(a):
"""
translate to 0 1
"""
return a/2+0.5 |
def generate_query(schema):
"""
Generate a create schema query
:param schema: The schema object
:return: The create schema string
"""
q = None
if schema:
q = "CREATE SCHEMA"
if schema.if_not_exists:
q = "{} IF NOT EXISTS".format(q)
if schema.name:
... |
def is_prime(n):
"""
Return a boolean value based upon
whether the argument n is a prime number.
"""
if n < 2:
return False
if n == 2:
return True
for m in range(2, int(n ** 0.5) + 1):
if (n % m) == 0:
return False
else:
return True |
def format_alternative(account):
"""format and print the data
Args:
account (list): [a list with the account informations]
Returns:
[string]: [return the alternative line]
"""
name = account["name"]
description = account["description"]
country = account["country"]
ret... |
def accession_table(report, headers, rows):
"""Returns an HTML table."""
return {'report': report,
'headers': headers,
'rows': rows} |
def _line_y(line, x):
"""Return the y value at which the `line` crosses the vertical line at `x`."""
p1 = line[0]
p2 = line[1]
if p2[0] == p1[0]:
if p1[0] == x:
return p1[1]
return None
m = (p2[1] - p1[1]) / (p2[0] - p1[0])
y = p1[1] + m * (x - p1[0])
return y |
def _clean_query_string(q):
"""Clean up a query string for searching.
Removes unmatched parentheses and joining operators.
Arguments:
q (str): Query string to be cleaned
Returns:
str: The clean query string.
"""
q = q.replace("()", "").strip()
if q.endswith("("):
q... |
def get_fitness(cell_type,cell_neighbour_types,DELTA,game,game_params):
"""returns fitness of single cell"""
return 1+DELTA*game(cell_type,cell_neighbour_types,*game_params) |
def find_descriptor(cls, attrname):
"""Find the descriptor of an attribute."""
def hasspecialmethod(obj, name):
return any(name in klass.__dict__ for klass in type(obj).__mro__)
for klass in cls.__mro__:
if attrname in klass.__dict__:
descriptor = klass.__dict__[attrname]
... |
def member_joined_organization_message(payload):
"""
Build a Slack message informing about a new member.
"""
member_name = payload['user']['name']
member_url = payload['user']['url']
org_name = payload['organization']['name']
org_url = payload['organization']['url']
message = 'Say hi! ... |
def guess_shape_and_submatrix_shape(dic):
"""
Guess the data shape and the shape of the processed data submatrix.
"""
if 'procs' not in dic: # unknow dimensionality and shapes
return None, None
procs = dic['procs']
if 'SI' not in procs or 'XDIM' not in procs:
return None, None ... |
def rivers_with_station(stations):
"""Returns a set of rivers with a monitoring station. The input is stations, which
is a list of MonitoringStation objects."""
# return a set of rivers with at least one station
return {station.river for station in stations} |
def caffe_compute(transformed_image,
caffe_net=None, output_layers=None):
"""
Run a Caffe network on an input image after preprocessing it to prepare
it for Caffe.
:param PIL.Image pimg:
PIL image to be input into Caffe.
:param caffe.Net caffe_net:
A Caffe network ... |
def all_different(L):
""" Utility function to check that all values in the list are different """
isinstance(L, list)
result = set()
for value in L:
if value not in result:
result.add(value)
else:
return False
return True |
def parse_sbatch_defaults(parsed):
"""Unpack SBATCH_DEFAULTS."""
d = parsed.split() if type(parsed) == str else parsed
args = {}
for keyval in [a.split("=") for a in d]:
k = keyval[0].strip().strip("-")
v = keyval[1].strip() if len(keyval) == 2 else None
args[k] = v
return ar... |
def next_state(s,counter,N,args):
""" implements magnetization conservation. """
if(s==0): return s;
#
t = (s | (s - 1)) + 1
return t | ((((t & (0-t)) // (s & (0-s))) >> 1) - 1) |
def format_template_names(name_list):
"""Create a comma-separated list of template names.
:param name_list: Input list of names
:return: Comma-separated string
"""
name_txt = ''
for i_name, name_i in enumerate(name_list):
if (i_name == 0):
name_txt += name_i
else:
... |
def for_origin_trial_feature(items, feature_name):
"""Filters the list of attributes or constants, and returns those defined for the named origin trial feature."""
return [item for item in items if
item['origin_trial_feature_name'] == feature_name and
not item.get('exposed_test')] |
def is_in_range(point, other_point, distance=3):
"""Check if point and other_point are within wanted distance."""
points_distance = sum(
abs(coord1 - coord2)
for coord1, coord2 in zip(point, other_point))
return points_distance <= distance |
def sanitizeString(string: str) -> str:
""" Sanitize a string to be safe for filenames
Args:
string: String to sanitize for filenames
Returns:
Version of input string safe for filenames
"""
return string.replace("|", "-").\
replace("/","-").\
replace("\\","-").\
... |
def is_present(lst, target):
""" Determines of the target is in the lst. If so, returns true. If
not, returns false. """
for item in lst:
if target == item:
return True
return False |
def dot_product(X, Y):
"""Computes dot product of two vectors u and v, each represented as a tuple
or list of coordinates. Assume the two vectors are the same length."""
size = len(X)
total = 0
for i in range(size):
total += X[i] * Y[i]
#print X[i], Y[i]
#print total
ret... |
def operator_gt_or_eq_to(op1, op2):
""" Compare two operators to determine operator precedence."""
if op1 in '/*' and op2 in '/*':
return True
elif op1 in '-+' and op2 in '/*-+':
return True
return False |
def get_sample_per_cycle(rate, freq):
"""
calculate the samples per cycle
:param rate: sample rate value
:param freq: sample rate value
:return: samples per cycle
"""
if freq == 0:
return 0
return rate / freq |
def _get_exist_branches(branch_names, all_branch_names):
"""Filter out not existing branches from branch names or return all branches."""
if not branch_names:
return all_branch_names
return set(branch_names).intersection(all_branch_names) |
def get_formatted_name(first, last):
"""Generate a neatly formatted full name."""
full_name = first + ' ' + last
return full_name.title() |
def pow(n):
"""Return 2**n, where n is a nonnegative integer."""
if n == 0: # T(0) = 1
return 1
x = pow(n//2) # T(n) = 1+T(n/2)
if n%2 == 0:
return x*x
return 2*x*x |
def find_kmers(seq, k):
"""Find k-mers in string"""
seq = str(seq)
n = len(seq) - k + 1
return list(map(lambda i: seq[i:i + k], range(n))) |
def is_inside_circle(circle_x: float, circle_y: float, rad: float, x: float, y: float) -> bool:
"""
Finds if a given point lies on or inside the circle, or outside the circle.
Parameters:
circle_x, circle_y : Coordinates of center of circle
rad: radius of circle
... |
def format_text(text: str):
"""Formats text by decoding into utf-8."""
return " ".join([w.encode("latin1").decode("utf-8") for w in text.strip().split(" ")]) |
def atomic_number(elt):
"""Atomic number"""
return elt['z'] |
def RGB(r,g,b):
"""
Pack integer color values into a 32-bit integer format.
@param r: 0 - 255 or 0.0 - 1.0 specifying red
@param g: 0 - 255 or 0.0 - 1.0 specifying green
@param b: 0 - 255 or 0.0 - 1.0 specifying blue
@return: single integer that should be used when any function needs a color value
@rtype: int
@typ... |
def near_field_shift(foclenwat, patlenwat, acovelwat, acovelmet):
"""
:param foclenwat: Fw = focal length in water
:param patlenwat: Xw = path length in water
:param acovelwat: Cw = acoustic velocity in water
:param acovelmet: Cm = acoustic velocity in metal
:return: Fv = new (virtual) focal len... |
def divide_two_numbers(number_1,number_2):
"""The function is to divide two numbers.
PARAMETERS;
number_1: takes the first number, float
number_2: takes the first number, float
RETURN TYPE:
The return value should be in float
EXAMPLE;
>>>print(dividing_two_numbers(9,4))
"""
if number_2 == 0:
print("number error")... |
def bytes_from_str( size_str ):
"""
Given a string description of directory size, return float bytes.
Supports B, K, M, G, T suffixes. B can be ommitted.
"""
unit_conversions = { char: 1024**power for ( power, char ) in enumerate( [ "B", "K", "M", "G", "T" ] ) }
try:
coeff = unit_convers... |
def dd2dms(deg: float):
"""
convert between decimal degrees and deg-min-sec
Parameters
----------
deg
decimal degrees
Returns
-------
list
[degrees as float, minutes as float, seconds as float]
"""
try:
d, m = divmod(abs(deg), 1)
except TypeError:
... |
def bleach_url(url):
"""Remove trailing crud from URL. Use if page doesn't load.
>>> bleach_url('government.ru/news/2666/&sa=U&ved=0ahUKEwjbnY')
'government.ru/news/2666/'
>>> bleach_url('http://www.adsisland.com/?view=selectcity&targetview=post')
'http://www.adsisland.com/'
>>> b... |
def _get_indices(term, chunk):
"""Get indices where term appears in chunk
Parameters
----------
term : str
The token to look for in the `chunk`
chunk : [str]
A chunk of text in which to look for instances of `term`
Returns
-------
[int]
Indices in `chunk` where ... |
def pos2idx(pos, image_size):
"""
Given a position in the 3D image space, return a flattened idx.
Args:
pos (list of 3 int): Position in 3D volume
image_size (list of 3 int): Size of 3D volume
"""
assert(len(pos)==3)
assert(len(image_size)==3)
return (pos[0] * image_size[1]*image_size[2]) + (pos[1] * ima... |
def mashup_one(prefix: str, name: str):
"""Join a prefix and a name split by a hyphen
"""
return prefix.capitalize() + "-" + name.capitalize() |
def _trajectory(line: str):
"""Returns parsed action trajectory."""
actions = [int(x) for x in line.split(' ')]
return tuple(actions) |
def linear_warmup_lr(current_step, warmup_steps, base_lr, init_lr):
"""warmup lr at the end of training"""
lr_inc = (float(base_lr) - float(init_lr)) / float(warmup_steps)
lr1 = float(init_lr) + lr_inc * current_step
return lr1 |
def flatten(list_iterable):
"""
Flatten out multidim list
"""
res = []
for item in list_iterable:
if isinstance(item, list):
res += flatten(item)
else:
res.append(item)
return res |
def proper(list):
"""turns a list of items into a string, but it has the "and" at the end, meaning we can't just use .join()"""
string = ""
for i, item in enumerate(list):
item = str(item)
if i == 0:
string += item
elif i != len(list) - 1:
string += f", {item... |
def find_uniq(arr: list) -> int:
""" This function returns the unique number from 'arr'. """
count_min = arr.count(min(arr))
count_max = arr.count(max(arr))
if count_min == 1:
return min(arr)
return max(arr) |
def read_line(filename):
"""help function to read a single line from a file. returns none"""
line = "Unknown"
try:
with open(filename) as f:
line = f.readline().strip()
finally:
return line |
def _mapSubject(annotation,mapping):
"""
map annotation category_id to a subject
:param mapping:
:param annotation:
:return:
@type mapping: dict
"""
return mapping[annotation['category_id']] if annotation['category_id'] in mapping else 'man-made object' |
def mapValue(value, minValue, maxValue, minResultValue, maxResultValue):
"""
Maps value from a given source range, i.e., (minValue, maxValue),
to a new destination range, i.e., (minResultValue, maxResultValue).
The result will be converted to the result data type (int, or float).
"""
# check if value... |
def is_abstract_model(model):
"""
Given a model class, returns a boolean True if it is abstract and False if it is not.
"""
return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract |
def _get_go2nt(goids, go2nt_all):
"""Get user go2nt using main GO IDs, not alt IDs."""
go_nt_list = []
goids_seen = set()
for goid_usr in goids:
ntgo = go2nt_all[goid_usr]
goid_main = ntgo.id
if goid_main not in goids_seen:
goids_seen.add(goid_main)
go_nt_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.