content stringlengths 42 6.51k |
|---|
def merge_dicts(*dict_args):
"""
Merge all dicts passed as arguments, skips None objects.
Repeating keys will replace the keys from previous dicts.
"""
result = None
for dictionary in dict_args:
if dictionary is not None:
if result is None:
result = dictionar... |
def chaos_of_warp(character: dict, enemy: dict) -> int:
"""
Use Chaos of Warp skill.
This is a helper function for use_skill
:param enemy: a dictionary
:param character: a dictionary
:precondition: character must be a dictionary
:precondition: character must be a valid character created by... |
def getPeak(hour):
"""
Getting hour for peak/OffPeak
"""
if '07' < hour < '10':
return 1
elif '16' < hour < '19':
return 1
else:
return 0 |
def dict_diff(dictA, dictB):
"""Return key and value differences from 2 given dictionaries
Args:
dictA (dict): Dictionary A
dictB (dict): Dictionary B
Returns:
list, lit: Not found keys, not matching values
"""
not_found_key = []
not_match_value = []
for k in dictA.... |
def _kuster_toksoz_eta(k, mu):
"""Inputs must be same shape
Args:
k (array-like): Bulk Modulus
mu (array-like): Shear Modulus
Returns:
(array-like): eta term
"""
return (mu * (9 * k + 8 * mu)) / (6 * (k + 2 * mu)) |
def trim_list(line, header):
"""Trim the number of fields in an input csv line to math the header"""
t = line[:len(header)]
return(t) |
def iterable(x):
"""Check if the input is iterable, stolen from numpy.iterable()"""
try:
iter(x)
return True
except:
return False |
def build_speechlet_response(title, output, reprompt_text, should_end_session):
""" Build Speechlet Response """
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'Simple',
'title': "SessionSpeechlet - " +... |
def convert_multidict(obj):
"""Convert querystring params, pulling values out of list
if there's only one.
"""
new_dict = {
key: (obj[key][0] if len(obj[key]) == 1 else obj[key]) for key in obj.keys()
}
return new_dict |
def column(matrix, i):
"""Helper to get column of matrix"""
return [row[i] for row in matrix] |
def split_camel(text, fix=True):
"""
Split a string in camel case format into a tuple of its component words
By default the result is guaranteed to be all lowercase
:param text: Text to split
:param fix: Whether to lowercase the result, or leave capitalization as-is
:return: Tuple of str... |
def lr_schedule_with_init(epoch,init_lr, lr):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float... |
def popout_single_lineages(lineages):
""" To remove lineages with cell numbers <= 5. """
trimed_lineages = []
for cells in lineages:
if len(cells) < 5:
pass
else:
trimed_lineages.append(cells)
assert len(trimed_lineages) > 0
return trimed_lineages |
def _dusort (seq, decorator, reverse = False) :
"""Returns a sorted copy of `seq`. The sorting is done over a
decoration of the form `decorator (p), i, p for (i, p) in
enumerate (seq)`.
>>> _dusort ([1, 3, 5, 2, 4], lambda e : -e)
[5, 4, 3, 2, 1]
"""
temp = [(decorator (p), i, p... |
def masi_distance(label1, label2):
"""Distance metric that takes into account partial agreement when multiple
labels are assigned.
>>> from nltk.metrics import masi_distance
>>> masi_distance(set([1, 2]), set([1, 2, 3, 4]))
0.665
Passonneau 2006, Measuring Agreement on Set-Valued Items (MASI)
... |
def parse_image_id(image_ref):
"""Return the image id from a given image ref
This function just returns the last word of the given image ref string
splitting with '/'.
:param str image_ref: a string that includes the image id
:return: the image id string
:rtype: string
"""
return image_... |
def markdown(text, col):
"""
:param text: The text to colour
:param col: A string (or list of strings) of colours to apply
:return: The input text with all colours applied
"""
colours = {"blue": "\033[94m", "green": "\033[92m", "red": "\033[91m", "bold": "\033[1m"}
# If multiple options wer... |
def upper_first(s):
"""The input string with the first character in uppercase.
"""
return s[0:1].upper() + s[1:] |
def centerSM(coorSM, maxS, maxM):
"""
Center vector coorSM in both S and M axes.
:param coorSM: coordinate of vector from S to M centers.
:param maxS: value representing end of estatic axis.
:param maxM: value representing end of mobile axis.
:return: SM centered coordinate.
"""
return ... |
def convert_f2c(S):
"""(str): float
Converts a Fahrenheit temperature represented as a string
to a Celsius temperature.
"""
fahrenheit = float(S)
celsius = (fahrenheit - 32) * 5 / 9
return celsius
print (celsius) |
def get_num_replicas_in_sync(strategy):
""" Returns the number of replicas in sync. """
try:
return strategy.num_replicas_in_sync
except AttributeError:
return 1 |
def __is_billing_enabled(project_name, projects):
"""
Determine whether billing is enabled for a project
@param {string} project_name Name of project to check if billing is enabled
@return {bool} Whether project has billing enabled or not
"""
try:
res = projects.getBillingInfo(name=proje... |
def calculate_overlap_area(cloth: list) -> int:
"""
Calculate the total area of overlapping claims
:param cloth: List of claims made on each square inch of the cloth
:return: Area of overlapping claims
"""
area = 0
for row in cloth:
for col in row:
area += (len(col) >= 2... |
def fib(n):
"""nth fibonacci number (iterative)"""
a, b = 0, 1
for _ in range(n): a, b = b, a+b
return a |
def segmentation_set_name(settings):
""" Deeplab sdataset name """
return 'unsupervised_llamas' if settings['problem'] == 'multi'\
else 'binary_unsupervised_llamas' |
def check_ip(ip_addr):
""" Check if IP is valid """
try:
ip = ip_addr.split('.')
if len(ip) != 4:
return False
for tmp in ip:
if not tmp.isdigit():
return False
i = int(tmp)
if i < 0 or i > 255:
return False
return True
except ValueError:
return False |
def L1_norm(seq):
"""calculates the L1 norm of a sequence or vector
:param seq: the sequence or vector
:returns: the L1 norm"""
norm = 0
for i in range(len(seq)):
norm += abs(seq[i])
return norm |
def hello(name):
"""Say hello
Function docstring using Google docstring style.
Args:
name (str): Name to say hello to
Returns:
str: Hello message
Raises:
ValueError: If `name` is equal to `nobody`
Example:
This function can be called with `Jane Smith` as argu... |
def join_hierarchical_category_path(category_path):
"""Join a category path."""
def escape(s):
"""Espace one part of category path."""
return s.replace('\\', '\\\\').replace('/', '\\/')
return '/'.join([escape(p) for p in category_path]) |
def fix_angle(angle: int) -> int:
"""Fix angle when value is negative."""
if angle < 0:
return 360 + angle
return angle |
def link_checklist(checklist, regex):
"""
QoL function to help compare automatic vs manual treatment
:param checklist: an array of manual entries deemed present
:param regex: a regex entry in the dataframe resulting of wikipedia banlist scraping
:return: nothing :)
"""
keywords = [{'key': X... |
def thrust_rating(thrust, total_mass):
""" Calculate a 0%-100% thrust rating for a ship
Given the thrust and mass of a ship, give it a rating between 0% and 100%.
Args:
thrust: A float that represents the thrust of a ship. See calc_thrust()
total_mass: The total mass of the ship
Retur... |
def lca(T, v, w):
"""
The lowest common ancestor (LCA) of two nodes v and w in a tree or directed
acyclic graph (DAG) T is the lowest (i.e. deepest) node that has both v and
w as descendants, where we define each node to be a descendant of itself
(so if v has a direct connection from w, w is the low... |
def split_query_string(query_string):
"""
Splits a query string into a dictionary
>>> split_query_string('a=1&b=2&name=abc&y=&z=ab23')
{'a': '1', 'y': '', 'b': '2', 'name': 'abc', 'z': 'ab23'}
"""
qs_dict = {}
qs_parts = query_string.split('&')
for qs_part in qs_parts:
k,v = q... |
def reset_counts_deterministic(shots, hex_counts=True):
"""Reset test circuits reference counts."""
targets = []
if hex_counts:
# Reset 0 from |11>
targets.append({'0x2': shots})
# Reset 1 from |11>
targets.append({'0x1': shots})
# Reset 0,1 from |11>
targets.... |
def keep_going(steps, num_steps, episodes, num_episodes):
"""Determine whether we've collected enough data"""
# if num_episodes is set, this overrides num_steps
if num_episodes:
return episodes < num_episodes
# if num_steps is set, continue until we reach the limit
if num_steps:
retu... |
def get_crystal_system(spg: int) -> str:
"""Get the crystal system for an international space group number."""
if 0 < spg < 3:
return "triclinic"
if spg < 16:
return "monoclinic"
if spg < 75:
return "orthorhombic"
if spg < 143:
return "tetragonal"
if spg < 168:
... |
def build_video_page(page):
"""
Url builder for TED talk video pages.
Appending the page number to the 'page' parameter.
"""
return 'http://new.ted.com/talks/browse?page={}'.format(page) |
def check_rot_equal(s1, s2):
"""
Is s1 rotationally equal to s2?
"""
if len(s1) != len(s2) or not s1 or not s2:
return False
if s1 == s2:
return True
s2 += s2
return s2.count(s1) >= 1 |
def receptive_field_size(total_layers, num_cycles, kernel_size, dilation=lambda x: 2**x):
"""Compute receptive field size.
Args:
total_layers; int
num_cycles: int
kernel_size: int
dilation: callable, function used to compute dilation factor.
use "lambda x: 1" to disable dilated convolutions.
Returns:
... |
def get_valid_padding(kernel_size, dilation):
"""
Padding value to remain feature size.
"""
kernel_size = kernel_size + (kernel_size-1)*(dilation-1)
padding = (kernel_size-1) // 2
return padding |
def words_not_anagrams(word_a, word_b):
"""Two words are not anagrams."""
if sorted(word_a) != sorted(word_b):
return True |
def compress_vertex_list(individual_vertex: list) -> list:
"""
Given a list of vertices that should not be fillet'd,
search for a range and make them one compressed list.
If the vertex is a point and not a line segment, the returned tuple's
start and end are the same index.
Args:
indivi... |
def parse_list(name, value, default): # pylint: disable=unused-argument
"""
Parses a comma separated string into a list
Argumments:
value (str or list[str]):
the value as a string or list of strings
Returns:
list[str]:
the parsed value
"""
parsed_value ... |
def selected_features_to_constraints(feats, even_not_validated=False):
"""
Convert a set of selected features to constraints.
Only the features that are validated are translated into constraints,
otherwise all are translated when `even_not_validated` is set.
:return: str
"""
res = ""
f... |
def filter_out_outline_page(outline_dict):
"""Filter out outline whose target page are not in the extracted pages list."""
for outline_chapter in outline_dict['content'].copy():
if outline_chapter['position']['page'] is None:
outline_dict['content'].remove(outline_chapter)
# recursiv... |
def apply(function, *args, **kwargs):
"""
Calls a given function with given arguments.
>>> apply(str, 24)
'24'
"""
return function(*args, **kwargs) |
def choose_driver_by_precedence(cli_drivers=None, suite_drivers=None,
settings_default_driver=None):
""" Defines which browser(s) to use by order of precedence
The order is the following:
1. browsers defined by CLI
2. browsers defined inside a suite
3. 'default_driver... |
def accumulator(init, update):
"""
Generic accumulator function.
.. code-block:: python
# Simplest Form
>>> a = 'this' + ' '
>>> b = 'that'
>>> c = functools.reduce(accumulator, a, b)
>>> c
'this that'
# The type of the initial value determines outp... |
def binary_search(element, values, start, end, get_index):
"""Binary search of element in values.
"""
i = start
j = end
while i < j:
mid = (i + j) // 2
midvalue = values[get_index(mid)]
if midvalue < element:
i = mid + 1
else:
j = mid
retur... |
def bubble_sort(x):
"""
Sorts an array x in non-decreasing order using the bubble sort algorithm.
@type x: array
@param x: the array to sort
@rtype: array
@return: the sorted array
"""
n = len(x)
for i in range(n - 1):
for j in range(n - 1, i, -1):
if x[j] < x... |
def discounted_price(price, discount):
"""
Takes in a price and a discount to return the discounted price
Arguments
---------
price: (int) Price
discount: (float)
Examples
--------
>>> discounted_price(100, 15)
85.00
"""
return round(float(price) * ((100 - float(discoun... |
def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except As... |
def convert_date_time(date, time=None):
""" The date time is only concatenated unless there is no time.
"""
if time is None:
return date
else:
return "%s %s" % (date, time) |
def get_dependencies(line):
"""
Returns dependencies (list) of a Depends: line in a control file.
Those separeted by | are returned as a separate list.
Parameters
line : str, current line
"""
deps = line[9:].split(",")
alt = []
ind = []
for n, d in enumerate(deps):
# che... |
def factorial(n):
"""
Calculates a number factorial
:param n > 0
:returns n!
"""
if n == 1:
return 1
return n * factorial(n - 1) |
def oneHotEncode_01(x, r_vals=None):
"""
This function one hot encodes the input for a binary label
"""
# define universe of possible input values
onehot_encoded = []
universe = [0, 1]
for i in range(len(universe)):
if x == universe[i]:
value = 1.
else:
... |
def get_extension(path):
""" Return the extension of the file targeted by path. """
return path[path.rfind('.'):] |
def _create_remove_item_task(title, filepath, videoid):
"""Create a single task item"""
return {
'title': title,
'filepath': filepath,
'videoid': videoid
} |
def has_unique_together_changed(old_model_sig, new_model_sig):
"""Returns whether unique_together has changed between signatures.
unique_together is considered to have changed under the following
conditions:
* They are different in value.
* Either the old or new is non-empty (even if equal... |
def get_call_zygosity(variant, simple_pedigree, family_member):
"""Get the zygosity for the given variant for the fiven family member.
Using the simple_pedigree dictionary extract the genotype for the given
variant which matches the desired type of family member. If not record is
found for the given fa... |
def validate_sequence_length(sequence):
"""
Validates that the sequence passed into it has a minimum length of 100 n.t.
"""
try:
assert len(sequence) >= 100
return True
except AssertionError:
return False |
def gen_l_hpu(i_hds):
"""
# Treat columns as if it is a batch of natural language utterance with batch-size = # of columns * # of batch_size
i_hds = [(17, 18), (19, 21), (22, 23), (24, 25), (26, 29), (30, 34)])
"""
l_hpu = []
for i,i_hds1 in enumerate(i_hds):
for (a,b) in i_hds1:
... |
def format_feature_value(bits, start_bit=0):
"""
Formats a FASM feature value assignment according to the given bits
as a string or any iterable yeilding "0" and "1". The iterable must return
bits starting from LSB and ending on MSB. The yieled bit count determines
the FASM feature assignment width ... |
def get_complementary(nt: str,
) -> str:
"""
:param nt: Nucleotide string
:return: Complementary sequence
Function to get the complementary coding sequence on the reverse (-) DNA
strand of the coordinates being give. First reverses the input nucleotide
sequence, then get b... |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'ok' and password == 'python' |
def format_response(event):
"""Determine what response to provide based upon event data.
Args:
event: A dictionary with the event data.
"""
event_type = event['type']
text = ""
sender_name = event['user']['displayName']
# Case 1: The bot was added to a room
if event_type == 'ADD... |
def header(text, color='black'):
"""Create an HTML header"""
raw_html = f'<h1 style="margin-top:16px;color: {color}"><center>' + text + '</center></h1>'
return raw_html |
def endOfChunk(prevTag, tag, prevType, type_):
"""
checks if a chunk ended between the previous and current word;
arguments: previous and current chunk tags, previous and current types
"""
return ((prevTag == "B" and tag == "B") or
(prevTag == "B" and tag == "O") or
(prevTag == "I" ... |
def collect(self, into=list):
"""
Consumes the iterator and returns a collection of the given type.
Special handling is given to the `str` type. `__str__()` is called on each
element and then the resulting list of strings are concatenated together to
form one string.
All other collections are ... |
def pt2mm(pt=1):
"""72pt -> 25.4mm (1 inch)"""
return float(pt) * 25.4 / 72.0 |
def rm_ws(string: str) -> str:
"""
Remove all extra whitespaces characters
Get rid of space, tab, newline, return, formfeed
"""
return ' '.join(string.split()) |
def mergeUnitCompare(a, b):
"""
_mergeUnitCompare_
Compare two merge units. They will be sorted first by run ID and then by
lumi ID.
"""
if a["run"] > b["run"]:
return 1
elif a["run"] == b["run"]:
if a["lumi"] > b["lumi"]:
return 1
elif a["lumi"] == b["l... |
def _weighted_sum(*args):
"""Returns a weighted sum of [(weight, element), ...] for weights > 0."""
# Note: some losses might be ill-defined in some scenarios (e.g. they may
# have inf/NaN gradients), in those cases we don't apply them on the total
# auxiliary loss, by setting their weights to zero.
return su... |
def hostname_from_fqdn(fqdn):
"""Will take a fully qualified domain name and return only the hostname."""
split_fqdn = fqdn.split('.', 1) # Split fqdn at periods, but only bother doing first split
return split_fqdn[0] |
def translate_DNA(dnaStrand,translation_table='DNA_TABLE.txt'):
"""
function body including documentation and test cases
>>> translate_DNA('ATGTATGATGCGACCGCGAGCACCCGCTGCACCCGCGAAAGCTGA')
'MYDATASTRCTRES'
"""
#dictionary to store the corresponding protein for each codon
d={'TTT':'F'... |
def is_valid_index(idx, in_list, start_idx=0):
"""
param: idx (str) - a string that is expected to
contain an integer index to validate
param: in_list - a list that the idx indexes
param: start_idx (int) - an expected starting
value for idx (default is 0); gets
subtra... |
def lst1_in_lst2(lst1,lst2):
"""
if lst1 in lst2 return 1 else return 0
"""
for i in lst1:
if not i in lst2:
return 0
return 1 |
def find_last_digits_power(base, exponent, digit_length):
"""Return the last digits of a very large power."""
counter = 1
result = base
while counter < exponent:
result = result * base
result = str(result)[0:digit_length]
result = int(result)
counter += 1
return resul... |
def quote_text(string):
"""Quote a string by the CSV rules:
if the text contains commas, newlines or quotes it will be quoted
quotes inside the text will be doubled
"""
if not string:
return string
if ',' in string or '\n' in string or '"' in string:
# check if already quoted
... |
def unmap_from_unit_interval(y, lo=0., hi=1.):
""" Linearly map value in [0, 1] to [lo_val, hi_val] """
return y * (hi - lo) + lo |
def build_gragh(graph_string):
"""
A quick parser from string into a dict that represent the graph.
Keys in the root level are the start of the path, keys in the result
are the desinations, values are the distance of the path
sample format:
AB5, BC4
returns {"A": {"B": 5}, "B": {"C": 4}}
... |
def _pad_b64(b64):
"""Fix padding for base64 value if necessary"""
pad_len = len(b64) % 4
if pad_len != 0:
missing_padding = (4 - pad_len)
b64 += '=' * missing_padding
return b64 |
def create_grid(width, height):
"""
Create new empty grid
Returns new unpopulated grid as a two-dimensional array of boolean values.
``True`` means "populated", ``False`` means "unpopulated".
"""
return [[False for x in range(width)] for y in range(height)] |
def does_not_contain_at_position(wordlist, letter, position):
"""Return the words in wordlist that don't contain the specified
letter at the specified position. This corresponds to a repeated
letter that was marked grey but does exist elsewhere in the word.
"""
result = []
for word in wordlist:
... |
def item_prefix(item):
"""
Get the item prefix ('+','++','-','--','').
"""
if item.startswith('++'):
prefix = '++'
elif item.startswith('+'):
prefix = '+'
elif item.startswith('--'):
prefix = '--'
elif item.startswith('-'):
prefix = '-'
else:
prefi... |
def bit_list_to_decimal(bit_list):
"""Convert a list of bits to a decimal number (no sign, msb on the left)"""
out = 0
for bit in bit_list:
out = (out << 1) | bit
return out |
def testSiteConnection(siteURL, timeoutLimit = 5):
"""
Tests to see if can access the given website.
"""
import urllib.request
try:
response=urllib.request.urlopen(siteURL,timeout=int(timeoutLimit))
return True
except:
return False |
def maybe_quote(s):
"""Return s quoted if it needs to be, otherwise unchanged."""
for c in s:
if c == "\"" or c == "\\" or c == "'" or c.isspace():
break
else:
return s
r = []
for c in s:
if c == "\"":
r.append("\\\"")
elif c == "\\":
... |
def max(lst):
"""Returns the maximum number in a list."""
value = lst[0]
if len(lst) == 1:
return value
maximum = max(lst[1:])
return maximum if maximum > value else value |
def qtoPhred33(q):
""" Turn Q into Phred+33 ASCII-encoded quality"""
return chr(q+33) |
def make_menu_dict_from_list(orig_list):
"""
Function to create a menu dictionary from a list
:type orig_list: List
:param orig_list: List you want to make a menu from
:rtype: Dict
:return: A dictionary with menu
"""
temp_dict = dict()
menu_new_key = 1
for orig_list_line in o... |
def print_pair_2(
claim1: str,
claim2: str,
true_label: str,
predicted_label: str,
score: float,
round_num: int = 3):
"""
Print the claims pair in a nicely formatted way when the model disagrees with annotation.
:param claim1: claim 1 string
:param claim2... |
def dictzip(keys,values):
""" zips to lists into a dictionary """
#if not keys or not values:
# raise Exception("Bad params")
#if len(keys) != len(values):
# raise
d = {}
for x in list(zip(keys,values)):
d[x[0]] = x[1]
return d |
def parsenums(linestring):
"""converts strings like '1-10; 15-17' into a list of ph0001.fits, ph0002.fits, etc"""
ans = []
first=linestring.split(';')
for thing in first:
ans= ans + (list(range(
int(thing.split('-')[0]),
int(thing.split('-')[1])+1)))
... |
def fitness_func(individual):
"""Evaluate the fitness of an individual using hamming
distance to [1,1, ... , 1]. returns value within [0,1]
"""
# ideal vector
target = [1] * len(individual)
# hamming distance to ideal vector
distance = sum([abs(x - y) for (x,y) in zip(individual, target)])... |
def str_to_numeric(s):
"""
Convert a string to a numeric type.
Returns either an int or a float depending on the apparent type of the
string.
"""
try:
return int(s)
except ValueError:
return float(s) |
def find_odd_occurred_number_sol3(nums):
"""
You are given an array of repeating numbers. All numbers repeat in even way, except for
one. Find the odd occurring number.
- Time: O(len(nums))
- Space: O(1)
"""
xor = 0
for n in nums:
xor ^= n
return xor |
def escape(s, quote=True):
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
"""
s = s.replace("&", "&") # Must b... |
def _float_to_str(x):
"""
Converts a float to str making. For most numbers this results in a
decimal representation (for xs:decimal) while for very large or very
small numbers this results in an exponential representation suitable for
xs:float and xs:double.
"""
return "%s" % x |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.