content stringlengths 42 6.51k |
|---|
def make_csv(tiles, width):
"""
Takes a list of tiles and a width and returns a string of comma-separated values
"""
csv = ""
for i in range(0, len(tiles), width):
csv += ",".join(str(t) for t in tiles[i:i+width])
if i + width < len(tiles):
csv += ',\n'
else:
... |
def ek_WT(cell):
"""
Returns the WT reversal potential (in mV) for the given integer index
``cell``.
"""
reversal_potentials = {
1: -91.6,
2: -92.8,
3: -95.1,
4: -92.3,
5: -106.1
}
return reversal_potentials[cell] |
def check_int(_, candidate):
"""Checks whether candidate is <int>."""
try:
int(candidate)
return True
except:
return False |
def str_convert_beforeprint(x):
""" #Before writing/output to printer put in utf-8 """
try:
return x.encode("utf-8")
except:
return x |
def conv_fmt(flag):
"""convective formatter"""
if flag<0.5:
return 's'
if flag>0.5:
return 'c'
return '' |
def mult(num1, num2=1):
"""
Multiplies two numbers
Args:
`num1`: The first number
`num2`: The second number, default `1`
Returns:
The result of the **multiplication** process
"""
return (num1*num2) |
def h(data):
""" A small helper function to translate byte data into a human-readable hexadecimal
representation. Each byte in the input data is converted into a two-character hexadecimal
string and is joined to its neighbours with a colon character.
This function is not essential to driver-building bu... |
def lookupName(n, names):
"""Check if name is in list of names
Parameters
----------
n : str
Name to check
names : list
List of names to check in
Returns
-------
bool
Flag denoting if name has been found in list (True) or not (False)
"""
if n in names:... |
def has_identical_list_elements(list_):
"""Checks if all lists in the collection have the same members
Arguments:
list_: collection of lists
Returns:
true if all lists in the collection have the same members; false otherwise
"""
if not list_:
return True
for i in range(1, l... |
def shift(register, feedback, output):
"""GPS Shift Register
:param list feedback: which positions to use as feedback (1 indexed)
:param list output: which positions are output (1 indexed)
:returns output of shift register:
"""
# calculate output
out = [register[i - 1] for i in output]
... |
def convert_by_interpolation(integer: int) -> str:
"""
Converts an integer to a string using string interpolation.
:param integer: an integer
:return: the integer as a string
"""
return "%s" % integer |
def edge_args(start, dest, direction, label, qos):
"""
Compute argument ordering for Edge constructor based on direction flag.
@param direction str: 'i', 'o', or 'b' (in/out/bidir) relative to start
@param start str: name of starting node
@param start dest: name of destination node
"""
edge... |
def extract_str(input_: str) -> str:
"""Extracts strings from the received input.
Args:
input_: Takes a string as argument.
Returns:
str:
A string after removing special characters.
"""
return ''.join([i for i in input_ if not i.isdigit() and i not in [',', '.', '?', '-', '... |
def clamp(v, low, high):
"""clamp v to the range of [low, high]"""
return max(low, min(v, high)) |
def removeSubsets(sets):
""" Removes all subsets from a list of sets.
"""
final_answer = []
# defensive copy
sets = [set(_set) for _set in sets]
sets.sort(key=len, reverse=True)
i = 0
while i < len(sets):
final_answer.append(sets[i])
for j in reversed(range(i+1, len(set... |
def dict_to_sse_arg(d):
"""
Converts a dictionary to the argument syntax for this SSE
"""
# Dictionary used to convert argument values to the correct type
types = {bool:"bool", int:"int", float:"float", str:"str"}
# Output string
s = ""
# Format into the required syntax
for k, v i... |
def avg_stdev(lst):
"""Return average and standard deviation of the given list"""
avg = sum(lst)/len(lst)
sdsq = sum((x-avg) ** 2 for x in lst)
stdev = (sdsq / (len(lst) -1)) ** 0.5
return avg, stdev |
def longest_common_prefix(string1, string2):
"""get the longest common prefix in two strings"""
i = 0
while i < len(string1) and len(string2) and string1[1] == string2[i]:
i += 1
return string1[:i] |
def jmp(amount: str, pos: int) -> int:
"""
jmp jumps to a new instruction relative to itself. The next instruction to execute is found using the argument as
an offset from the jmp instruction; for example, jmp +2 would skip the next instruction, jmp +1 would continue to
the instruction immediately below... |
def _padright(width, s):
"""Flush left.
>>> _padright(6, u'\u044f\u0439\u0446\u0430') == u'\u044f\u0439\u0446\u0430 '
True
"""
fmt = u"{0:<%ds}" % width
return fmt.format(s) |
def _any_not_none(*args):
"""Returns a boolean indicating if any argument is not None"""
for arg in args:
if arg is not None:
return True
return False |
def move_idx_to_top(gra, idx1, idx2):
""" move indexing for atm at idx1 to idx2
"""
atms, bnds = gra
newatms = {}
newbnds = {}
for key in atms:
if key == idx1:
newatms[idx2] = atms[key]
elif idx2 <= key < idx1:
newatms[key + 1] = atms[key]
else:
... |
def valid_field(field):
""" Check if a field is valid """
return field and len(field) > 0 |
def split_array(ranges, threshold):
"""
Args:
ranges: Output from laserscan
threshold: Threshold for deciding when to start a new obstacle
Returns:
obstacles_1D: List of list of ranges
"""
obstacles_1D = [[ranges[0]]]
current_obstacle_index = 0
for i in range(len(ranges)-1):
if abs(ranges[i] - ranges[... |
def is_key_suitable_for_name(key_name):
"""Check if a key is suitable for name input."""
return len(key_name) == 1 and key_name.isalnum() or key_name in ['-', '_'] |
def multiset(target, key, value):
"""
Set keys multiple layers deep in a target dict.
Parameters
-------------
target : dict
Location to set new keys into
key : str
Key to set, in the form 'a/b/c'
will be available as target[a][b][c] = value
value : any
Will be added... |
def getUriParent(uri):
"""Return URI of parent collection with trailing '/', or None, if URI is top-level.
This function simply strips the last segment. It does not test, if the
target is a 'collection', or even exists.
"""
if not uri or uri.strip() == "/":
return None
retur... |
def x_times(a):
"""
Multiply the given polinomial a, x times.
"""
return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) |
def event_converter(event):
"""
Converts event to string format that shows the event's portait on Reddit.
"""
if event["monsterType"] == "DRAGON":
event = event["monsterSubType"]
else:
event = event["monsterType"]
if event == "BARON_NASHOR":
return "[B](#mt-barons)"
... |
def duplicates(L):
"""
Return a list of the duplicates occurring in a given list L.
Args:
L (list): an input list
Returns:
a sorted list (possibly empty) of the elements appearing
more than once in input list L.
Examples:
>>> duplicates([1, 2, 1, 3, 1, 4, 2, 5])
... |
def generate_INCLUDE_GET_READY_OUTPUT_CHAR_REPR(total_number_parameters):
"""Generate on the model:
number_remaining_parameters = 1;
"""
return("number_remaining_parameters = " + str(total_number_parameters) + ";") |
def normalize_by_mean(nodes, edges, feature_list, sequence_info):
""" Normalize over all existing edges in the batch """
normalizing_feature_names = [feature for feature in feature_list if feature+"_MNORM_" in feature_list]
for feature in normalizing_feature_names:
data = edges[feature].clone()
... |
def egcd(a, b):
"""Extended Euclid's algorithm for the modular inverse calculation.
"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) |
def pad_text_batch(data_batch, vocab2int):
"""Pad text with <PAD> so that each text of a batch has the same length"""
max_text = max([len(text) for text in data_batch])
return [text + [vocab2int['<PAD>']] * (max_text - len(text)) for text in data_batch] |
def find_subclasses(cls):
""" Finds subclasses of the given class"""
classes = []
for subclass in cls.__subclasses__():
classes.append(subclass)
classes.extend(find_subclasses(subclass))
return classes |
def sm_name(section):
""":return: name of the submodule as parsed from the section name"""
section = section.strip()
return section[11:-1] |
def reorder(rules):
""" Set in ascending order a list of rules, based on their score.
"""
return(sorted(rules, key = lambda x : x.score)) |
def __url_path_format(version_id: str, resource_name: str, method_name: str) -> str:
"""
Function makes the method path
using specific format.
:param version_id: Version of API
:param method_name: Name of method
:param resource_name: Name of resource
:return: str
"""
return f"/{versi... |
def is_true ( val ):
"""
Returns true if input is a boolean and true or is a string and looks like a true value.
"""
return val == True or val in [ 'True', 'true', 'T', 't' ] |
def value_in(resource, value):
"""
check for field in resource
:param resource:
:param value:
:return: True | False
"""
if value in resource:
if isinstance(resource[value], dict):
if resource[value] == {}:
return False
else:
ret... |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... |
def identify_climate_scenario_run(scen_info, target_scen):
"""Identify the first matching run for a given climate scenario.
Returns
----------
* str or None, run id
"""
for scen in scen_info:
if target_scen in scen_info[scen]['climate_scenario']:
return scen
# End for
... |
def poly(coefs,z):
"""Evaluate a polynomial at z given its coefficient vector"""
result = 0j
for c in reversed(coefs):
result = result*z + c
return result |
def stringify_list(list_: list,
quoted: bool = False
) -> str:
"""Converts a list to a string representation.
Accepts a list of mixed data type objects and returns a string
representation. Optionally encloses each item in single-quotes.
Args:
list_: The li... |
def format_artist(index, data):
"""Returns a formatted line of text describing the artist."""
return "{}. {artist}\n".format(index, **data) |
def _B36Check(b36val):
"""
Verify that a string is a valid path base-36 integer.
>>> _B36Check('aa')
'aa'
>>> _B36Check('.')
Traceback (most recent call last):
...
ValueError: invalid ...
"""
int(b36val, 36)
return str(b36val).lower() |
def is_iterable(obj):
"""Return True if the object is a list or a tuple.
Parameters
----------
obj : list or tuple
Object to be tested.
Returns
-------
bool
True if the object is a list or a tuple.
"""
return isinstance(obj, list) or isinstance(obj, tuple) |
def build_tt_message(event, params):
"""Given an event and dictionary containing parameters, builds a TeamTalk message.
Also preserves datatypes.
inverse of parse_tt_message"""
message = event
for key, val in params.items():
message += " " + key + "="
# integers aren't encapsulated in quotes
if isinstance(va... |
def format_datetime(value, context=None):
"""Formats a value as an iso8601 date/time.
Formatting preserves timezone information if present.
"""
if not value:
return value
return value.isoformat() |
def nested_dict_lookup(key, var):
"""Searches a nested dictionary for a key and returns the first key it finds.
Returns None if not found.
Warning: if key is in multiple nest levels,
this will only return one of those values."""
o = None
if hasattr(var, 'iteritems'):
for k, v in var.items():
if... |
def get_key_name_as_convention(desired_name: str):
"""
:param desired_name: The name you would
like to convert
:return: The key name as a personal
convention I'm using for brightness.ini
"""
return desired_name.lower().replace(" ", "").replace(":", "") |
def any_exist(paths):
"""Return True if any path in list exists."""
return any([path.exists() for path in paths]) |
def filter_response(response, filter_fields):
"""Filter PowerFlex API response by fields provided in `filter_fields`.
Supports only flat filtering. Case-sensitive.
:param response: PowerFlex API response
:param filter_fields: key-value pairs of filter field and its value
:type filter_fields: dict
... |
def _clean_protocol_metadata(protocol_metadata: dict) -> dict:
"""Replace confusing '|' (reserved for separation btw elements) with space.
Only 1 manufacturer with this apparently but...
"""
return {
k: v.replace("|", " ")
if isinstance(v, str)
else v # there are some None (not ... |
def getkey(dict_, key, default=None):
"""Return dict_.get(key, default)
"""
return dict_.get(key, default) |
def rundescriptor_in_dsname(dsname):
"""Returns (str) run-descriptor flom dsname, e.g. "6-12" from dsname="exp=xcsx35617:run=6-12".
"""
for fld in dsname.split(':'):
if fld[:4]=='run=': return fld.split('=')[-1]
return None |
def decode_media_origin(hex_str: str) -> str:
""" Decode a string encoded with encode_media_origin() and return a string. """
return bytes.fromhex(hex_str).decode() |
def get_weekdays(first_weekday=0):
"""Get weekdays as numbers [0..6], starting with first_weekday"""
return list(list(range(0, 7)) * 2)[first_weekday: first_weekday + 7] |
def missing_explanation(json):
"""Returns false if all recommendations have an explanation.
Returns errormessage and status code if not."""
for recommendations in json.values():
for rec in recommendations:
if 'explanation' not in rec:
return 'Recommendations must include ... |
def get_metadata_from_attributes(Object, skip_attributes = None, custom_classes = None):
"""
Get metadata dict from attributes of an object.
Parameters
----------
Object :
object from which the attributes are.
skip_attributes : list, optional
If given, these attributes are... |
def aero_dat(Re, Ma, Kn, p_inf, q_inf, rho_inf, gamma_var, Cd_prev, Cl_prev):
"""
Constant aerdynamic coefficients - space shuttle example
"""
C_d = 0.84
C_l = 0.84
C_s = 0.0
return [C_d, C_l, C_s] |
def sol_rad_island(et_radiation):
"""
Estimate incoming solar (or shortwave) radiation, *Rs* (radiation hitting
a horizontal plane after scattering by the atmosphere) for an island
location.
An island is defined as a land mass with width perpendicular to the
coastline <= 20 km. Use this method ... |
def shout(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = word + '!!!'
# Replace print with return
return shout_word |
def expected_p_t(step: int, p0: float, c_lambda: float, model_type: str) -> float:
"""
Computes expected value of transition probability according to theoretical results.
:param step:
:param p0:
:param c_lambda:
:param model_type:
:return:
"""
if model_type == 'success_punished':
... |
def get_el_feedin_tariff_chp(q_nom, el_feedin_epex=0.02978, vnn=0.01):
"""
Calculates feed-in tariff for CHP-produced electricity.
Parameters
----------
q_nom : nominal thermal power of chp in kW
el_feedin_epex : epex price for electricity in Euro/kWh
vnn : avoided grid charges ("vermiedene... |
def post_games(match_id='POST'):
"""Create a game. Return game details and status."""
# If game_id then something is wrong
# If match_id then create a new game in that match
# If no match_id then create a new game with no match
result = '{"game_id":"POST", "match_id":"'+str(match_id)+'"}'
return... |
def make_text(words):
"""Return textstring output of get_text("words").
Word items are sorted for reading sequence left to right,
top to bottom.
"""
line_dict = {} # key: vertical coordinate, value: list of words
words.sort(key=lambda w: w[0]) # sort by horizontal coordinate
for w in words... |
def isXPathNonVar(var):
"""Returns true iff var is a string ("foo" or 'foo') or a number."""
if (var.startswith("'") and var.endswith("'")) or \
(var.startswith('"') and var.endswith('"')):
return True
# list from XPathToCode, below
if var.lower() in ["count", "empty", "true", "fals... |
def instancegroup_config(id, instanceCount):
"""
create instance_group
:param id: id
:type id: string
:param instanceCount: instanceCount
:type instanceCount: int
:return: instancegroup_config
"""
instancegroup_config = {
'id': id,
'instanceCount': instanceCount
}... |
def gc_sandstone(Vp, B=0.80416, C=-0.85588):
"""
Vs from Vp using Greenberg-Castagna sandstone coefficients.
Vs = A*Vp**2.0 + B*Vp + C
"""
Vs = B*Vp + C
return Vs |
def ms_to_strtime(timems):
"""Convert Milliseconds to ASS string time"""
s, ms = divmod(timems, 1000)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
cs, ms = divmod(ms, 10)
return '{:01d}:{:02d}:{:02d}.{:02d}'.format(h, m, s, cs) |
def overlay_configs(*configs):
"""Non-recursively overlay a set of configuration dictionaries"""
config = {}
for overlay in configs:
config.update(overlay)
return config |
def _get_mean(list):
"""calculates and returns average from list of floats
also works for 1-dimmensional numpy arrays
"""
ave = 0.0
for n in list:
ave += n
return ave / len(list) |
def ID_to_int(s_id):
"""
Converts a string id to int
falls back to assuming ID is an Int if it can't process
Assumes string IDs are of form "[chars]-[int]" such as
mp-234
"""
if isinstance(s_id, str):
return int(str(s_id).split("-")[-1])
elif isinstance(s_id, (int, float)):
... |
def format_speed(bps):
"""
Formats a string to display a transfer speed utilizing :py:func:`fsize`. This is code has been copied from :py:meth:`deluge's format_speed <deluge.ui.console.utils.format_utils.format_speed>`.
:param int bps: bytes per second.
:returns: a formatted string representing transfe... |
def convert_dec_to_hex_string(decimal_value):
"""
This function converts a decimal value into 8-byte hex string
and reverses the order of bytes.
"""
hex_str = '{:016x}'.format(decimal_value)
reversed_hex = []
index = len(hex_str)
while index > 0:
reversed_hex += hex_str[index - 2... |
def convert_dtype(contents):
"""
Take the parsed TSV file and convert columns
from string to float or int
"""
# Convert contents to array
contents_arr = contents[1:]
cols = list(zip(*contents_arr))
# Iterate over every column in array
for idx in range(len(cols)):
# Get c... |
def count_frequency(samples, target):
"""
Calculate how frequent an target attribute appear in a list
Arguments:
samples (list): Input list. Its elements must be hashable.
target (object): The target element.
Returns:
float: The frequency that target appears in samples. Must be... |
def get_column_reference(headers, name):
"""Make an Excel-style column reference."""
return chr(ord('A') + headers.index(name)) |
def charIdx_to_tokenIdx(spans, ans_text, ans_start):
"""
Convert answer 'char idx' to 'token idx' for one single record
"""
# Convert answer 'char idxs' to 'token idxs' for one single record
if ans_start != -999:
ans_end = ans_start + len(ans_text) - 1
ans_to... |
def get_write_param_value(mode, memory, ptr):
"""Returns the value of the paramter at memory[ptr] based on the mode, for a writing parameter"""
# position mode
if mode == 0:
return memory[ptr]
# immediate mode
elif mode == 1:
# immediate mode is not supported
raise Exception
... |
def slice_to_list(sl, max_len):
"""
Turn a slice object into a list
Parameters
----------
sl: slice
The slice object
max_len: int
Max length of the iterable
Returns
-------
list
The converted list
"""
if sl.start is None:
start = 0
elif... |
def custom_format(template, **kwargs):
"""
Custom format of strings for only those that we provide
:param template: str - string to format
:param kwargs: dict - dictionary of strings to replace
:return: str - formatted string
"""
for k, v in kwargs.items():
template = template.replac... |
def is_safe(func_str):
"""
Verifies that a string is safe to be passed to exec in the context of an
equation.
:param func_str: The function to be checked
:type func_str: string
:returns: Whether the string is of the expected format for an equation
:rtype: bool
"""
# Remove whitespa... |
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found. C++ way of checking the chars in the string method used.
Run time: O(n*m), n is length of the string, m is for if statement to check
match is found.
Space Complexity: O(1) be... |
def flatten_dict(d, prefix=''):
""" Recursively flattens nested dictionaries.
Warning: Eliminates any lists!
"""
result = {}
for key in d:
if isinstance(d[key], str):
result[prefix + key] = d[key]
elif isinstance(d[key], dict):
prefix = key + '_'
... |
def _format_as_index(indices):
"""
(from jsonschema._utils.format_as_index, copied to avoid relying on private API)
Construct a single string containing indexing operations for the indices.
For example, [1, 2, "foo"] -> [1][2]["foo"]
"""
if not indices:
return ""
return "[%s]"... |
def map(function, iterator):
""" Our own version of map (returns a list rather than a generator) """
return [function(item) for item in iterator] |
def percent_g(seq): # checked
"""Returns the percentage of G bases in sequence seq"""
return float("%.2f"%((seq.count("G") / float(len(seq))) * 100)) |
def iss(ary):
"""Sorts an array in a nondecreasing order"""
ary_len = len(ary)
for i in range(ary_len):
j = i
while ary[j] < ary[j - 1] and j > 0:
ary[j], ary[j - 1] = ary[j - 1], ary[j]
j -= 1
return ary |
def remove_v(ss,v):
""" removes from ss those that have value v"""
s = []
for i in range(len(ss)):
if ss[i] == v:
continue
else:
s = s + [ss[i]]
return s |
def check(ans, temp_ans, input_ch):
"""
Check if the user guessed the right letter.
:param ans: The correct word string.
:param temp_ans:Every temporarily answer when the user guess a letter.
:param input_ch: The character the user input.
:return: return to the temporarily answer when the user d... |
def skip_add(n):
""" Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0.
>>> skip_add(5) # 5 + 3 + 1 + 0
9
>>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
30
>>> # Do not use while/for loops!
>>> from construct_check import check
>>> # ban iteration
>>> check(this_file, 'skip_add... |
def set_trainable_params(params):
"""
Freeze positional encoding layers
and exclude it from trainable params for optimizer.
"""
trainable_params = []
for param in params:
if param.name.endswith('position_enc.embedding_table'):
param.requires_grad = False
else:
... |
def oooc_to_ooow(formula):
"""Convert (proprietary) formula from calc format to writer format.
Arguments:
formula -- str
Return: str
"""
prefix, formula = formula.split(":=", 1)
assert "oooc" in prefix
# Convert cell addresses
formula = formula.replace("[.", "<").replace(":.",... |
def is_ltriangular(A):
"""Tells whether a matrix is an lower triangular matrix or not.
Args
----
A (compulsory)
A matrix.
Returns
-------
bool
True if the matrix is an lower triangular matrix, False otherwise.
"""
for i in range(len(A)):
for j ... |
def concatenate_authors(list_of_authors):
"""Concatenate a list of authors into a string seperated by commas, and with the last author preceded by 'and'."""
if not isinstance(list_of_authors, list) or len(list_of_authors) == 0:
return None
elif len(list_of_authors) == 1:
return list_of_autho... |
def average_rate(instantaneous_rate_primary, instantaneous_rate_secondary):
"""Returns the average achievable rate for SNR value in dB.
Arguments:
instantaneous_rate_primary -- instantaneous achievable rate of the primary user.
instantaneous_rate_secondary -- instantaneous achievable rate of... |
def remove_newline(string, n=1):
"""Remove up to `n` trailing newlines from `string`."""
# Regex returns some weird results when dealing with only newlines,
# so we do this manually.
# >>> import re
# >>> re.sub(r'(?:\r\n|\n\r|\n|\r){,1}$', '', '\n\n', 1)
# ''
for _ in range(n):
if s... |
def backslash_escape(data):
"""
This encoding is used in JSON:
Double quotes become: \"
Single quotes become: \'
"""
return data.replace(u'"', u'\\"').replace(u"'", u"\\'") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.