content stringlengths 42 6.51k |
|---|
def credentials(access_key, secret_key, account_id):
"""Fake set of MWS credentials"""
return {
"access_key": access_key,
"secret_key": secret_key,
"account_id": account_id,
} |
def findIntersection(newLinexList, newLineyList, inputxList, inputyList):
"""After preprocessing is complete, goes about finding intersection of
straight line and orginal data curve by finding point on striaght line
that is closest to a point on data curve (brute force)"""
mainDiffList = []
mainDiffListDataIndexes... |
def prepare_url(valip, valch):
"""
Prepare the URL
"""
## Parameter - IP
url = "http://" + valip
## Parameter - URL - action
url += "/api/v100/dali_devices.ssi?action=get"
## Parameter - Channel
url += "&ch=" + valch
return url |
def retry_func(func, retrys, allowed_exceptions, *args, **kwargs):
"""
Calls `func` with `args` and `kwargs` until it executes without raising an
exception in `allowed_exceptions`. Calls a max of `retrys` times.
Returns the return value of `func` call. If func raises an exception not in
`allowed_exc... |
def get_overlap(a, b):
"""
report overlap of coordinates
"""
return max(0, min(a[1], b[1]) - max(a[0], b[0])) |
def get_ir_account_name(eas):
"""Return IR account name, or None if not found."""
try:
if eas.selectedPlugins:
if eas.selectedPlugins.IonReporterUploader:
if eas.selectedPlugins.IonReporterUploader.userInput:
inpt = eas.selectedPlugins.IonReporterUploader.... |
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# Count the number of occurences of each word in s
words = s.split() # split words into list on spaces
uniquewords = []
# for every word in the list
for word in words:
iswordunique = True
# check to... |
def scale_ticks_params(tick_scale='linear'):
""" Helper function for learning cureve plots.
Args:
tick_scale : available values are [linear, log2, log10]
"""
if tick_scale == 'linear':
base = None
label_scale = 'Linear scale'
else:
if tick_scale == 'log2':
... |
def can_be_float(string):
"""Returns True if a string can be converted to a float,
False if not"""
try:
float(string)
return True
except ValueError:
return False |
def find_multiples_sum_for_range(number_range):
"""
Find the sum of all the multiples of 3 or 5 below N.
Function to take number_range as integer and return sum of
all the multples of 3 or 5 below it.
Parameters
----------
number_range : int
Range of number
Returns
-------... |
def reduce_multiple(f, parts):
""" """
partitions = iter(parts)
try:
res = next(partitions)[0]
except StopIteration:
return
for part in partitions:
if part:
res = f(res, part[0])
return [res] |
def pop(obj, key=0, *args, **kwargs):
"""Pop an element from a mutable collection.
Parameters
----------
obj : dict or list
Collection
key : str or int
Key or index
default : optional
Default value. Raise error if not provided.
Returns
-------
elem
P... |
def equal_or_slightly_less(a, b, threshold=5):
"""
Return boolean depending on whether `a` is equal to or slightly
less than `b` (based on threshold of allowed deviation).
Args:
a (number): first number
b (number): second number
threshold (int, optional): Threshold. Defaults to... |
def parse_number_input(user_input):
"""Converts a string of space-separated numbers to an array of numbers."""
lst_str = user_input.strip().split(' ')
return list(map(int, lst_str)) |
def rstrip_word(text, suffix):
"""Strip suffix from end of text"""
if not text.endswith(suffix):
return text
return text[:len(text) - len(suffix)] |
def reported_news(file_paths):
"""Check if Misc/NEWS has been changed."""
return True if 'Misc/NEWS' in file_paths else False |
def credentials_file(api_name):
""" returns a path to the file where credentials are to be stored. """
return 'api_keys/' + api_name + '_credentials.json' |
def scinotation(x,n=2):
"""
Displays a number in scientific notation.
:param x: number
:param n: number of significant digits to display
"""
import decimal
fmt='%.'+str(n)+'E'
s= fmt % decimal.Decimal(str(x))
return s |
def _score_phrases(phrase_list, word_scores):
"""Score a phrase by tallying individual word scores"""
phrase_scores = {}
for phrase in phrase_list:
phrase_score = 0
# cumulative score of words
for word in phrase:
phrase_score += word_scores[word]
phrase_scores[" ... |
def convertStrand(s):
"""
Given a potential strand value, converts either from True/False/None
to +/-/None depending on value
"""
assert s in [True, False, None, "+", "-"]
if s == True: return "+"
elif s == False: return "-"
elif s == None: return None
elif s == "-": return False
... |
def should_distort_images(flip_left_right, random_crop, random_scale,
random_brightness):
"""Whether any distortions are enabled, from the input flags.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting the total m... |
def lm_to_ansi(l, m):
"""Convert Zernike (l,m) two term index to ANSI single term index.
Parameters
----------
l,m : int
radial and azimuthal mode numbers.
Returns
-------
idx : int
ANSI index for l,m
"""
return int((l * (l + 2) + m) / 2) |
def coordinates_string(coordinates_list):
"""
This function transforms the list of coordinates to string.
:param coordinates_list: list
the list has float coordinate values
in this order:
[min_lon, min_lat, m... |
def compute_error(b, m, coordinates):
"""
m is the coefficient and b is the constant for prediction
The goal is to find a combination of m and b where the error is as small as possible
coordinates are the locations
"""
totalError = 0
for i in range(0, len(coordinates)):
x = coordinat... |
def compute_acc_by_type(q_types, corrects):
"""
Args:
q_types (list of str), q_type for each example
corrects (list of int), 1/0 predition for each example
return:
acc_by_type: list of stringfied acc for each type
"""
qtypes = ["what", "who", "where", "how", "why", "other"]
... |
def build_process_dic(lst):
"""
Simple method to build a dictionnary for process need and results
from a list such as ['cake', '8', 'dollar', '20'] wich will result in
{'cake' : 8, 'dollar' : 20}
"""
dico = {}
i = 0
for i, elem in enumerate(lst):
if elem[-1] =... |
def toLowerCase(s):
""" Convert a sting to lowercase. E.g., 'BaNaNa' becomes 'banana'
"""
return s.lower() |
def _interpolate(dist_in_interval, min_val, max_val, interval_length):
"""Linear interpolation between min_val and max_val.
Interval assumed to be (0,interval_length)
"""
if dist_in_interval > interval_length:
raise ValueError
if min_val > max_val:
raise ValueError
diff = max_va... |
def flatten_columns(columns, sep = '_'):
"""flatten multiple columns to 1-dim columns joined with '_'
"""
l = []
for col in columns:
if not isinstance(col, str):
col = sep.join(col)
l.append(col)
return l |
def FormatType(value):
"""Custom type for '--format' option."""
value = value.split(',')
fmt = value.pop(0)
if fmt not in ('qcow2', 'raw'):
import argparse
raise argparse.ArgumentTypeError("format must either 'qcow2' or 'raw'")
options = {opt: opt_val for elt in value for opt, opt_va... |
def remove_whitespace(phrase):
"""
This function remove all the whitespace of a string
Parameters :
phrase: the string
Returns :
return string whitout whitespace
"""
return phrase.replace(' ', '') |
def _nonnegative_nonzero_integer(x):
"""Check for nonnegative and nonzero integer."""
if x is not None:
try:
x = int(x)
except ValueError:
raise ValueError(
"'stata_check_log_lines' must be a nonzero and nonnegative integer, "
f"but it is '... |
def rad_seq(t, y, energy):
"""returns radial SEQ as system of two 1st order differential equations"""
# input: y = [y1, y2]; return y = [y1', y2']
# y1' = y2; y2' = (...)*y1
return [y[1], (- 2 * (1 / t + energy)) * y[0]] |
def decor_tester(req, **kwargs):
"""
:kwargs: None
"""
return {'status': True, 'data': 'Decor Tests Passed'} |
def reverse_string(st):
"""
return a string in reverse form
"""
stack = list()
# Push each character into stack
for ch in st:
stack.append(ch)
rev = ""
# Pop each character one by one until stack is not empty
while len(stack):
rev += stack.pop()
return rev |
def gcd(fst, snd):
"""Uses Euclidean algorithm to compute the gcd of two integers.
Takes two integers, returns gcd >= 0.
Note: gcd(0,0) returns 0 but in this case the gcd does not exist.
"""
while snd > 0:
fst, snd = snd, fst % snd
return fst |
def gen_end( first_instruction_address ):
"""generate end record"""
col2_size = 6
col1 = "E"
col2 = hex(first_instruction_address)[2:].zfill(col2_size).upper()
return col1 + col2 |
def convert_datetime(value):
"""Deserialize datetime object into string"""
if value is None:
return None
return [value.strftime("%d-%m-%y"), value.strftime("%H:%M:%S")] |
def get_deep(obj, selector):
""" Returns the object given by the selector, eg a:b:c:1 for ['a']['b']['c'][1] """
try:
if type(selector) is str:
selector = selector.split(':')
if len(selector) == 0:
return obj
top_selector = selector.pop(0)
if type(obj) ... |
def _number(number, noun):
"""Return a repr of amount in correct grammatical number."""
suffix = 's' if number > 1 else ''
return f'{number} {noun}{suffix}' |
def _signed_12bit_to_float(val):
""" Take first 11 bits as absolute value
"""
abs_val = (val & 0x7FF)
if val & 0x800:
return 0 -float(abs_val)
return float(abs_val) |
def visible(headers):
""" returns only headers of visible columns """
return [el for el in headers if el.get('visible', True)] |
def _get(data, item, default=None):
"""
Helper function to catch empty mappings in RAML. If item is optional
but not in the data, or data is ``None``, the default value is returned.
:param data: RAML data
:param str item: RAML key
:param default: default value if item is not in dict
:param ... |
def bagofwords(sentence_words, vocab):
"""Given tokenized, words and a vocab
Returns term frequency array"""
bag = [0] * len(vocab)
for sw in sentence_words:
for i, word in enumerate(vocab):
if word == sw:
bag[i] += 1
return bag |
def isPalindrome(s):
"""
:type s: str
:rtype: bool
"""
s=s.lower()
element=[i for i in s if i.isalnum()]
return element==element[::-1] |
def add_suffix(suffix, name):
"""Adds subfix to name."""
return "/".join((name, suffix)) |
def make_uniform_initializer(low, high):
"""make uniform initializer param of make_table_options
Args:
low (float): A python scalar. Lower bound of the range of random values to generate.
high (float): A python scalar. Upper bound of the range of random values to generate.
Returns:
... |
def dates_to_fits(date_begin, date_end):
"""Convert two dates into FITS form.
Parameters
----------
date_begin : `astropy.time.Time`
Date representing the beginning of the observation.
date_end : `astropy.time.Time`
Date representing the end of the observation.
Returns
---... |
def test_bit(value, offset):
"""Test a bit at offset position
:param value: value of integer to test
:type value: int
:param offset: bit offset (0 is lsb)
:type offset: int
:returns: value of bit at offset position
:rtype: bool
"""
mask = 1 << offset
return bool(value & mask) |
def same_sentence(c):
"""Return True if all Spans in the given candidate are from the same Sentence.
:param c: The candidate whose Spans are being compared
:rtype: boolean
"""
return all(
c[i].sentence is not None and c[i].sentence == c[0].sentence
for i in range(len(c))
) |
def atlas_name_from_repr(name, resolution, major_vers=None, minor_vers=None):
"""Generate atlas name given a description."""
if major_vers is None and minor_vers is None:
return f"{name}_{resolution}um"
else:
return f"{name}_{resolution}um_v{major_vers}.{minor_vers}" |
def AxisUnitsConvertRev(UnitCode):
""" convert axis untis"""
switcher = {
'nm' : 'nm',
'$\mu$m' : 'microns'
}
return switcher.get(UnitCode, 'nm') |
def avoid_snakes(possible_moves: dict, snakes: dict):
""" Removes the moves that will collide with other snakes """
moves_to_remove = []
for snake in snakes:
for move in possible_moves:
if possible_moves[move] in snake["body"]:
moves_to_remove.append(move)
for move i... |
def greatest_common_divisor(a: int, b: int) -> int:
"""
>>> greatest_common_divisor(4, 8)
4
>>> greatest_common_divisor(8, 4)
4
>>> greatest_common_divisor(4, 7)
1
>>> greatest_common_divisor(0, 10)
10
"""
return b if a == 0 else greatest_common_divisor(b % a, a) |
def _paths_to_tree(paths):
"""Build a tree from the given paths.
The structure of the tree is described in the docstring for _prune_paths.
"""
tree = {}
for path in paths:
t = tree
for c in path:
if c not in t:
t[c] = {}
t = t[c]
return t... |
def revcomp(dna, reverse=True, complement=True):
""" reverse complement of a protein in negative strand"""
bases = 'ATGCTACG'
complement_dict = {bases[i]:bases[i+4] for i in range(4)}
if reverse:
dna = reversed(dna)
result_as_list = None
if complement:
result_as_list = [compl... |
def solution(number): # O(N)
"""
Write a function to compute the fibonacci sequence value to the requested iteration.
>>> solution(3)
2
>>> solution(10)
55
>>> solution(20)
6765
"""
m = {
0: 0,
1: 1
} ... |
def is_leap_year(year):
"""Determine whether a year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
def histogram(s):
"""Takes a string s, returns a dictionary d of letters -> frequencies"""
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d |
def _longstr(num, length=0):
""" Return binary string representation of `num`. """
buf = chr(num & 0xff)
num >>= 8
while num:
buf = chr(num & 0xff) + buf
num >>= 8
while len(buf) < length:
buf = chr(0) + buf
return buf |
def dec_to_bin(x):
"""
convert decimal value into a binary value
:param x: decimal value
:return: binary value
"""
return int(bin(x)[2:]) |
def colorscale_to_scale(colorscale):
"""
Extracts the interpolation scale values from colorscale as a list
"""
scale_list = []
for item in colorscale:
scale_list.append(item[0])
return scale_list |
def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float
"""
try:
... |
def get_pager_start(pager, start):
"""Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept.
"""
if pager in ['less','more']:
if start:
start_string = '+' + str(start)
else:
start_string = ''
els... |
def n_smaller(num,a,i1,i2):
"""
Returns the number of elements smaller
than num in sorted array, a between indices
i1 and i2
"""
if num>a[i2-1]:
return i2-i1+1
elif num<a[i1-1]:
return 0
hi=i2-1; lo=i1-1
mid = int((lo+hi)/2)
while hi>lo:
if num==a[mid] or... |
def flatten_dictionary(dictionary):
"""Function that takes a heirarchical dictionary and flattens it to one level.
The function takes an input dictionary containing multiple levels (i.e. dictionaries
within dictionaries), and restructures the contents as a single level dictionary wit... |
def filter_keys(keys):
"""This api is used to take a string or a list of one string and split it
appropriately to get the list of keys to look for while filtering a
dictionary. It is first split on basis of semicolon(;) which acts like a
separator of scenarios given. Next it's split on comma which is th... |
def filter_objlist(olist, fieldname, fieldval):
"""
Returns a list with of the objetcts in olist that have a fieldname valued as fieldval
@param olist: list of objects
@param fieldname: string
@param fieldval: anything
@return: list of objets
"""
return [x for x in olist if getattr(x, ... |
def contains_base_name(string, base_name):
"""
Checks if the base experiment name is contained in a string. Both names should look like
MODELNAME__PARAM1=VALUE1__PARAM2=VALUE2...
Parameters
-----------
string: str
We want to know if string contains base name.
base_name: str
... |
def has_tag(obj, tag):
"""Helper class that tests to see if the obj is a dictionary
and contains a particular key/tag.
>>> obj = {'test': 1}
>>> has_tag(obj, 'test')
True
>>> has_tag(obj, 'fail')
False
>>> has_tag(42, 'fail')
False
"""
return type(obj) is dic... |
def _remove_default_condition(settings):
"""Returns settings with "//conditions:default" entries filtered out."""
new_settings = []
for setting in settings:
if settings != "//conditions:default":
new_settings.append(setting)
return new_settings |
def transform_name_to_id(name: str, lower: bool = True) -> str:
"""This transformation was taken from the cpp Antares Simulator.."""
duppl = False
study_id = ""
for c in name:
if (
(c >= "a" and c <= "z")
or (c >= "A" and c <= "Z")
or (c >= "0" and c <= "9")
... |
def solve_pair(p1, p2, ofs1, ofs2):
"""way faster"""
for n in range(p2):
t = p1 * n - ofs1
if (t + ofs2) % p2 == 0:
return t |
def symbol_syntax(exchange, symbol):
"""
translate ticker symbol to each exchange's local syntax
"""
asset, currency = symbol.upper().split(":")
# ticker symbol colloquialisms
if exchange == "kraken":
if asset == "BTC":
asset = "XBT"
if currency == "BTC":
... |
def _GetFormatCharForStructUnpack(int_width):
"""Gets the sample's integer format char to use with struct.unpack.
It is assumed that 1-byte width samples are unsigned, all other
sizes are signed.
Args:
int_width: (int) width of the integer in bytes. Can be 1, 2, or 4.
Returns:
The format char corre... |
def give_unit_attribute(unit_to_display):
"""give the unit attributes"""
attr = {}
attr["Unit displayed"] = unit_to_display
return attr |
def get_expected_validation_developer_message(preference_key, preference_value):
"""
Returns the expected dict of validation messages for the specified key.
"""
return "Value '{preference_value}' not valid for preference '{preference_key}': {error}".format(
preference_key=preference_key,
... |
def cleanString(string, nows=False):
"""*nows* is no white space."""
if nows:
return ''.join(string.strip().split())
else:
return ' '.join(string.strip().split()) |
def ms_limit(q, lim):
"""MS SQL Server implementation of 'limit'"""
return "SELECT TOP {} sq.* FROM ({}) sq".format(lim, q) |
def flatten_dict(d: dict):
"""Flattens dictionary with subdictionaries.
Arguments:
d {dict} -- Dict to flatten
Returns:
flattened {dict} -- Flattened dict
"""
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, sub... |
def matches(ticker_tape, aunt):
"""
matches returns true if the aunt's attributes match the ones in the ticker_tape
"""
for attribute, value in aunt.items():
if ticker_tape[attribute] != value:
return False
return True |
def get_target_path(triple, kind, test_it):
"""Constructs a target path based on the configuration parameters.
Args:
triple: Target triple. Example: 'x86_64-unknown-linux-gnu'.
kind: 'debug' or 'release'.
test_it: If this target is tested.
"""
target_path = '/tmp/%s_%s' % (triple, kind)
if test_i... |
def decrypt(d, n, c):
"""
Given d and n are given, select a number (c) and return the decrypted value.
>>> decrypt(257, 377, 341)
100
>>> decrypt(186, 255, 461)
106
>>> decrypt(256, 300, 657)
201
"""
return c ** d % n |
def export_clean_cav_ligand_info(dict_coverage, list_ligands, list_lig_coords, cavities):
"""
Helpful for the database storage because with what's above it's a horrible mess
"""
try:
dict_coverage.items()
except:
return None, None
list_covered_ligands = []
dict_cavid_lig_bool = {}
for ligid, value in dict_c... |
def delta(prev, cur, m):
""" Compute the delta in metric 'm' between two metric snapshots. """
if m not in prev or m not in cur:
return 0
return cur[m] - prev[m] |
def sanitize_secrets(secrets):
""" misc utilities for Cloudflare API"""
redacted_phrase = 'REDACTED'
if secrets is None:
return None
secrets_copy = secrets.copy()
if 'password' in secrets_copy:
secrets_copy['password'] = redacted_phrase
elif 'X-Auth-Key' in secrets_copy:
... |
def strip(line):
"""Strip the identation of a line for the comment header."""
if line.startswith(' ' * 4):
line = line[4:]
return line.rstrip() |
def decode_float(value):
"""Decode a float after checking to make sure it is not already a float, 0, or empty."""
if type(value) is float:
return value
elif value == 0:
return 0.0
elif not value:
return None
return float(value) |
def element_to_set_distance(v, s):
"""Returns shortest distance of some value to any element of a set."""
return min([abs(v-x) for x in s]) |
def get_workspace_type(workspace_path):
"""Return workspace type."""
if workspace_path.endswith('.gdb'):
workspace_type = 'FILEGDB_WORKSPACE'
elif workspace_path.endswith('.mdb'):
workspace_type = 'ACCESS_WORKSPACE'
elif workspace_path.endswith('.sde'):
workspace_type = 'SDE_WORK... |
def get_car_road_position(left_fit, right_fit, xm_per_pix, UNWARPED_SIZE):
""" Calculate position of the vehicle with respect to center of road
Args:
left_fit: `numpy.ndarray` second order linear regression of left lane line
right_fit: `numpy.ndarray` second order linear regression of right lan... |
def dict2descorderlist(
d: dict) -> list:
"""Creates a sorted list in
decending order from
a dictionary with counts
Args:
dict: histogram or
frequency count
Returns:
list
"""
l = [[v, k] for k, v in d.items()]
l.sort()
l.reverse()
r... |
def label_list_to_int(label):
"""convert type of labels to integer"""
int_label = []
for e in label:
try:
inte = int(e)
except ValueError:
print('Label are not int numbers. A mapping will be used.')
break
int_label.append(inte)
if len(int_label... |
def check_min_range(j, min):
"""
Checks j >= min
If false, returns j mod min
Else j
"""
if j < min:
j %= min
return j |
def filter_betting_on_same_match(bet_on_matches, home_team, away_team):
"""
Reduce candidates which have had a bet placed already
"""
for match in bet_on_matches:
if home_team == match["home"] and away_team == match["away"]:
bet_on_matches.remove(match)
return bet_on_match... |
def constant(x, amp):
""" Constant model
:param x: Dispersion
:type x: np.ndarray
:param amp: Amplitude of the constant model
:type amp: float
:return: Constant model
:rtype: np.ndarray
"""
return amp + 0 * x |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if input_list is None:
return None
next_pos_0 = 0
next_pos_2 = len(input_list) - 1
front_pos = 0
... |
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
print ("Top of loop:", x, a)
if x == a:
print ("In x == a: ", x, a)
return 0
elif x < a:
print ("In x < a: ", x, a)
... |
def multistep_lr_decay(optimizer, current_step, schedules):
"""Manual LR scheduler for implementing schedules described in the WAE paper."""
for step in schedules:
if current_step == step:
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr']/schedu... |
def compress_whitespace(instr: str) -> str:
"""
Remove leading and trailing white space and compress multiple
consecutive internal spaces into one space.
Args:
instr (str): String to be cleaned.
Returns:
(str): The cleaned string.
"""
result = instr.strip()
result = ' '.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.