content stringlengths 42 6.51k |
|---|
def add_up(n):
"""
Adds up all numbers from 1 to n.
"""
numbers = range(1, n + 1)
return sum(numbers) |
def serial_to_chamber(x: int) -> int:
"""Convert serialized chamber id to chamber number."""
return (x & 0x0000003F) + 1 |
def _to_list(obj):
"""Make object into a list"""
return [obj] if not isinstance(obj, list) else obj |
def u_func(c, h, mp):
""" Calculates utility of chosen (consumption, housing) bundle.
Args:
c (float): consumption
h (float): housing
mp (dict): model parameters.
Returns:
(float): utility of bundle
"""
return (c**(1-mp['phi']))*(h**mp['phi']) |
def JsonString_to_JsonFile(json_string,file_name="test.json"):
"""Transforms a json string to a json file"""
out_file=open(file_name,'w')
out_file.write(json_string)
out_file.close()
return file_name |
def _py_assert_stmt(expression1, expression2):
"""Overload of assert_stmt that executes a Python assert statement."""
assert expression1, expression2()
return None |
def do_the_diff(defaults, overrides):
"""Diff two yaml loaded objects, returning diffs in a namedtuple
:param defaults: File you wish to compare against, the base.
:param overrides: File you wish to compare, the mask.
:return: stuff
:rtype: dict
"""
new_combined_diff = {}
for key in o... |
def pad(l, until=0, fillvalue=None):
"""
Pad a list.
"""
for _ in range(until - len(l)):
l.insert(0, fillvalue)
return l |
def convert (number):
"""
:param number: int
:return: str - as requested
"""
result = ''
if (number % 3) == 0:
result = 'Pling'
if (number % 5) == 0:
result += 'Plang'
if (number % 7) == 0:
result += 'Plong'
if len (result) == 0:
return f'{number... |
def get_total_colors(color_frequencies: dict) -> int:
"""Count total amount of colors"""
return len([p for p in color_frequencies.values() if p]) |
def generate_variable(r, c, n):
"""Creates a label for the coordinates and contents of a cell."""
return f'{r},{c}_{n}' |
def merge_timelines(timeline_a, timeline_b):
"""Takes two timelines, both of which must contain a list of times and a
list of values, and combines them into a single timeline containing a list
of times and added values, so that if an interval in both timelines
overlap, then the returned timeline will sh... |
def nexus_infile(myid,itwist):
""" nexus style input name
Args:
myid (str): prefix
itwist (int): twist index
Returns:
str: input filename
"""
prefix = myid.split('.')[0]
infile = '.'.join([prefix,'g%s'%str(itwist).zfill(3),'twistnum_%d'%itwist,'in','xml'])
return infile |
def xlen(seq):
"""
Returns the length of a sequence or None.
Parameters
----------
seq : iterable or None
Returns
-------
int or None
"""
if (seq is None): return seq
return len(seq) |
def divider_row(sizes):
""" Create a one line string of '-' characters of given length in each column """
s = ''
for i in range(len(sizes)):
s = s + '-'.ljust(sizes[i], '-') + ' '
return s |
def isempty(s):
"""return if string is empty
"""
if s is None or s == "" or s == "-":
return True
else:
return False |
def count_vowels(s):
""" (str) -> int
Return the number of vowels (a, e, i, o, and u) in s.
>>> count_vowels('Happy Anniversary!')
5
>>> count_vowels('xyz')
0
"""
num_vowels = 0
for char in s:
if char in 'aeiouAEIOU':
num_vowels = num_vowels + 1
return nu... |
def should_force_reinit(config):
"""Configs older than 2.0.0 should be replaced"""
ver = config.get("cli_version", "0.0.0")
return int(ver.split(".")[0]) < 2 |
def extract_features(document, word_features):
"""
Used to get a word vector required by the naive bayes classifier for training and during streaming
:param document: tokens
:param word_features: all words
:return:
"""
document_words = set(document)
features = []
for word in word_fea... |
def get_errors_from_serializer(serializer_errors):
"""
Extracts the errors from the serializer errors into a list of strings.
"""
errors = []
for key, details in serializer_errors.items():
for error in details:
errors.append(str(error))
return errors |
def check_parameter_string(candidate, param):
"""Checks that a parameter is a string or a list of strings.
"""
parameters = {
"site": "NWIS station id(s) should be a string or list of strings,"
+ "often in the form of an eight digit number enclosed in quotes.",
"parameterCd": "NWIS p... |
def scalar_mul(eta, x):
"""Scalar multiplication. Return a list with the same dimensions as `x`
where each element in `x` is multiplied by `eta`.
Args:
eta (float) Scalar to apply to `x`.
x (list): Vector to scale. 1 or 2 dimensional.
Returns:
list: A scaled list. Same dimensio... |
def calc_lcoe_om(fom, vom, cf=1):
"""
:param fom: Fixed operation and maintentance costs as CURR/KWY
:param vom: Variable cost in the form of CURR/ KWH
:param cf: Capacity factor assumed for the plant, default is 1
:return: LCOE O&M component in CURR per KWh
"""
fixed = fom / (cf * 8600)
... |
def process_funql(funql):
"""Remove quotes and unnecessary spaces."""
funql = funql.replace("'", "")
funql = funql.replace(", ", ",")
funql = funql.replace(", ", ",")
funql = funql.replace(" ,", ",")
return funql |
def intersection(L1, L2):
"""
Find the intersection point of the two lines
A1 * x + B1 * y = C1
A2 * x + B2 * y = C2
The intersection point is:
x = Dx/D
y = Dy/D
The determinant D
A1 B1 which is L1[0] L1[1]
A2 B2 L2[0] L2[1]
Dx:
C1 B1 which is L1[2... |
def parse_line(line):
"""Parse a line of instructions and return a (step, requires) tuple"""
assert line.startswith("Step ") and line.endswith(" can begin.")
word = line.split()
return word[7], word[1] |
def quantize(rgb, quanta):
"""map a tuple (r,g,b) each between 0 and 255
to our discrete color buckets"""
r,g,b = rgb
r = max([q for q in quanta if q <= r])
g = max([q for q in quanta if q <= g])
b = max([q for q in quanta if q <= b])
return (r,g,b) |
def create_word_vocab(input_data):
"""create word vocab from input data"""
word_vocab = {}
for sentence in input_data:
words = sentence.strip().split(' ')
for word in words:
if word not in word_vocab:
word_vocab[word] = 1
else:
word_voc... |
def list_merger(base_list, overlay_list):
"""It is important to note we expect both arg lists to be non-repeating.
Merges lists such that the `base_list` is preserved and
the `overlay_list` is overlaid onto it.
Example:
source = ['Node', 'Node1']
target = ['Node', 'Jack']
returns = ['Node', ... |
def point_sub(a, b):
""" Subtract two 2d vectors
(Inline this if you can, function calls are slow)
"""
return (a[0] - b[0], a[1] - b[1]) |
def unwrap(mappings):
"""Remove the set() wrapper around values in component-to-team mapping."""
for c in mappings['component-to-team']:
mappings['component-to-team'][c] = mappings['component-to-team'][c].pop()
return mappings |
def choice_id(choice):
"""
Returns Choice type field's choice id for form rendering
"""
try:
resp = choice[0]
except IndexError:
resp = ''
pass
return resp |
def camel_case(name):
# type: (str) -> str
"""Return a camelCased version of a string."""
return name[0:1].lower() + name[1:] |
def _validate(validation_func, err, *args):
"""Generic validation function that returns default on
no errors, but the message associated with the err class
otherwise. Passes all other arguments into the validation function.
:param validation_func: The function used to perform validation.
:param err... |
def sort_by(comparator, list):
"""Sorts the list according to the supplied function"""
return sorted(list, key=comparator) |
def gcd_recursive_by_divrem(m, n):
"""
Computes the greatest common divisor of two numbers by recursively getting remainder from
division.
:param int m: First number.
:param int n: Second number.
:returns: GCD as a number.
"""
if n == 0:
return m
return gcd_recursive_by_div... |
def sort_and_print(body, num):
"""
Sorts the values of dictionaries and prints respective
top sentences
:param body: list of dictionaries of 'sentence': score
:param num: no of sentences to be printed
:return: prints
"""
result = []
rank = []
for sentdict in body:
for sen... |
def _clean_message(output: str) -> str:
"""Strips the succeeding new line and carriage return characters."""
return output.rstrip("\n\r") |
def time_is_hh_mm_ss_ms(str_hh_mm_ss_ms):
"""test if time value is format hh:mm:ss.ms
Args:
str_hh_mm_ss_ms (str): time value
Raises:
Exception: incorrrect format
Returns:
bol: True if valid
"""
try:
hr, min, sec = map(float, str_hh_mm_ss_ms.split(':'))
... |
def reverse_dict(dct):
""" Reverse the {key:val} in dct to
{val:key}
"""
newmap = {}
for (key, val) in dct.items():
newmap[val] = key
return newmap |
def _get_interior_years(from_year, to_year, start_year, end_year):
"""Return the Rule years that overlap with the Match[start_year, end_year].
"""
years = []
for year in range(start_year, end_year + 1):
if from_year <= year and year <= to_year:
years.append(year)
return years |
def ctd_sbe37im_preswat(p0, p_range_psia):
"""
Description:
OOI Level 1 Pressure (Depth) data product, which is calculated using
data from the Sea-Bird Electronics conductivity, temperature and depth
(CTD) family of instruments.
This data product is derived from SBE 37IM instru... |
def M_from_t(t,n,M0,t0):
"""
find mean anomaly at time t
Parameters
----------
t
time to find M for
n
mean motion
M0
reference mean anomaly at time t0
t0
reference time t0
Note that M = 0 at pericentre so if t0 = pericentre passage time then M0 = 0
... |
def decode_cp1252(string):
"""
CSV files look to be in CP-1252 encoding (Western Europe)
Decoding to ASCII is normally fine, except when it gets an O umlaut, for example
In this case, values must be decoded from cp1252 in order to be added as unicode
to the final XML output.
This function helps ... |
def count_mismatches(aligned_seq1, aligned_seq2):
"""
:param seq1, aligned_seq2: aligned sgRNA and genomic target (seq+PAM)
:return:
"""
cnt = 0
ending = len(aligned_seq1) - 3
for i in range(ending):
cnt += int(aligned_seq1[i] != aligned_seq2[i] and aligned_seq1[i] != "-" and aligned_seq2[i] != "-")
... |
def decimal_to_binary_util(val):
"""
Convert 8-bit decimal number to binary representation
:type val: str
:rtype: str
"""
bits = [128, 64, 32, 16, 8, 4, 2, 1]
val = int(val)
binary_rep = ''
for bit in bits:
if val >= bit:
binary_rep += str(1)
val -= bi... |
def get_catalog_record_embargo_available(cr):
"""
Get access rights embargo available date as string for a catalog record.
:param cr:
:return:
"""
return cr.get('research_dataset', {}).get('access_rights', {}).get('available', '') |
def _damerau_levenshtein(a, b):
"""Returns Damerau-Levenshtein edit distance from a to b."""
memo = {}
def distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y]
if not x:
d = len(y)
elif not y:
d = len(x)
else:
... |
def itb(num: int, length: int):
#print(num)
"""
Converts integer to bit array
Someone fix this please :D - it's horrible
:param num: number to convert to bits
:param length: length of bits to convert to
:return: bit array
"""
if num >= 2**length:
num = 2**length - 1
if nu... |
def get_filesize_est(n_regions):
""" Get a filesize estimate given the number of regions in grid encoding.
Parameters
----------
n_regions: int
number of regions encoded by grid encoding
Returns
-------
float
Estimated filesize
"""
return 0.00636654 * n_regions... |
def sext(binary, bits):
"""
Sign-extend the binary number, check the most significant
bit
"""
neg = binary & (1 << (bits - 1))
if neg:
mask = 0
for i in range(bits, 16):
mask |= (0b1 << i)
return (mask | binary)
else:
return binary |
def zfp_precision_opts(precision):
"""Create a compression options for ZFP in fixed-precision mode
The float precision parameter is the number of uncompressed bits per value.
"""
zfp_mode_precision = 2
return zfp_mode_precision, 0, precision, 0, 0, 0 |
def schur_representative_from_index(i0, i1):
"""
Simultaneously reorder a pair of tuples to obtain the equivalent
element of the distinguished basis of the Schur algebra.
.. SEEALSO::
:func:`schur_representative_indices`
INPUT:
- A pair of tuples of length `r` with elements in `\{1,\... |
def get_qualified_name(_object):
"""Return the Fully Qualified Name from an instance or class."""
module = _object.__module__
if hasattr(_object, '__name__'):
_class = _object.__name__
else:
_class = _object.__class__.__name__
return module + '.' + _class |
def is_valid(x, y, grid, x_max, y_max):
"""Check the bounds and free space in the map"""
if 0 <= x < x_max and 0 <= y < y_max:
return grid[x][y] == 0
return False |
def keys_of(d):
"""
Returns the keys of a dict.
"""
try:
return list(d.keys())
except:
raise ValueError('keys_of(d) must be passed a dict') |
def sint(mixed, default=None):
"""Safe int cast."""
try:
return int(mixed)
except:
return default |
def quick_exponent_with_mod(base, power, modulo):
"""Compute quickly the exponent within a given modulo range.
Will apply a modulo with the specified base at every iteration of the
exponentiation algorithm, making sure the result is in the given range."""
# 'powers' will be a list of the base with powe... |
def list_to_string(list_to_convert):
"""
list_to_convert -> List that should be converted into string
e.g. '[1,2,False,String]'
returns string
"""
list_to_string = '['
for j in range(len(list_to_convert)):
list_to_string += str(list_to_convert[j]) + ','
# remove last ','
lis... |
def compute_U(Sigma_sfr, Sigma_g):
"""
Ionizaton parameter as a function of star formation and gas surface densities.
reference:
Eq. 38 Ferrara et al. 2019
inputs:
Sigma_sfr in Msun/yr/kpc^2
Sigma_g in Msun/kpc^2
"""
out= (1.7e+14)*(Sigma_sfr/(Sigma_g*Sigma_g))
return ou... |
def _coerce_ascii(c):
"""
coerce an ASCII value into the alphabetical range
"""
while True:
if c > 127: c -= 128
if c < 64: c += 64
if (c >= 65 and c <= 90) or (c >= 97 and c <= 122):
return c
c += 7 |
def status_8bit(inp):
"""
Return the status of each bit in a 8 byte status
"""
idx = 7
matches = {}
for num in (2 ** p for p in range(idx, -1, -1)):
if ((inp - num) > 0) or ((inp - num) == 0):
inp = inp - num
matches[idx] = True
else:
matches[... |
def query_url(namespace, cls_version,
extension=''):
"""
"""
url = 'https://kg.humanbrainproject.org/query/%s/%s/fg' %\
(namespace.lower(), cls_version)
return url+extension |
def prune_position(step):
"""Keep only ``left`` and ``top`` keys in step position."""
return {k: v for k, v in step.get('position', {}).items() if k in ('left', 'top')} |
def _header_name(channel_name: str, i_bin: int, unique: bool = True) -> str:
"""Constructs the header name for a column in a yield table.
There are two modes: by default the names are unique (to be used as keys). With
``unique=False``, the region names are skipped for bins beyond the first bin (for
les... |
def pack_message_other(code, data):
"""
Method by which other modules messages are (re-)packed
:param code: the code of the message
:param data: the data to pack
:return: dict, code and data
"""
b_data = bytes(data, 'ascii')
return {'code': code, 'data': b_data} |
def solution(N):
"""
DINAKAR
convert to binary and find gap by just knowing the entry of 1 and remember the last index of 1
also remember the longest in each iteration when 1 is encountered
"""
longest = -1
last_longest_index = 0
ar = bin(N).replace("0b", "")
print(ar)
for i in r... |
def get_item_safe(sequence, index=0, default=""):
"""
Retrives the item at index in sequence
defaults to default if the item des not exist
"""
try:
item = sequence[index]
except IndexError:
item = default
return item |
def merge_datasets(datasets):
""" Merge a list of datasets into one dataset """
dataset = datasets[0]
for i in range(1, len(datasets)):
dataset.extend(datasets[i])
return dataset |
def get_subdict(d, param):
"""
Get a subdictionary d : key -> value
in a dictionary of form d : key -> (d : param -> value)
"""
return dict([(key, d[key][param]) for key in d.keys()]) |
def check_correlation_method(method):
"""Confirm that the input method is currently supported.
Parameters
----------
method : str
The correlation metric to use.
Returns
-------
str
Correctly formatted correlation method.
"""
method = method.lower()
avail_metho... |
def get_label_from_iri_list(iri_list, iri2label_dict):
""" Helper for getting labels of a df with IRI lists as values using an iri2label dict"""
label_list = [iri2label_dict[iri] for iri in iri_list]
return label_list |
def StripComments(lines):
"""strip comments and empty lines
"""
result = []
found_comment = 0
for line in lines:
if not line.strip():
continue
if found_comment:
if line.startswith(" */"):
found_comment = 0
else:
if line.startswith(" //"):
continue
elif li... |
def _number(string):
"""
Extracts an int from a string.
Returns a 0 if None or an empty string was passed.
"""
if not string:
return 0
else:
try:
return int(string)
except ValueError:
return float(string) |
def next_month_is(year, month):
"""
Short function to get the next month given a particular month of interest
:param year: year of interest
:param month: month of interest
:type year: integer
:type month: integer
"""
next_year = year
next_month = month + 1
if next_month > 12... |
def example_func(parameter):
""" This is an example function """
try:
var = int(parameter)
result = var * var
except ValueError:
result = 'Nan'
return result |
def removeTags(fileStr):
"""
Removes all tags from the chat that start with '<xyz' and end with '</xyz'.
"""
current = 0
while True:
#print("Next char:",fileStr[current])
openAngleBracketIndex = fileStr.find('<',current)
if openAngleBracketIndex == -1:
... |
def class_ldap(log):
"""An error classifier.
log the console log text
Return None if not recognized, else the error type string.
"""
if 'failed to bind to LDAP server' in log:
return 'LDAP failure'
return None |
def array_chunk_loop(array, size):
"""Return an array containing chunks of the specified array with the specified size, using a loop."""
result = []
chunk = []
for i, value in enumerate(array):
chunk.append(value)
if len(chunk) == size or i + 1 == len(array):
result.append(ch... |
def flatten(data):
"""
Flatten a list/tuple/set of any nestedness.
"""
result = []
for item in data:
if isinstance(item, (tuple, list, set)):
result.extend(flatten(item))
else:
result.append(item)
return result |
def check_line_for_error(line,errormsg):
"""
Parse given line for VASP error code
Args:
line (string): error statement
Returns:
errormsg (string): VASP error code
"""
if 'inverse of rotation matrix was not found (increase SYMPREC)' in line:
errormsg.append('inv_rot_mat')
elif 'WARNING: Sub-Space-Matrix i... |
def auc(points):
"""Calulate the area under the curve using trapezoid rule."""
return sum((p[0]-lp[0])/100*(lp[1]+(p[1]-lp[1])/2.0)/100
for p, lp in zip(points[1:], points[:-1])) |
def learner_stats_id(ctr_info):
"""Assemble stats id."""
broker_id = ctr_info.get('broker_id')
explorer_id = ctr_info.get('explorer_id')
agent_id = ctr_info.get('agent_id')
return "_".join(map(str, (broker_id, explorer_id, agent_id))) |
def isSet(input):
"""
This function check input is a set object.
:param input: unknown type object
"""
return isinstance(input, set) |
def pascal_triangle(n):
"""pascal triangle"""
if (n <= 0):
return []
init = [[1]]
for i in range(1, n):
if (i == 1):
init.append([1, 1])
else:
init.append([0] * (i + 1))
init_point = 0
for num in range(i + 1):
if (nu... |
def fnSeconds_To_Hours(time_period):
"""
Convert from seconds to hours, minutes and seconds.
Date: 16 October 2016
"""
num_hrs = int(time_period/(60.*60.));
time_period =time_period - num_hrs*60.*60.;
num_mins = int(time_period/60.);
num_secs = time_period - num_mins*60.;
return... |
def with_subfolder(location: str, subfolder: str):
"""
Wrapper to appends a subfolder to a location.
:param location:
:param subfolder:
:return:
"""
if subfolder:
location += subfolder + '/'
return location |
def merge(dict1, dict2, def1, def2, func):
"""Merge two nested dictionaries, using default values when it makes sense"""
assert isinstance(dict1, dict)
assert isinstance(dict2, dict)
toReturn = {}
keys1 = set(dict1.keys())
keys2 = set(dict2.keys())
for key in keys1 | keys2: # change this ... |
def create_mute_list(time_list):
"""
Args:
subs (tuple): a list of tuples (start,end)
Returns:
"""
muteTimeList = []
for timePair in time_list:
lineStart = timePair[0]
lineEnd = timePair[1]
muteTimeList.append("volume=enable='between(t," + format... |
def is_convolution_or_linear(layer):
""" Return True if `layer` is a convolution or a linear layer
"""
classname = layer.__class__.__name__
if classname.find('Conv') != -1:
return True
if classname.find('Linear') != -1:
return True
return False |
def ngram(max_ngram_size: int, s1: str, s2: str, *,
weighted: bool = False, any_mismatch: bool = False, longer_worse: bool = False) -> int:
"""
Calculates how many of n-grams of s1 are contained in s2 (the more the number, the more words
are similar).
Args:
max_ngram_size: n in ngram
... |
def get_audio_args(name, data, sample_rate=None, step=None, **kwargs):
"""
Wrapper to parse args
"""
return (name, data, step, sample_rate) |
def _crossing(n_x, n_y, n, shift):
"""tells you if the shift crosses PBC in the x or why direction
:param n_x: system size in x
:type n_x: int
:param n_y: system_size in y
:type n_y: int
:param n: what index you are currently at
:type n: int
:param shift: whoch way you want to shift to
... |
def qmul(q1, q2):
"""
Return quaduple (4 tuple) result of quaternion multiplation of q1 * q2
Quaternion multiplication is not commutative q1 * q2 != q2 * q1
Quaternions q1 and q2 are sequences are of the form [w, x, y, z]
"""
w = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3]
... |
def build_placements(shoes):
""" (list of str) -> dict of {str: list of int}
Return a dictionary where each key is a company
and each value is a
list of placements by people wearing shoes
made by that company.
>>> result = build_placements(['Saucony', 'Asics', \
'Asics', 'NB... |
def get_path(obj, *keys):
"""Extract a value from a JSON data structure."""
for key in keys:
if not obj:
return obj
if isinstance(key, int):
try:
obj = obj[key]
except IndexError:
return None
elif isinstance(key, str):
... |
def decimal_to_string(decimal):
"""
"""
# Don't love this
problem_fractions = {0.13: "1/8", 0.67: "2/3", 0.33: "1/3"}
if decimal in problem_fractions:
return problem_fractions.get(decimal)
ratio = float(decimal).as_integer_ratio()
return "/".join(str(d) for d in ratio) |
def key_to_list(key):
"""make a list that contains primaryKey of this ingredient"""
return [x.strip() for x in key.split(',')] |
def formatannotation_fwdref(annotation, base_module=None):
"""the python 3.7 _formatannotation with an extra repr() for 3rd party
modules"""
if getattr(annotation, "__module__", None) == "typing":
return repr(annotation).replace("typing.", "")
if isinstance(annotation, type):
if annotat... |
def prod(iterator):
"""Product of the values in this iterator."""
p = 1
for v in iterator:
p *= v
return p |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.