content stringlengths 42 6.51k |
|---|
def c_to_f(celsius):
"""Converts Celsius to Fahrenheit
>>> c_to_f(0)
32.0
>>> c_to_f(5)
41.0
>>> c_to_f(-25)
-13.0
"""
"*** YOUR CODE HERE ***"
a = celsius * 9 / 5 + 32
return a |
def calc_time_cost_function_total(natom, nkpt, kmax, niter, nspins=1):
"""Estimates the cost of simulating a all iteration of a system"""
costs = natom**3 * kmax**3 * nkpt * nspins * niter
return costs |
def bounding_rect(polygon):
"""takes a polygon and returns a rectangle parallel to the axes"""
xs = [q[0] for q in polygon]
ys = [q[1] for q in polygon]
return [[min(xs), min(ys)], [max(xs), max(ys)]] |
def calculate_displacement(src_grammar, tgt_grammar):
"""Calculate displacement between 2 grammar. E.g: S -> A B C to S -> B C A has displacement of [1 2 0]"""
src_grammar_lst = src_grammar.split()
tgt_grammar_lst = tgt_grammar.split()
src_grammar_lst = src_grammar_lst[src_grammar_lst.index("->")+1... |
def merge(f_list):
"""Merge two polynomials into a single polynomial f.
Args:
f_list: a list of polynomials
Format: coefficient
"""
f0, f1 = f_list
n = 2 * len(f0)
f = [0] * n
for i in range(n // 2):
f[2 * i + 0] = f0[i]
f[2 * i + 1] = f1[i]
return f |
def all_pairs(items):
"""Make all unique pairs (order doesn't matter)"""
pairs = []
nitems = len(items)
for i, wi in enumerate(items):
for j in range(i+1, nitems):
pairs.append((wi, items[j]))
return pairs |
def tab(code, nb_tab=1):
"""add tabulation for each lines"""
space = ' '*4
indent_char = space * nb_tab
ret = []
for line in code.splitlines():
ret.append("%s%s" % (indent_char, line))
return '\n'.join(ret) |
def hash_string(keyword, buckets):
"""
Takes as its inputs a string and the number of buckets, b,
and returns a number between 0 and b - 1, which gives the
position where that string belongs.
"""
h = 0
for char in keyword:
h = (h + ord(char)) % buckets
return h |
def findRoot(x, power, epsilon):
""" Assumes x and epsilon int or float, power an int,
epsilon > 0 & power >= 1
Returns float y such that y**power is within epsilon of x.
If such a float does not exists, it returns None."""
if x < 0 and power % 2 == 0:
return None
low = min(... |
def mac_addr(address):
"""Convert a MAC address to a readable/printable string
Args:
address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06')
Returns:
str: Printable/readable MAC address
"""
return ':'.join('%02x' % ord(b) for b in address) |
def _decode_lut_config(raw_lut_string):
"""Extend a LUT string to one suitable for a 4-LUT.
If the input has less than four inputs it will be too sort and must
be extended so that no matter what the other inputs are set to,
it won't affect the output for the bits that matter.
"""
# We ... |
def _str_list_converter(argument):
"""
A directive option conversion function that converts the option into a list
of strings. Used for 'skip' option.
"""
if argument is None:
return []
else:
return [s.strip() for s in argument.split(',')] |
def clean_link_text(link_text):
""" The link text sometimes contains new lines, or extrananeous spaces, we
remove them here. """
return link_text.strip().replace('\n', '').replace('\r', '') |
def my_sum(arg):
"""
Sums the arguments and returns the sum.
"""
total = 0
for val in arg:
total += val
return total |
def format_input_source(input_source_name, input_source_number):
"""Format input source for display in UI."""
return f"{input_source_name} {input_source_number}" |
def matrixify(string_grid, separator='\n'):
"""Return a matrix out of string_grid.
Args:
string_grid (str): A string containing non-whitespace and whitespace characters.
separator (str): A whitespace character used in string_grid.
Returns:
list: Returns list of the strings of strin... |
def _compare_ranges(range1, range2, epsilon=1e-3):
"""Returns true if the both range are close enough (within a relative epsilon)."""
if not range1[0] or not range2[0]:
return False
return abs(range1[0] - range2[0]) < epsilon and abs(range1[1] - range2[1]) < epsilon |
def bounce(function, *args):
"""Returns a new trampolined value that continues bouncing on the
trampoline."""
return ('bounce', function, args) |
def get_mirror_giturl(submod_name):
"""Gets the submodule's url on mirror server.
Retrurn the download address of the submodule on the mirror server from the submod_name.
"""
mirror_url = 'https://gitee.com/RT-Thread-Mirror/submod_' + submod_name + '.git'
return mirror_url |
def toDataRange(size, r = all):
"""Converts range r to numeric range (min,max) given the full array size
Arguments:
size (tuple): source data size
r (tuple or all): range specification, ``all`` is full range
Returns:
tuple: absolute range as pair of integers
... |
def get_min_and_max_coords_from_exon_chain(coords):
"""Gets the minumum and maximum coordinates from exon chain
Args:
coords ([[int, int]]): [[start,end]] exon coordinate chain
Returns:
(int, int): start and end coordinates of entire chain
"""
min_coord = min(map(min, ... |
def zigzagLevelOrder(root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res, temp, stack, flag = [], [], [root], 1
while stack:
for i in range(len(stack)):
node = stack.pop(0)
temp += [node.val]
if node.left:... |
def _validate_x_and_y(x, y):
"""
Validate input data.
"""
if x is None or y is None:
raise TypeError("x and y cannot be of NoneType")
return x, y |
def get_label_yml(label):
"""Get yml format for label
Args:
label (dict): dictionnary if labels with keys color, name and description
as strings, possibly empty
Returns:
str: yml formatted dict, as a yml list item
"""
text = f' - name: "{label["name"]}"\n'
text += f' ... |
def is_cache_enabled(cache_config):
# type: (str) -> bool
""" Check if the cache is enabled.
:param cache_config: Cache configuration defined on startup.
:return: True if enabled, False otherwise. And size if enabled.
"""
if ":" in cache_config:
cache, _ = cache_config.split(":")
... |
def fact_recur(n):
"""assumes n >= 0 """
if n <= 1:
return 1
else:
return n * fact_recur(n - 1) |
def float_round(num, n):
"""Makes sure a variable is a float and round it at "n" decimals
Args:
num (str, int, float): number we want to make sure is a float
n (int): number of decimals
Returns:
num (float): a float rounded number
"""
num = float(num)
num = round(num, n... |
def navamsa_from_long(longitude):
"""Calculates the navamsa-sign in which given longitude falls
0 = Aries, 1 = Taurus, ..., 11 = Pisces
"""
one_pada = (360 / (12 * 9)) # There are also 108 navamsas
one_sign = 12 * one_pada # = 40 degrees exactly
signs_elapsed = longitude / one_sign
fraction_left = sig... |
def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2)) |
def parse_program(lines):
"""Parse program from lines."""
return [[int(num) for num in line.strip().split()]
for line in lines.strip().split('\n')] |
def cipher(text, shift, encrypt=True):
"""
Encrypting or deecrpting using Caesar cipher.
Parameters
----------
text : str
The contents to be encrypted or decrypted
shift : int
A fixed number of positions that each letter in text is shifted down (positive) or up (negative)
encryp... |
def humanbytes(size):
"""Input size in bytes,
outputs in a human readable format"""
if not size:
return ""
# 2 ** 10 = 1024
power = 2 ** 10
raised_to_pow = 0
dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"}
while size > power:
size /= power
raised_to_pow... |
def parse_rest_create_list_response(resp):
"""Split the response from the REST API lines
into columns
Args:
resp (string): [description]
Returns:
[rest_response_object]: [description]
"""
rest_responses = []
lines = resp.splitlines()
del lines[0:2]
for line in lines... |
def get_steps(length, input_dimension, output_dimension):
"""Calculates each step along a dimension of the tile.
length is the total length of the dimension, model resolution
is the detector's expected input length, and padding is the model's
required padding (zero if none.)
"""
steps = []
p... |
def check_long_form(doc, alice_mapping):
"""
usage: get the mapping b/w long_form: short form for each document
input: take the document in
output: return the matching short_form: long_form
"""
try:
long_name = alice_mapping[doc]
except:
long_name = dict()
return long_na... |
def strip_keys(key_list):
""" Given a list of keys, remove the prefix and remove just
the data we care about.
for example:
['defender:blocked:ip:ken', 'defender:blocked:ip:joffrey']
would result in:
['ken', 'joffrey']
"""
return [key.split(":")[-1] for key in key_list] |
def convert_predictions_to_str_set(predictions):
""" Helper method to convert predictions into readable text strings """
return {x.text + "_" + x.label_ for x in predictions} |
def ot2bio_ate(ate_tag_sequence):
"""
ot2bio function for ate task
"""
n_tags = len(ate_tag_sequence)
new_ate_sequence = []
prev_ate_tag = '$$$'
for i in range(n_tags):
cur_ate_tag = ate_tag_sequence[i]
if cur_ate_tag == 'O' or cur_ate_tag == 'EQ':
# note that, EQ... |
def error_running_file(filename, section, error):
"""returns a string in log format if a module errors out"""
file_error = "ty_error_running_file=%s" % (filename, )
section_error = "ty_error_section=%s" % (section, )
error_message = "ty_error_message=%r" % (error, )
return " ".join([
file_e... |
def pmelt_T_iceIh(T):
"""
EQ 1 / Melting pressure of ice Ih
"""
T_star = 273.16
p_star = 611.657E-6
theta = T / T_star
a = (0.119539337E7, 0.808183159E5, 0.333826860E4)
b = (0.300000E1 , 0.257500E2, 0.103750E3)
sum = 0
for i in range(0, 3):
sum += a[i] * (1 - theta *... |
def partition(f, xs):
"""
Works similar to filter, except it returns a two-item tuple where the
first item is the sequence of items that passed the filter and the
second is a sequence of items that didn't pass the filter
"""
t = type(xs)
true = filter(f, xs)
false = [x for x in x... |
def __filter_assets(catalogs, attachments):
"""
Separate series from episode assets.
:param catalogs: All catalogs
:type: list
:param attachments: All attachments
:type attachments: list
:return: Episode catalogs, episode attachments, series catalogs, series attachments
:rtype: list, li... |
def filter_cmd(cmd):
"""Remove some non-technical option strings from `cmd`, which is assumed to
be a string containing a shell command.
"""
cmd = cmd.replace(' -outputname /dev/null', '')
cmd = cmd.replace(' -q', '')
return cmd |
def prep_violations(rule, violations):
"""Default to test rule if code is omitted."""
for v in violations:
if "code" not in v:
v["code"] = rule
return violations |
def getOrderedDict(keys,keysid):
"""Get ordered dict"""
from collections import OrderedDict
d = OrderedDict()
for i in keysid:
d[keys[i]] = []
return d |
def round_channels(channels,
divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns
-------
... |
def check_empty(string: str, delimiter: str = ' '):
"""Check if string represents dirty data"""
string_list = string.split(delimiter)
check = 0
for string in string_list:
if len(string) < 3:
check += 1
if check == len(string_list):
string = 'None'
else:
... |
def jamify(s):
"""
Convert a valid Python identifier to a string that follows Boost.Build
identifier convention.
"""
return s.replace("_", "-") |
def decode_transaction_filter(metadata_bytes):
"""Decodes transaction filter from metadata bytes
Args:
metadata_bytes (str): Encoded list of transaction filters
Returns: decoded transaction_filter list
"""
transaction_filter = []
if not metadata_bytes:
return None
for i in... |
def centerOfMassMotion(*args):
"""input: [m, vx, vy, vz, vr]
variables: m=mass,
vx=velocity-along-x,
vy=velocity-along-y,
vz=velocity-along-z,
vr=velocity-along-radius"""
mi=0; vxi=1; vyi=2; vzi=3; vri=4
m_total = sum([item[m... |
def interval(lower_, upper_):
"""Build an interval."""
if lower_ <= upper_:
return lower_, upper_
return None |
def parse_grid(data):
"""Parses the string representation into a nested list"""
return data.strip().split('\n') |
def getReverseConnectivity(connectivity):
"""getReverseConnectivity(connectivity) -->
resort connectivity dict with nodes as keys"""
reverseConnectivity = {}
for el, conn in connectivity.items():
for node in conn:
if node not in reverseConnectivity.keys():
reverseC... |
def _strip_object(key):
"""
Strips branch and version info if the given key supports those attributes.
"""
if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'):
return key.for_branch(None).version_agnostic()
else:
return key |
def first(iterable, default=None, key=None):
"""
Return first element of `iterable` that evaluates true, else return None
(or an optional default value).
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], def... |
def pluralize(word, quantity, suffix=None, replacement=None):
"""Simplistic heuristic word pluralization."""
if quantity == 1:
return word
if replacement:
return replacement
if suffix:
return '%s%s' % (word, suffix)
return '%ss' % word |
def get_month(day_str):
"""
UTILITY FUNCTION
takes the day date (str) and returns its month.
"""
month_dict = {'01':'january',
'02':'february',
'03':'march',
'04':'april',
'05':'may',
'06':'june',
... |
def _split_classes_into_list(name):
"""This dataset provides the classes via a | in the str to signify an or for BCE."""
classes = name.split("|")
if len(classes) < 1:
return [name] # base case
return classes |
def extract(data, ids, default=None):
"""
inputs:
data: hierarchical data structure consisting of lists, dicts, and objects with attributes.
ids: a list of idices, key names, and attribute names
default: optional object
output:
the value stored at the location indicated by th... |
def transcode_bytes(data, encoding):
"""
Re-encodes bytes to UTF-8.
"""
return data.decode(encoding).encode() |
def wafv2_custom_body_response_content_type(content_type):
"""validate wafv2 custom response content type"""
valid_types = ["APPLICATION_JSON", "TEXT_HTML", "TEXT_PLAIN"]
if content_type not in valid_types:
raise ValueError('ContentType must be one of: "%s"' % (", ".join(valid_types)))
return co... |
def get_class(kls):
"""
Converts a string to a class.
Courtesy:
http://stackoverflow.com/q/452969/#452981
"""
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m |
def _SubtractCpuStats(cpu_stats, start_cpu_stats):
"""Computes average cpu usage over a time period for different process types.
Each of the two cpu_stats arguments is a dict with the following format:
{'Browser': {'CpuProcessTime': ..., 'TotalTime': ...},
'Renderer': {'CpuProcessTime': ..., 'TotalTim... |
def get_snmp_server_config_name(config, name):
"""
:param config:
:param name:
:return:
"""
try:
config[name]
server_config_name = name
except KeyError as exception:
server_config_name = 'common'
return server_config_name |
def get_swagger_version(obj):
""" get swagger version from loaded json """
if isinstance(obj, dict):
if 'swaggerVersion' in obj:
return obj['swaggerVersion']
elif 'swagger' in obj:
return obj['swagger']
return None
else:
# should be an instance of Bas... |
def zip_check(file_path, compression_type):
"""
Check if the file suffix or the compression type indicates that it is
a zip file.
"""
if file_path:
if file_path.split('/')[-1].split('.')[-1] == 'zip':
return True
if compression_type == 'zip':
return True
else:
... |
def strip_whitespace(string):
"""
Converter to strip whitespace from a provided string.
"""
return string.strip() |
def filtra_lista_request_vars(requestvars,clave):
"""Sirve para limpiar listas que se forman en request.vars con algunas variables que se ponen en el GEt y en el POST
devuelve
"""
if clave in requestvars:
if isinstance(requestvars[clave],(list,tuple)):
requestvars[clave]=requestvars... |
def filter_old_translation_sheets(spreadsheet_names,current_translation_regex,old_translation_regex,languages_to_translate):
""" Removes the old translation sheets from the data model.
Arguments:
spreadsheet_names {[list]} -- [List of the spreadsheet names found in the Translation folder.]
current_translati... |
def _modcell(cell_in):
"""Modify the cell"""
out = []
for line in cell_in:
out.append(line.replace(' C ', ' Si '))
return out |
def pKa_mod(resName):
"""
definitions of min distance
"""
pKa_mod = {'C- ': 3.20,
'ASP': 3.80,
'GLU': 4.50,
'HIS': 6.50,
'CYS': 9.00,
'TYR':10.00,
'LYS':10.50,
'ARG':12.50,
'N+ ':... |
def get_agents_with_name(name, stmts):
"""Return all agents within a list of statements with a particular name."""
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] |
def _decode_attribute_map_key(key):
"""This decode a key in an _attribute_map to the actual key we want to look at
inside the received data.
:param str key: A key string from the generated code
"""
return key.replace('\\.', '.') |
def calc_radiated_power_nadir(radiance_integrated,
pixel_resolution_along,
pixel_resolution_cross):
"""
Calculate the power radiated from a ground pixel at Nadir.
Returns
-------
double : Watts per Sterradian.
"""
return radiance_... |
def sort_array_for_min_number(nums):
"""
:param nums: int list
:return: min number string
"""
from functools import cmp_to_key
# def cmp(a, b):
# return -1 if a + b < b + a else 1
nums = [str(i) for i in nums]
# nums.sort(key = cmp_to_key(cmp))
nums.sort(key = cmp_to_key(lamb... |
def clear_low_information_words(message):
"""
Remove links from messages
:param message:
:return: message
"""
output = []
for word in message.split():
# remove links, as they contain no real conversation info and cannot be stemmed
if not word.startswith('http'):
... |
def clean_reg_name(reg, list):
"""
Clean the name of the registers by removing any characters contained in
the inputted list.
"""
for char in list:
reg = reg.replace(char, '')
return reg |
def module_level_function(param1, param2=None, *args, **kwargs):
"""Evaluate to true if any paramaters are greater than 100.
This is an example of a module level function.
Function parameters should be documented in the ``Parameters`` section.
The name of each parameter is required. The type and descr... |
def _add_value_squared_where_missing(row):
"""Add values `value_squared` where missing."""
value_squared = row[-2]
value = row[-3]
if value_squared != value_squared:
return value
else:
return value_squared |
def _compute_f_pre_rec(beta_square, tp, fn, fp):
"""
:param tp: int, true positive
:param fn: int, false negative
:param fp: int, false positive
:return: (f, pre, rec)
"""
pre = tp / (fp + tp + 1e-13)
rec = tp / (fn + tp + 1e-13)
f = (1 + beta_square) * pre * rec / (beta_square * pr... |
def state_ocd_id(state):
"""Get the OCD ID of the state
Returns the state OCD ID, which can be used both alone and as a prefix
Args:
state: state CD (uppercase)
Returns:
OCD ID of the state
string
"""
if state == 'DC':
state_id = 'ocd-division/country:us/distri... |
def q_prior(q, m=1, gamma=0.3, qmin=0.1):
"""Default prior on mass ratio q ~ q^gamma
"""
if q < qmin or q > 1:
return 0
C = 1/(1/(gamma+1)*(1 - qmin**(gamma+1)))
return C*q**gamma |
def calculate_reindeer_run(reindeer, duration):
"""Calculate distance travelled by reindeer in specified duration"""
# get reindeer stats
flight_speed = reindeer['flight_speed']
flight_duration = reindeer['flight_duration']
rest_period = reindeer['rest']
# get number of rounds reinder flies an... |
def common_start(*strings):
""" Returns the longest common substring
from the beginning of the `strings`
"""
if len(strings)==1:
strings=tuple(strings[0])
def _iter():
for z in zip(*strings):
if z.count(z[0]) == len(z): # check all elements in `z` are the same
... |
def process_documents(articles):
"""Process articles and returns it in dictionary format
Parameters
----------
articles : list of str
List of articles dictionaries
Returns
-------
dicts_textContent : dict
Dictionary containing the required structure used by the models:
... |
def str_signature(sig):
""" String representation of type signature
>>> from sympy.multipledispatch.dispatcher import str_signature
>>> str_signature((int, float))
'int, float'
"""
return ', '.join(cls.__name__ for cls in sig) |
def get_first_animal_recordings(all_recordings, animal):
"""Returns the first animal Recordings instance from a list of Recordings instances
:param list all_recordings: list of :py:class:`recording_io.Recordings` instances
:param str animal: value to look for in Recordings[0].info['animal']
:return: re... |
def parse_error_msg(orig_msg):
"""
Parse "error" message received from backend
Format:
"error: %s\r\n"
"""
error = orig_msg[7:]
return "error", error |
def venus_rot_elements_at_epoch(T, d):
"""Calculate rotational elements for Venus.
Parameters
----------
T: float
Interval from the standard epoch, in Julian centuries.
d: float
Interval in days from the standard epoch.
Returns
-------
ra, dec, W: tuple (float)
... |
def check_abc_lec_status(output):
"""
Reads abc_lec output and determines if the files were equivelent and
if there were errors when preforming lec.
"""
equivalent = None
errored = False
for line in output:
if "Error: The network has no latches." in line:
errored = True
... |
def psc(x, size_ratio, ref_cost):
"""
Returns: Cost of a power-sizing model estimate as per the formula:
tcost = ( size_ratio)^x * ref_cost
"""
return ref_cost * size_ratio ** x |
def _get_iterator_device(job_name, task_id):
""" Returns the iterator device to use """
if job_name != 'learner':
return None
return '/job:%s/task:%d' % (job_name, task_id) |
def calculate_tax(income_tax_spec, taxable_income):
"""Calculate household tax payments based on total household taxable income weekly"""
tax_base = taxable_income - income_tax_spec[0]
if taxable_income < income_tax_spec[0]:
tax_rate = 0
elif (taxable_income >= income_tax_spec[0]) and (
... |
def dictvals(dictionary):
"""
Returns the list of elements in a dictionary, unpacking them if they are inside a list
:param dictionary: the dictionary to be unpacked
:returns :[list]
"""
try:
return [x[0] for x in dictionary.values()]
except IndexError:
return list(dictionary... |
def ref_seq_nt_output(in_seq_name, in_ref_name, nt, ext):
"""
Generate output file name
:param in_seq_name: treatment name (str)
:param in_ref_name: reference name (str)
:param nt: aligned read length (int)
:param ext: extension (ie. csv or pdf)
:return: output filename (str)
"""
ret... |
def get_display_name(user):
"""
Tries to return (in order):
* ``user.profile.display_name``
* ``user.username``
"""
if user is None:
return None
profile = user.profile
if profile.display_name:
return profile.display_name
return user.username |
def above_threshold(student_scores, threshold):
"""Determine how many of the provided student scores were 'the best' based on the provided threshold.
:param student_scores: list - of integer scores.
:param threshold: int - threshold to cross to be the "best" score.
:return: list - of integer scores tha... |
def flatten_index(index: tuple, shape: tuple) -> int:
""" Unravel index
Convert flatten index into tuple index.
Parameters
----------
index: tuple
index (x, y)
shape: tuple
shape of matrix the flatten index is about
Returns
-------
index: int64
flatten inde... |
def get_board_config(json_data: dict) -> str:
"""Return boardconfig of said device"""
return json_data["boardconfig"] |
def ShardedFilePatternToGlob(file_pattern):
"""Converts a file pattern path@shards to path-?????-of-shards."""
if ',' in file_pattern:
raise ValueError(
'ShardedFilePatternToGlob does not support multiple file patterns.')
if '@' not in file_pattern:
return file_pattern
path, shards = file_patter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.