content stringlengths 42 6.51k |
|---|
def calc_cycle_energy_forced_year(timestep, array_cycle_flex_forced):
"""
Calculate cycle energy flexibility for whole year (with forced operation)
Parameters
----------
timestep : int
Timestep in seconds
array_cycle_flex_forced : np.array
Array holding cycle flexibility power v... |
def get_normalized_distance (pair,s_pronoun) :
"""Normalized distance: if the antecedent and the mention are the same sentence normalize, otherwise 0"""
if pair[2] == pair[3] :
distance = abs(int(pair[1][2]) - int(pair[0][2]))
return round(distance / len(s_pronoun), 3)
return 0 |
def clean_candidates_id_list(candidates, known_ids):
"""Filter already known properties."""
new_elements = []
for candidate in candidates:
if not candidate['id'] in known_ids:
new_elements.append(candidate)
return new_elements |
def get_X_P(dfp):
"""Get the parameter values for each model run"""
lists = [d for d in dfp['values']]
return list(zip(*lists)) |
def retrieve_variable_to_cgpm(cgpms):
"""Return map of variable v to its index i in the list of cgpms."""
return {v:i for i, c in enumerate(cgpms) for v in c.outputs} |
def strip_html(base):
"""Strip html tags from a string"""
import re
# use html parser?
return re.sub(r'<[^>]+>', '', base) |
def clamp(value, min_value=0.0, max_value=1.0):
"""Clamps a value between a minimum and maximum value.
Similar to ``numpy.clip`` but is faster for non-array
:param value: number to clamp
:type value: float
:param min_value: maximum value
:type min_value: float
:param max_value: minimum valu... |
def cartesian_list(lst1, lst2):
"""lst1 and lst2 should be iterative"""
return [(l1, l2) for l1 in lst1 for l2 in lst2] |
def is_integer(x):
"""Any integer value"""
try:
return float(x).is_integer()
except ValueError:
return False |
def CanLen(input):
"""
Return whether it is valid to call len on the supplied input
"""
try:
len(input)
return True
except TypeError:
return False |
def get_masks(tokens, max_seq_length):
"""Mask for padding"""
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens) + [0] * (max_seq_length - len(tokens)) |
def get_unique_vals(tbl, col_num):
"""
returns a set of unique values in col_num of tbl
"""
vals = []
for r in tbl[1:]:
vals.append(r[col_num])
return list(set(vals)) |
def merge_dicts(x, y):
"""Returns a copy of y merged into x."""
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z |
def generate_url(coverage_pct: float) -> str:
"""Generate badge source URL."""
color = "yellow"
if coverage_pct == 100:
color = "brightgreen"
elif coverage_pct > 90:
color = "green"
elif coverage_pct > 70:
color = "yellowgreen"
elif coverage_pct > 50:
color = "yel... |
def select_comment_blocks(file_content, comment_blocks, condition):
"""
For a block comment, search the ones that match the condition
The condition is a term that should be retrieved or not in the comment
blocks defined by comment_blocks
Return a set containing the tuples in comment... |
def ismatch(t1, t2, first=False):
"""
return if t1 contains t2
"""
len_t1, len_t2 = len(t1), len(t2)
for i in range(0, len_t1-len_t2+1):
if t1[i:i+len_t2] == t2:
return True
if first:
break
return False |
def QLineEdit_parseVectors(lineedit):
"""
Return one or more component real vector as list from comma separated text in QLineEdit widget
or None if invalid.
"""
try:
text = lineedit.text()
values = [ float(value) for value in text.split(",") ]
return values
except:
... |
def _norm_text_angle(a):
"""Return the given angle normalized to -90 < *a* <= 90 degrees."""
a = (a + 180) % 180
if a > 90:
a = a - 180
return a |
def align_up(bytes, alignment):
"""Rounds bytes up to nearest alignment."""
return (int(bytes) + int(alignment) - 1) / int(alignment) * int(alignment) |
def is_numeric(value=''):
"""
Check if the value is numeric.
Parameters
----------
value : str
Value to check.
Returns
-------
boolean
Whether the value is numeric.
"""
if isinstance(value, str):
try:
float(value) if '.' in value else int(val... |
def check_fields(dict1, dict2):
"""Check all fields of dict1 is in dict2
:param dict1: dict, first dictionary
:param dict2: dict, second dictionary
:return: boolean
"""
for key, value in dict1.items():
if isinstance(value, dict):
if not isinstance(dict2.get(key), dict):
... |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured to conform to the schema.
"""
# no further processing
return proc_data |
def isnum(x, others=None):
"""
Returns True if x is an int or float of one of the
other number types passed in (e.g. Fraction, complex).
"""
if isinstance(x, (int, float)):
return True
if others:
return isinstance(x, others)
return False |
def acrostic(items):
"""
Take the acrostic of a list of words -- the first letter of each word.
"""
return ''.join([item[0] for item in items]) |
def _without_keys(dict_data, keyz):
"""
Removes elements from a (copy of a) dictionary.
:param dict_data: the dictionary to remove entries from.
:param keyz: the keys to remove from the dictionary.
:return: a new dictionary withiout the intended keys.
"""
cleaned_data = dict_data.copy()
... |
def cns_dihedral_restraint(resid_i, atom_i, resid_j, atom_j,
resid_k, atom_k, resid_l, atom_l,
energy_constant, degrees, range,
exponent, comment=None):
"""
Create a CNS dihedral angle restraint string
Parameters
---------... |
def convert_pid(value):
"""Convert pid from hex string to integer."""
return int(value, 16) |
def serialize_none(x):
"""Substitute None with its string representation."""
return str(x) if x is None else x |
def MinMaxAvg(data):
"""
Given a list of values, the MIN/MAX/AVG value is returned in a Dictionary
:param data: List of data of the same kind
:type data: int[] or float[]
:returns: a dictionary { 'min':min,'max':max,'avg':average }
:rtype: dictionary
.. seealso:: Stats
"""
min_val = data[0]... |
def fibonacci(n):
"""Returns fibonnaci number n.
See http://en.wikipedia.org/wiki/Fibonacci_number.
>>> print(fibonacci.cache)
{}
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(10)
55
>>> fibonacci.cache[10]
55
>>> fibonacci(40)
102334155
"""
assert... |
def restructure_allele_freq_info(allele_annotations):
"""Restructure information related to allele frequency
"""
alleles_data = []
for _annotation in allele_annotations:
freq_data = _annotation.get('frequency')
if freq_data:
freq = {'freq': {}}
freq_data = list(fr... |
def get_iscsi_portal(hostname, port):
"""Get iscsi portal info from iXsystems FREENAS configuration."""
return "%s:%s" % (hostname, port) |
def version_to_string(version):
"""
Create a version string from tuple.
"""
return '{}.{}.{}.{}'.format(version[0], version[1], version[2], version[3]) |
def getSuffixFromNuclideLabel(nucLabel):
"""
Return the xs suffix for the nuclide label.
Parameters
----------
nucLabel: str
A string representing the nuclide and xs suffix, eg, "U235AA"
Returns
-------
suffix: str
The suffix of this string
"""
retu... |
def Align4(i):
"""Round up to the nearest multiple of 4. See unit tests."""
return ((i-1) | 3) + 1 |
def shortest_path(graph, start, end, path=[]):
"""Find the shortest path between two nodes.
Uses recursion to find the shortest path from one node to another in an
unweighted graph.
Adapted from http://www.python.org/doc/essays/graphs.html
:param graph: a mapping of the graph to analyze, of the f... |
def is_none_p(value):
"""Return True if value is None"""
print("is_none_p", value)
return value is None |
def delete(flavor_id, **kwargs):
"""Delete flavor."""
# NOTE: flavor_id can be any string, don't convert flavor name to uuid
url = '/flavors/{flavor_id}'.format(flavor_id=flavor_id)
return url, {} |
def time_to_str(time_min:str, time_max:str):
"""
Replace ':' to '-' from the time variables.
Parameters
----------
time_min: str
Time variable with ':'.
time_max: str
Time variable with ':'.
Returns
-------
time_min_str: str
Time vari... |
def add_fictional_bindings_with_initial_objects(obj_into_name,zep_last_conf):
"""
this function modifies the final configuraiton to allow bindings with initial objects
"""
for j in zep_last_conf["bindings"]:
if (j["provider"] in obj_into_name) or (j["requirer"] in obj_into_name):
j["nu... |
def _command(register_offset, port_number, register_type):
"""Return the command register value corresponding to the register type for a given port number and register offset."""
return (register_offset * register_type) + port_number |
def false_position(f, x0, x1, y0, y1, x, yval, xtol, ytol):
"""False position solver."""
_abs = abs
if y1 < 0.: x0, y0, x1, y1 = x1, y1, x0, y0
dx = x1-x0
dy = yval-y0
if not (x0 < x < x1 or x1 < x < x0):
x = x0 + dy*dx/(y1-y0)
yval_ub = yval + ytol
yval_lb = yval - ytol
x_ol... |
def check_for_fields_to_keep(term, dbterm):
""" see if is_slim_for present and check if preferred_name is different from
term_name in dbterm if so add to term
"""
if 'is_slim_for' in dbterm:
term['is_slim_for'] = dbterm['is_slim_for']
if 'preferred_name' in dbterm: # should alwawys be t... |
def to_years_and_months(months):
"""
Convert a integer value into a string of years and months e.g.
27 would be represented as '2 Years 3 Months'
"""
whole_years = months // 12
remaining_months = months % 12
result = ''
if whole_years >= 1:
if whole_years == 1:
result... |
def make_rev_comp(s):
"""
Generates reverse comp sequences from an input sequence.
"""
return s[::-1].translate(s[::-1].maketrans("ACGT", "TGCA")) |
def get_prefix_less_dict(elements):
""" Returns a dict containing each element with a stripped prefix
This Function will return a dict that contains each element resulting on
the element without the found prefix
:param elements: List of all your shapes
:type group: list
:return: The matching ... |
def _emscripten_urls(path):
"""
Produce a url list that works both with emscripten, and stripe's internal artifact cache.
"""
return [
"https://storage.googleapis.com/webassembly/emscripten-releases-builds/old/{}".format(path),
"https://artifactory-content.stripe.build/artifactory/google... |
def calc_fuel(mass):
""" divide by three, round down, and subtract 2 """
return mass // 3 - 2 |
def reward(s, a, utility, cost):
"""
Reward as a function of the true state and the price of action
"""
# return [1,0.6,0.3,0][s]
# return [1,0.6,0.3,0][s] - [0.05, 0.5][a]
return utility[s] - cost[a] |
def shortest_torus_path_length(source, destination, width, height):
"""Get the length of a shortest path from source to destination using
wrap-around links.
See http://jhnet.co.uk/articles/torus_paths for an explanation of how this
method works.
Parameters
----------
source : (x, y, z)
... |
def find_in_inventory_index(invt, pid):
""" Returns the index from inventory item matching pid """
def binary_search(invt, value):
low = 0
high = len(invt)-1
while low <= high:
mid = (low + high)//2
if invt[mid].pid > value: high = mid-1
elif invt[mi... |
def isodd(num):
"""check if a number is odd"""
return num & 1 and True or False |
def trunc(s, length=-1, strip=True, ellipsis=False, convert_to_none=True):
"""
Truncates a string to the given length. If strip is
true then also strips the string. If ellipsis is true then
ellipsis are added to the end of the string.
"""
if not s:
if convert_to_none and s is not None:
... |
def _filter_typos(typos, char_vocab):
"""
Filters typos that contain out of the alphabet symbols
"""
new_typos = dict()
for key,values in typos.items():
new_values = list()
for v in values:
invalid_chars = [c for c in v if c not in char_vocab... |
def get_neighbour_squares(square, square_to_edges, edge_to_squares):
"""Get squares that are neighbours - have one matching edge."""
neighbour_squares = []
for square_edge in square_to_edges[square]:
squares_with_edge = edge_to_squares[square_edge]
if len(squares_with_edge) > 1:
... |
def parse_char(ch):
"""
'A' or '\x41' or '41'
"""
if len(ch) == 1:
return ord(ch)
if ch[0:2] == "\\x":
ch = ch[2:]
if not ch:
raise ValueError("Empty char")
return ord(chr(int(ch, 16))) |
def replace_spaces(text):
"""
Replace spaces with a dash.
"""
if not isinstance(text, str):
return text
return text.replace(" ", "-") |
def parse_count(cell_value):
"""
Parse Halias data cell value to integer.
"""
if cell_value.startswith('"') and cell_value.endswith('"'):
cell_value = cell_value[1:-1]
if len(cell_value) > 0:
cell_value = int(cell_value)
else:
cell_value = None
return cell_value |
def fmt(text):
"""used specially for badge fields"""
special = ["-", " "]
for i in special:
text = text.replace(i, "_")
return text |
def check_for_duplicate_ranges(range_list):
"""Return True if the given list of tuples contains duplicates.
"""
non_redun_range_list = list(set(range_list))
x = None
if len(non_redun_range_list) < len(range_list):
x = True
else:
x = False
return x |
def should_exclude(base_path, repo_path):
"""Check wither a repo should be excluded in a given rsync"""
if base_path == repo_path:
return False
if not base_path:
return True
if repo_path.startswith(base_path + "/"):
return True
return False |
def list_item_html(text: str) -> str:
"""Embed text in list element tag."""
return "<li>{}</li>".format(text) |
def check_tab(tab):
"""Check that translation table chosen is valid"""
if tab is None:
tab = 1
else:
if int(tab) in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33]:
tab = int(tab)
else:
print('User Error: Chose... |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length,
False otherwise.
"""
for row in board:
row = row[1:][:-1].replace("*", "")
for num in row:
if row.count(num) > 1:
... |
def add_timeout(cmd, timeout_secs):
"""Adds a timeout to a command using linux's (gnu) /bin/timeout."""
return ['timeout', str(timeout_secs)] + cmd |
def inv_gaussian_variance(mu, lam):
"""
As in https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
@param mu: the expectation
@param lam: lambda in Wikipedia's notation
@return: Var[X]
"""
return mu ** 3 / lam |
def rgb2hex(rgb):
"""To convert the RGB values to HEX."""
clamp = lambda x: max(0, min(x, 255))
return f"#{clamp(rgb[0]):02x}{clamp(rgb[1]):02x}{clamp(rgb[2]):02x}" |
def _escape_using_hex(char):
"""Use hex digits to escape the character."""
codepoint = ord(char)
if codepoint > 0xFFFF:
return u'\\U{:08x}'.format(codepoint)
return u'\\u{:04x}'.format(codepoint) |
def key2hump(key):
"""
try to capitalize the underscore
:param key:
:type key:
:return:
:rtype:
"""
return key.title().replace("_", "") |
def secs_to_str(secs):
"""Given number of seconds returns, e.g., `02h 29m 39s`"""
units = (('s', 60), ('m', 60), ('h', 24), ('d', 7))
out = []
rem = secs
for (unit, cycle) in units:
out.append((rem % cycle, unit))
rem = int(rem / cycle)
if not rem:
break
if re... |
def union_exprs(La, Lb):
"""
Union two lists of Exprs.
"""
b_strs = set([node.unique_str() for node in Lb])
a_extra_nodes = [node for node in La if node.unique_str() not in b_strs]
return a_extra_nodes + Lb |
def severity_string(severity, mapping={
-300: 'TRACE',
-200: 'DEBUG',
-100: 'BLATHER',
0: 'INFO',
100: 'PROBLEM',
200: 'ERROR',
300: 'PANIC'}):
"""Convert a severity code to a string."""
s = mapping.get(int(severity), '')
return "%s(%s)" % (s, severity... |
def _annotation_packet(annotations, action):
"""
Generate a packet suitable for sending down the websocket that represents
the specified action applied to the passed annotations.
"""
return {
'payload': annotations,
'type': 'annotation-notification',
'options': {'action': act... |
def _printable_string(string, max_len=80):
"""
:param string: string
:param max_len: maximum length
:return: printable version of the given string adhering to the maximum length
"""
if max_len < 3:
raise ValueError("max_len is {0}, must be at least 3".format(max_len))
repred_str = re... |
def enforce_10ch_limit(names):
"""Enforce 10 character limit for fieldnames.
Add suffix for duplicate names starting at 0.
Parameters
----------
names : list of strings
Returns
-------
names : list of unique strings of len <= 10.
"""
names = [n[:5] + n[-4:] + '_' if len(n) > 10... |
def linkify_phone(value):
"""
Returns a user friendly clickable phone string.
"""
if value is None:
return None
return f"tel:{value}" |
def function(func):
"""
Check that ``func`` is callable.
Parameters
----------
func: callable
Value to check.
Raises
------
ValueError
Raised when ``func`` is not callable.
Returns
-------
success: bool
Return True.
"""
if not callable(func... |
def parse_playing_now_message(playback):
"""parse_playing_now_message
:param playback: object
:returns str
"""
track = playback.get("item", {}).get("name", False)
artist = playback.get("item", {}).get("artists", [])
artist = map(lambda a: a.get("name", ""), artist)
artist = ", ".join(l... |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given RGB color values."""
return '#%02x%02x%02x' % (int(red), int(green), int(blue)) |
def is_token_in( token, list_token_classes ):
""" return true if token is in the list or is a subclass of anything in the list """
for c_token in list_token_classes:
if token in c_token:
return True
return False |
def _match_single_glob_tokens(path_tokens, prefix_tokens):
"""If the prefix matches the path (anchored at the start), returns the
segment of the path tokens that matched -- or None if no match. The
arguments are lists of strings, with an implied "/" between elements.
The token "*" must match exactly o... |
def remove_op(fn, operator = '.', extn = '.txt'):
"""
Remove operator from file names and add an extension
"""
fn.split('.')
return fn |
def parse_template(template):
"""Parse a template spec for command line arguments into a tuple of list and
dictionary values.
"""
commands = template.split(' ')
positional_parameters = []
options = []
flags = []
for command in commands:
if len(command) > 0:
if command[0] == '[':
opt... |
def _to_list(a):
"""convert value `a` to list
Args:
a: value to be convert to `list`
Returns (list):
"""
if isinstance(a, (int, float)):
return [a, ]
else:
# expected to be list or some iterable class
return a |
def comma_code(items):
""" Combines list into a string of the form item1, item2, and item 3
Args:
items (list): List of strings
Returns:
string: list items combined into a string
"""
item_len = len(items)
if item_len == 0:
return ''
elif item_len == 1:
r... |
def isRV32FRegAllocatable(regFile, index):
""" default allocatable list for RV32 integer registers """
return index in [0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 28, 29, 30, 31] |
def factorial(n):
"""
Get the factorial of the number `n` using recursion.
>>> factorial(5)
120
"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1) |
def _get_range_float_message(arange):
""" Get range warning/error message
Returns:
.str
"""
return ("Range is expected to be float."
" Ex: [0.0, 1.0] or [-0.25, 2.0].\nYour range {0}"
).format(arange) |
def cheapest_edges(root, E):
"""Given a set of edges (s, d, w), make d unique and minimize w.
:param root: a root vertex to start search from
:type root: int
:param E: a set of edges
:type E: [(int, int, float), ...]
:return: subset of edges with the cheapest edges en... |
def clean_kwargs(ignored_keys, data):
"""
Removes the ignored_keys from the data sent
:param ignored_keys: keys to remove from the data (list or tuple)
:param data: data to be cleaned (dict)
returns: cleaned data
rtype: dict
"""
for key in ignored_keys:
data.pop(key, None)
... |
def _create_json(name, description, locked, connection):
"""
Create a JSON to be used for the REST API call
"""
json = {
"connection": connection,
"type": "ws",
"name": name,
"description": description,
"locked": locked
}
return json |
def bytes2human(n, _format='%(value).1f%(symbol)s'):
"""Converts n bytes to a human readable format.
>>> bytes2human(1023)
'1023.0B'
>>> bytes2human(1024)
'1.0KiB'
https://github.com/giampaolo/psutil/blob/master/psutil/_common.py
"""
symbols = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', '... |
def function2path(func):
""" simple helper function to return the module path of a function """
return f'{func.__module__}.{func.__name__}' |
def aslist(value):
"""
Return a list of strings, separating the input based on newlines.
"""
return list(filter(None, [x.strip() for x in value.splitlines()])) |
def set_cpu_throttling_rate(rate: float) -> dict:
"""Enables CPU throttling to emulate slow CPUs.
Parameters
----------
rate: float
Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
**Experimental**
"""
return {"method": "Emulation.setCPUThrottling... |
def merge_two(a, b, path=None, raise_on_conflict=False):
"""Merge two dictionaries into a new one creating recursing all keys.
Parameters
----------
a : dict
b : dict
path : list
use for debug purposes
raise_on_conflict : bool
if False, the first dict will have precedence
... |
def trifecta(word):
"""
Checks whether word contains three consecutive double-letter pairs.
word: string
returns: bool
"""
# Error handling
if len(word) <= 1:
return False
identical_list = []
prev_letter = word[0]
# Check each letters identity to the previous letter
... |
def normalize_phone_prefix(phone):
"""Add "+" to phone prefix."""
if phone is None:
return None
phone = str(phone)
if phone == "":
return None
if not phone.startswith("+"):
phone = "+" + phone
return phone |
def InLabels(labels, substr):
"""Returns true iff one of the labels contains substr."""
return any(substr in x for x in labels) |
def sub(list1, list2):
"""
Subtract a list from another item by item
:param list1:
:param list2:
:return:
"""
if len(list1) != len(list2):
raise Exception("Listas de tamanho diferente")
return [list1[i] - list2[i] for i in range(0, len(list1))] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.