content stringlengths 42 6.51k |
|---|
def expression_parser(expression, numeric):
"""Parse an uncomplete math expression e.g. '* 10' and apply it to supplied attribute.
Parameters
----------
expression : string
Incomplete math expression in the form '* 5' or '- 10'. Can also be empty to leave
numeric un-affected.
numeri... |
def next_power_of_2(x: int):
"""
Returns the smallest power of two which is >= x.
"""
assert isinstance(x, int) and x > 0
res = 2 ** (x - 1).bit_length()
assert x <= res < 2 * x, f'{x}, {res}'
return res |
def get_hit_table(hit):
"""Create context for a single hit in the search.
Args:
hit(Dict): a dictionary representing a single hit in the search.
Returns:
(dict).The hit context.
(list).the headers of the hit.
"""
table_context = {
'_index': hit.get('_index'),
... |
def get_destroyed_volume(vol, array):
"""Return Destroyed Volume or None"""
try:
return bool(array.get_volume(vol, pending=True)["time_remaining"] != "")
except Exception:
return False |
def check_object_inconsistent_identifier(frm_list, tubes):
"""
checking whether boxes are lost during the track
"""
valid_flag = False
for tube_id, tube_info in enumerate(tubes):
if tube_info[frm_list[0]]!=[0,0,1,1]:
for tmp_id in range(1, len(frm_list)):
tmp_frm ... |
def is_not_csv_file(filename):
"""Retun an indication if the file entered is the clusterserviceversion (csv) file """
return not filename.endswith('clusterserviceversion.yaml') |
def estimate_s3_conversion_cost(
total_mb: float,
transfer_rate_mb: float = 20.0,
conversion_rate_mb: float = 17.0,
upload_rate_mb: float = 40,
compression_ratio: float = 1.7,
):
"""
Estimate potential cost of performing an entire conversion on S3 using full automation.
Parameters
-... |
def merge(lst1, lst2):
"""Merges two sorted lists.
>>> merge([1, 3, 5], [2, 4, 6])
[1, 2, 3, 4, 5, 6]
>>> merge([], [2, 4, 6])
[2, 4, 6]
>>> merge([1, 2, 3], [])
[1, 2, 3]
>>> merge([5, 7], [2, 4, 6])
[2, 4, 5, 6, 7]
"""
"*** YOUR CODE HERE ***"
if lst1 == []:
... |
def cauchy(x0, gx, x):
"""1-D Cauchy. See http://en.wikipedia.org/wiki/Cauchy_distribution"""
#return INVPI * gx/((x-x0)**2+gx**2)
gx2 = gx * gx
return gx2 / ((x-x0)**2 + gx2) |
def max_of(a, b):
"""
Returns the larger of the values a and b.
"""
if a >= b:
return a
return b |
def add(a, b):
""" Addiert die beiden Matrizen a, b komponentenweise.
Gibt das Resultat der Addition als neue Matrix c aus. """
n = len(a)
c = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
c[i][j] = a[i][j] + b[i][j]
return c |
def isDelimited(value):
"""
This method simply checks to see if the user supplied value has delimiters.
That is, if it starts and ends with double-quotes, then it is delimited.
"""
if len(value) < 2:
return False
if value[0] == '"' and value[-1] == '"':
return True
else:
... |
def generate_fasta_dict(sec_record_list):
"""
Creates a dictionary containing FASTA formatted strings from a list of sequence record objects.
This dictionary is keyed by the sequence ID.
:param sec_record_list: List of Biopython sequence record objects.
:return: Dictionary containing FASTA formatted strings.
"""... |
def rgb2int(r, g, b):
""" rgba2int: Converts an RGB value into an integer
:param r The red value (0-255)
:param g The green value (0-255)
:param b The blue value (0-255)
:returns: The RGB value compact into a 24 byte integer.
"""
r, g, b = int(abs(r)), int(abs(g)), int(abs(b))
return (... |
def init_nested_dict_zero(first_level_keys, second_level_keys):
"""Initialise a nested dictionary with two levels
Parameters
----------
first_level_keys : list
First level data
second_level_keys : list
Data to add in nested dict
Returns
-------
nested_dict : dict
... |
def update_key_value(contents, key, old_value, new_value):
"""
Find key in the contents of a file and replace its value with the new value,
returning the resulting file. This validates that the old value is constant and
hasn't changed since parsing its value.
Raises a ValueError when the key cannot... |
def binarize_preds(predictions, threshold=0.5, debug=False):
"""
Converts real-value predictions between 0 and 1 to integer class values 0
and 1 according to a threshold.
Parameters:
-----------------
predictions: predicted values
threshold: threshold for converting prediction to 0 or 1
... |
def check_coarse_parallel(msgs):
# type: (str) -> bool
"""
Check if coarse parallel is enabled as expected
"""
for msg in msgs:
if msg.find('\"coarse_grained_parallel": \"off') != -1:
return False
return True |
def _build_pruned_tree(tree, cases, tree2):
"""helper method for ``build_pruned_tree``"""
is_results = False
if isinstance(tree[0], str):
try:
name, icase, cases2 = tree
except ValueError:
print(tree)
raise
if isinstance(icase, int):
a... |
def get_scope_preview(value, n):
"""
Get the top N lines of a ``scope`` list for an individual :model:`rolodex.ProjectScope`.
**Parameters**
``value``
The ``scope`` value of an individual :model:`rolodex.ProjectScope` entry
``value``
Number of lines to return
"""
return "\n... |
def card_average(hand):
"""
:param hand: list - cards in hand.
:return: float - average value of the cards in the hand.
"""
total = 0
for card in hand:
total += card
return total / len(hand) |
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
return ('' if len(text.split(begin)[0]) > len(text.split(end)[0]) and
begin in text and end in text else
text.split(begin)[-1].split(end)[0] if begin in ... |
def pair_sum_eff(A, n=0):
"""
O(nlogn) but a memory efficient
"""
A = sorted(A)
lst = []
first = 0
last = len(A) - 1
while first < last:
if A[first] + A[last] == n:
lst.append((A[first], A[last]))
first += 1
last -= 1
elif A[first] + A... |
def func_param_immutable_default_safer(collection=None):
"""
:param collection: a collection. default None which is immutable and therefor safer.
:return: collection by appending 'thing'
"""
if collection is None:
# safer pattern, instantiate a new mutable object inside the function, not as ... |
def get_req_key(req_items=[{}]):
"""
Determines the base key in the dict for required items
"""
return [key for key in req_items[0].keys()
if key not in ["description",
"dict_params",
"default_values"]][0] |
def get_rule_names(rules):
"""Returns a sorted list of rule names from the rules list."""
return sorted([r['name'] for r in rules]) |
def build_describe_query(subject):
"""Create a query SELECT * WHERE { <subject> ?p ?o .}"""
return {
'type': 'bgp',
'bgp': [
{
'subject': subject,
'predicate': '?p',
'object': '?o'
}
]
} |
def readable_timedelta(days):
"""To get the number of weeks and days in given nuber of days"""
number_of_weeks = days // 7 #To get number of weeks
number_of_days = days % 7 # To get number of days
return('{} week(s) and {} day(s)'.format(number_of_weeks, number_of_days)) |
def nested_set(base, key_list, value):
"""Set a value in a nested object in base by item sequence."""
for key in key_list[:-1]:
base = base.setdefault(key, {})
base[key_list[-1]] = value
return base |
def hex_to_chars(num):
""" Convert the hex representation of the number to a correctly ordered
string.
Parameters
----------
val: int
The integer representing the string. This is in reverse order.
Ie. XXYYZZ -> chr(ZZ)chr(YY)chr(XX)
Returns
-------
str
The actua... |
def get_one_song_cold_start_recs(title, title_pop_recs, pop_recs, trackID):
"""
Based on title popularity recommender for the cold start scenario!
This method is called for playlists with title info and first song!!
:param title:
:param title_pop_recs:
:param pop_recs:
... |
def concat_body_paragraphs(body_candidates):
"""
Concatenate paragraphs constituting the question body.
:param body_candidates:
:return:
"""
return ' '.join(' '.join(body_candidates).split()) |
def all_ped_combos_lsts(num_locs=4, val_set=("0", "1")):
"""Return a list of all pedestrian observation combinations (in list format) for a vehicle under the 4 location scheme"""
res = []
if num_locs == 0:
return []
if num_locs == 1:
return [[flag] for flag in val_set]
for comb in a... |
def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.split(".")
return int(i), int(f.ljust(6, "0")[:6]) |
def parse_description(description):
"""
Parses the description of a request/response field.
"""
if description is None:
return None
return description.lstrip(' /*').lstrip(' /**').replace('\n', ' ') |
def _decode_options(options):
"""Parse options given in str.
When options = 'cutoff = 4.0', options is converted to {'cutoff': 4.0}.
In this implementation (can be modified), using phonopy command line
options, ``options`` is passed by --fc-calc-opt such as::
phonopy --hiphiveph --fc-calc-opt... |
def scenario_ids(scenarios):
"""Parse the scenarios and feed the IDs to the test function."""
return [test_input[1] for test_input in scenarios] |
def exif2gps(exif_data):
"""
Transform coordinate from DMS into D.D
:param exif_data: image exif data:
:return: degrees in D.D format
"""
if not exif_data:
return None
if isinstance(exif_data[0], tuple):
degree = float(exif_data[0][0] / exif_data[0][1])
else:
degr... |
def quantile(x, percentile):
"""
Returns value of specified quantile of X.
:param list or tuple x: array to calculate Q value.
:param float percentile: percentile (unit fraction).
:return: Q value.
:rtype: int or float
:raise ValueError: when len of x == 0
"""
if x:
p_idx = ... |
def unify(lines):
"""
put one statement on each line
"""
results = []
result = []
for line in lines:
result.append(line)
if ";" in line:
results.append("".join(result))
result = []
return results |
def any_key(m) -> str:
"""Any single key"""
return str(m[0]) |
def subplot_dims(n_plots):
"""Get the number of rows and columns for the give number of plots.
Returns how many rows and columns should be used to have the correct
number of figures available. This doesn't return anything larger than
3 columns, but the number of rows can be large.
Parameters
-... |
def bitlist(n):
"""
Returns a list of bits for a char.
"""
return [n >> i & 1 for i in range(7,-1,-1)] |
def dec_to_tri(n):
"""
:param n: decimal number to be converted to trinary
:returns: trinary string of the number n
"""
tri_string = ""
while n != 0:
tri_string = str(n % 3) + tri_string
n = n // 3
return tri_string |
def f_linear(x, a, b):
"""
compute the linear function value with given parameters
Parameters
----------
x: int or vector
independent variable values
a: double
slope parameter
b: double
y-intercept parameter
... |
def transistor_power(vcc_max, i_out, r_load, r_set):
"""Calculate power loss in the transistor."""
r_tot = r_load + r_set
# Find point where power is maximum
max_pwr_i = vcc_max/(2 * r_tot)
load_rdrop = max_pwr_i * r_tot
v_trans = vcc_max - load_rdrop
return max_pwr_i * v_trans |
def regular_polygon_area(perimeter, apothem):
"""Returns the area of a regular polygon"""
# You have to code here
# REMEMBER: Tests first!!!
return (perimeter * apothem) / 2 |
def get_size_in_nice_string(sizeInBytes):
"""
Convert the given byteCount into a string like: 9.9bytes/KB/MB/GB
"""
for (cutoff, label) in [(1024 * 1024 * 1024, "GB"),
(1024 * 1024, "MB"),
(1024, "KB"),
]:
if siz... |
def _verify_notif_contents(packet):
"""
Verify the contents of a result packet
- Returns False, list of errors if verification fails
OR
- Returns True, None if passes verification
"""
errors = []
# Key "id" not allowed in a JSON-RPC notification
if "i... |
def three_list_to_record(three_list):
"""Helper function for csv_to_records to convert list with three
[lname,fname,age_str] to {'last_name': lname, 'first_name': fname, 'age': age_int}
Code checks argument for three entries and third entry being convertible to int.
Args:
three_list(list(str,st... |
def map_collection(collection, map_fn):
"""Apply ``map_fn`` on each element in ``collection``.
* If ``collection`` is a tuple or list of elements, ``map_fn`` is applied on each element,
and a tuple or list, respectively, containing mapped values is returned.
* If ``collection`` is a dictionary, ``map... |
def get_flattened_sub_schema(schema_fields, parent_name=''):
"""Helper function to get flattened sub schema from schema"""
flattened_fields = []
for field in schema_fields:
flattened_field = dict()
if 'list' in field and field['list']:
flattened_fields.extend(get_flattened_sub_s... |
def num_round(num, decimal=2):
"""Rounds a number to a specified number of decimal places.
Args:
num (float): The number to round.
decimal (int, optional): The number of decimal places to round. Defaults to 2.
Returns:
float: The number with the specified decimal places rounded.
... |
def get_option_specs(name, required=False, default=None, help_str='', **kwargs):
""" A wrapper function to get a specification as a dictionary. """
if isinstance(default, int):
ret = {'name':name, 'required':required, 'default':default, 'help':help_str,
'type':int}
elif isinstance(default, float):
... |
def ordered_sequential_search(array, element):
"""
Array must be ordered!
"""
pos = 0
found = False
stopped = False
while pos < len(array) and not found and not stopped:
if array[pos] == element:
found = True
else:
if array[pos] > element:
... |
def homo(a):
"""Homogenize, or project back to the w=1 plane by scaling all values by w"""
return [ a[0]/a[3],
a[1]/a[3],
a[2]/a[3],
1 ] |
def infer_shape(x):
"""Take a nested sequence and find its shape as if it were an array.
Examples
--------
>>> x = [[10, 20, 30], [40, 50, 60]]
>>> infer_shape(x)
(2, 3)
"""
shape = ()
if isinstance(x, str):
return shape
try:
shape += (len(x),)
... |
def maybe_float(v):
"""Casts a value to float if possible.
Args:
v: The value to cast.
Returns:
A float, or the original value if a cast was not possible.
"""
try:
return float(v)
except ValueError:
return v |
def str_to_bool(s):
"""
Convert a string to a boolean.
:param s: string to convert
:return: boolean value of string
"""
if s.lower() in ('1', 'true', 't'):
return True
elif s.lower() in ('0', 'false', 'f'):
return False
else:
raise ValueError('Input string \"%s\" ... |
def normalize(num, lower=0.0, upper=360.0, b=False):
"""Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : float
Lower limit of range. Default is 0.0.
upper : float
Upper limit of ran... |
def closest(l, n):
"""finds the closest number in sorted list l to n"""
mid = int(len(l) / 2)
if len(l) < 7:
return min(l, key=lambda e: abs(n - e))
elif n > l[mid]:
return closest(l[mid:], n)
else:
return closest(l[:mid+1], n) |
def BuildCampaignCriterionOperations(campaign_operations):
"""Builds the operations needed to create Negative Campaign Criterion.
Args:
campaign_operations: a list containing the operations that will add
Campaigns.
Returns:
a list containing the operations that will create a new Negative Campaign
... |
def unique(errors, model, field, value, *, update=None):
"""Validates that a record's field is unique.
:param errors: The existing error map
:type errors: dict
:param model: The SQLAlchemy database model to check against
:type model: flask_sqlalchemy.Model
:param field: The model's property to ... |
def string(mat, val_format='{0:>8.3f}'):
""" Write a matrix to a string.
:param mat: matrix to form string with
:type mat: tuple(tuple(float))
:param precision: number of integers past decimal
:type precision: int
:rtype: str
"""
mat_str = ''
for row in mat:
... |
def _customize_template(template, repository_id):
"""Copy ``template`` and interpolate a repository ID into its ``_href``."""
template = template.copy()
template['_href'] = template['_href'].format(repository_id)
return template |
def duration(duration):
"""Filter that converts a duration in seconds to something like 01:54:01
"""
if duration is None:
return ''
duration = int(duration)
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 60) // 60
s = '%02d' % (seconds)
m = '%0... |
def crimeValue(crimeStr):
"""Find the crime parameters in the .csv file and converts them from strings (str) to integers (int) for later comparison"""
if crimeStr == "low":
crimeInt = 1
elif crimeStr == "average":
crimeInt = 2
elif crimeStr == "high":
crimeInt = 3
else:
... |
def with_unix_endl(string: str) -> str:
"""Return [string] with UNIX-style line endings"""
return string.replace("\r\n", "\n").replace("\r", "") |
def get_pdb_atom_info(line):
"""Split and read pdb-file line (QPREP-OUT).
Extract and return:
atomnumber, atomname, resname, resid)
"""
# UNIT: check if the correct numbers are extracted
atomnum = int(line[6:11])
atmname = line[13:17].strip()
resname = line[17:20].strip()
resin... |
def closeyear(year):
"""
Find how many years away was the closest leap year to a specific year
"""
return int(year % 4) |
def sizeof_fmt(num, suffix='B', num_type='data'):
"""
Convert bytes into a human readable format
Straight rip from stackoverflow
"""
if num_type == 'data':
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit... |
def is_ipv4_address(addr):
"""Return True if addr is a valid IPv4 address, False otherwise."""
if (not isinstance(addr, str)) or (not addr) or addr.isspace():
return False
octets = addr.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
... |
def _WrapBinaryOp(op_fn, retrieval_fn, value, ctx, item):
"""Wrapper for binary operator functions.
"""
return op_fn(retrieval_fn(ctx, item), value) |
def keep_matched_keys(dict_to_modify,model_keys):
"""
Drops only the keys of a dict that do **not** have the same name as the keys in a source dictionnary.
Return dictionnary containing the rest.
Args:
dict_to_modify (TYPE): DESCRIPTION.
source_dict (TYPE): DESCRIPTION.
Returns:
... |
def remove_dashes(dashed_date):
"""
remove the dashes from a 'yyyy-mm-dd' formatted date
write as a separate function because the apply(lambda x) one doesn't
work as expected
"""
return str(dashed_date).replace('-', '') |
def hilbert_f(x):
"""The Hilbert transform of f."""
return x / (x ** 2 + 1) |
def least_significant_bit(val):
""" Return the least significant bit
"""
return (val & -val).bit_length() - 1 |
def global_object_name(obj):
"""
Return full name of a global object.
>>> from scrapy import Request
>>> global_object_name(Request)
'scrapy.http.request.Request'
"""
return "%s.%s" % (obj.__module__, obj.__name__) |
def _convert_bool_string(value):
"""
Convert a "True" or "False" string literal to corresponding boolean type.
This is necessary because Python will otherwise parse the string "False"
to the boolean value True, that is, `bool("False") == True`. This function
raises a ValueError if a value other tha... |
def capitalize(line):
"""
Courtesy of http://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python
:param line:
:return:
"""
return ' '.join(s[0].upper() + s[1:] for s in line.split(' ')) |
def transpose_list(org_list):
"""
Transpose list of lists.
Parameters
----------
org_list : list
list of lists with equal lenghts.
Returns
-------
list :
transposed list.
"""
return list(map(list, zip(*org_list))) |
def get_consumer_groups(acls):
"""
Given a list of plugins, filter out the `acl` plugin
and return a formatted string
of all the acl consumer group names which are `allowed`
to access the service.
"""
if acls is None:
return
return "`" + "`, `".join(i.get("group") for i in acls) ... |
def get_param_val(
param_str,
param_key='',
case_sensitive=False):
"""
Extract numerical value from string information.
This expects a string containing a single parameter.
Parameters
==========
name : str
The string containing the information.
param_key : st... |
def percental_difference_between_two_numbers(a, b):
"""
How much percent is smaller number smaller than bigger number.
If 1 -> both number equal size
If 0.5 -> smaller number is half the size of bigger number
"""
if a <= b:
return float(a) / b
else:
return float(b) / a |
def is_natural(maybe_nat):
""" Check if the given item is an Int >= 0
:param maybe_nat: Any
:return: Boolean
"""
return isinstance(maybe_nat, int) and maybe_nat >= 0 |
def formatDollarsCents(d,noneValue='',zeroValue='$0.00'):
"""Formats a number as a dollar and cent value with alternatives for None and 0."""
if d is None:
return noneValue
elif d==0:
return zeroValue
return '${:.2f}'.format(d) |
def sqrt(x: int) -> int:
"""
Gets the floor value of the positive square root of a number
"""
assert x >= 0
z = 0
if x > 3:
z = x
y = x // 2 + 1
while y < z:
z = y
y = (x // y + y) // 2
elif x != 0:
z = 1
return z |
def get_trackdata(tracks):
"""Converts CVAT track data.
Args:
tracks (OrderedDict): CVAT track data
Returns:
dict: Data of all tracks
"""
trackdata, tracks_size = \
{}, {}
trackdata['tracks_number'] = len(tracks)
for id, track in enumerate(tracks):
tracks_... |
def process_group(grp):
"""
Given a list of list of tokens
where each token starts with a
character from 'NSEWLRF', and
ends with a number, that describe
the motion of a ship and the direction
it faces at any given point in time,
compute the manhattan distance between
the initial poi... |
def find_du_based_on_ip(ip, functions):
"""
This method finds a du id associated to an ip
"""
for vnf in functions:
if 'vnfr' not in vnf.keys():
continue
vnfr = vnf['vnfr']
dus = []
if 'virtual_deployment_units' in vnfr.keys():
dus = vnfr['virtual... |
def _str(text):
"""Convert from possible bytes without interpreting as number.
:param text: Input to convert.
:type text: str or unicode
:returns: Converted text.
:rtype: str
"""
return text.decode(u"utf-8") if isinstance(text, bytes) else text |
def victoire_ligne(plateau, joueur):
"""
Teste si le plateau admet une victoire en ligne pour le joueur.
"""
for ligne in plateau:
if all(c == joueur for c in ligne):
return True
return False |
def get_data(data_list, data_cache):
"""
Gets the data specified by the keys in the data_list from the data_cache
:param data_list: string or list of strings
:param data_cache: dictionary containing the stored data
:return: a single pandas.DataFrame if input is a string,
a list of DataFrames if... |
def build_SQL_query(query_words: dict) -> str:
"""
Builds an SQL style query string from a dictionary
where keys are column titles and values are values
that the query will test for.
Args:
query_words (dict): a dictionary where keys are column
titles and values are value... |
def override_config(config, overrides):
"""Overrides config dictionary.
Args:
config: dict, user passed parameters for training job from JSON or
defaults.
overrides: dict, user passed parameters to override some within config
dictionary.
Returns:
Modified in... |
def calc_split_class_average_iou(dict):
"""Calculate SOA-C-IoU-Top/Bot-40"""
num_img_list = []
for label in dict.keys():
num_img_list.append([label, dict[label]["images_total"]])
num_img_list.sort(key=lambda x: x[1])
sorted_label_list = [x[0] for x in num_img_list]
bottom_40_iou = 0
... |
def format_list(_list):
"""Format a list to an enumeration.
e.g.: [a,b,c,d] -> a, b, c and d
"""
if len(_list) == 0:
return "no one"
elif len(_list) == 1:
return _list[0]
else:
s = ""
for e in _list[: len(_list) - 2]:
s = s + str(e) + ", "
s =... |
def facility_name(hutch):
"""Return the facility name for an instrument"""
if hutch in [
'dia', 'mfx', 'mec', 'cxi', 'xcs', 'xpp', 'sxr', 'amo',
'DIA', 'MFX', 'MEC', 'CXI', 'XCS', 'XPP', 'SXR', 'AMO',
]:
return '{}_Instrument'.format(hutch.upper())
return '{}_Instrument'.format(h... |
def _calc_isbn10_check_digit(number):
"""Calculate the ISBN check digit for 10-digit numbers. The number passed
should not have the check bit included."""
check = sum((i + 1) * int(n)
for i, n in enumerate(number)) % 11
return 'X' if check == 10 else str(check) |
def swap_xyz_string(xyzs, permutation):
"""
Permutate the xyz string operation
Args:
xyzs: e.g. ['x', 'y+1/2', '-z']
permuation: list, e.g., [0, 2, 1]
Returns:
the new xyz string after transformation
"""
if permutation == [0,1,2]:
return xyzs
else:
n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.