content stringlengths 42 6.51k |
|---|
def merge_dicts(d1: dict, d2: dict):
"""Merge dicts of dictionaries.
>>> merge_dicts(
{'name1': {'age': 20}, 'name2': {'age': 30}},
{'name1': {'phone': '+xxx'}, 'name2': {'phone': '+yyy'}, 'name3': {'phone': '+zzz'}}
)
... {'name1': {'age': 20, 'phone': '+xxx'}, 'name2': {'age': 30, 'phone': '+yyy'}}
"""
retu... |
def impuesto_iva12(monto=0):
""" Calcula el impuesto del IVA de 12 % """
total = ((monto * 12)/100)
return total |
def infer_eog_channels(ch_names):
"""
This function receives a list of channel names and will return
one frontal, one central and one occipital channel.
"""
eog = ['EOG ROC', 'EOG LOC']
found = []
# find frontal channel
for ch in ch_names:
if any([x in ch for x in eog])... |
def reduce_expr(expr):
"""
Reduces a boolean algebraic expression based on the identity X + XY = X
Args:
expr (str): representation of the boolean algebraic expression
Returns:
A string representing the reduced algebraic expression
"""
reduced = True
... |
def weight(size):
"""Construct a weight of some size."""
assert size > 0
return ['weight', size] |
def GetFilters(user_agent_string, js_user_agent_string=None,
js_user_agent_family=None,
js_user_agent_v1=None,
js_user_agent_v2=None,
js_user_agent_v3=None):
"""Return the optional arguments that shou... |
def splitsentence(reviewBuf):
"""
Splits each review into its individual sentences.
Arguments
---------
reviewBuf: List of reviews (strings)
Return
---------
List of sentences.
"""
new = []
# Iterate over every unique review
for i in range(len(reviewBuf)):
# Split the sentences
sentences = reviewBuf[... |
def _strip_input_and_targets(example):
"""Strip inputs and targets in example dict."""
example['input'] = example['input'].strip()
target = example['target']
if isinstance(target, str):
example['target'] = target.strip()
else:
example['target'] = [x.strip() for x in target]
return example |
def three_in_a_row(game_state, last_move):
"""Return true if X or O have three in a row in one of the
rows that include last_move. Else return false."""
if last_move == 0:
if game_state[0] == game_state[1] == game_state[2]: return True
if game_state[0] == game_state[4] == game_state[8]: ... |
def find_first(combination, idx):
"""finds the next non null element in the combination sequence whose first
element matches the index"""
for fc_idx, fc_set in enumerate(combination):
if fc_set is None:
continue
if idx == fc_set[0]:
return fc_idx
elif idx in f... |
def sort_0_1_2s(numbers):
"""
Write a program to sort an array of 0's,1's and 2's in ascending order.
"""
count_zeros = count_ones = count_twos = 0
for number in numbers:
if number == 0:
count_zeros += 1
elif number == 1:
count_ones += 1
elif number ==... |
def finalize_headers(headers, access_token):
"""
Args:
- headers: (dict-like) HTTP headers
- access_token: (str) SurveyMonkey access token
Returns: (dict) headers updated with values that should be in all requests
"""
new_headers = dict(headers)
new_headers.update({
'Aut... |
def getRequestType(data):
"""
Returns the HTTP Method type from the given request
"""
return data[0].decode("utf-8") |
def edge_match(e1, e2):
"""the strategy for edge matching in is_isomorphic.
Parameters:
----------
e1, e2 : edge).
Returns:
-------
True or false : bool
based on whether the length of bonds are the same or close to each other.
"""
return abs(e1['weight'] - e2['weight']) / e2... |
def twos_complement(val: int, num_bits: int) -> int:
"""Returns the num_bits-bit two's complement of the input value."""
mask = 2 ** (num_bits - 1)
twos_comp = -(val & mask) + (val & ~mask)
return twos_comp |
def qtr(secs_left):
"""Given the seconds left in the game, determine the current quarter."""
if secs_left <= 900:
return 4
if secs_left <= 1800:
return 3
if secs_left <= 2700:
return 2
return 1 |
def get_start_end_interval(ref, query, i = 0, j = -1):
"""
Return the start and end points in the query where the ref contig matches.
"""
#print 'start find interval'
#print ref
#print i,j
if i >= len(query):
return i, j
#print query[i][1] + '\tlen: ' + str(len(query))
... |
def _RemoveFileCommand(filename):
"""Returns a command list to remove a directory (or file) using Python."""
# Use / instead of \ in paths to avoid issues with escaping.
return ['python', '-c',
'from common import chromium_utils; '
'chromium_utils.RemoveFile("%s")' % filename.replace('\\', '/'... |
def set_phase_bounds(user_bounds, freq):
"""Make sure phase remains within the associated bounds."""
phase_min, phase_max = user_bounds
max_value = 360. / freq
if phase_min > max_value:
phase_min = phase_min - max_value
if phase_max > max_value:
phase_max = phase_max - max_value
... |
def movie_sort(movies):
"""Sorts a list of movies by their release date using bubble sort.
Args:
movies: a list of movies.
Returns:
A sorted list of movies.
"""
# make a copy of the list of movies
organized = movies.copy()
# initialize flag that tracks if there was a swap
... |
def from_matrix(mat):
"""Returns an R corresponding to the 3x3 rotation matrix mat"""
R = [mat[0][0],mat[1][0],mat[2][0],mat[0][1],mat[1][1],mat[2][1],mat[0][2],mat[1][2],mat[2][2]]
return R |
def normalize_requirement_name(name: str) -> str:
"""
Normalize the string: the name is converted to lowercase and all dots and underscores are replaced by hyphens.
:param name: Name of package
:return: Normalized name of package
"""
normalized_name = name.lower()
normalized_name = normaliz... |
def _generate_plurals(originals):
"""
Return a new set or dict containing the original values,
all with 's' appended to them.
Args:
originals set(str) or dict(str, any): values to pluralize
Returns:
set(str) or dict(str, any)
"""
if isinstance(originals, dict):
ret... |
def directive_exists(name, line):
"""
Checks if directive exists in the line, but it is not
commented out.
:param str name: name of directive
:param str line: line of file
"""
return line.lstrip().startswith(name) |
def calc_precision_recall(image_results):
"""Calculates precision and recall from the set of images
Args:
img_results (dict): dictionary formatted like:
{
'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int},
'img_id2': ...
...
... |
def estimate_traffic_speed_decrease_factor(traffic_density):
"""
Estimate a speed decrease factor, based on the current levels of traffic_density.
:param traffic_density: float value between 0 and 1.
:return: 0 <= traffic_speed_decrease_factor <= 1
"""
traffic_speed_decrease_factor = 1 - (float... |
def test_generator(*args, **kwargs):
"""
test generator
:param args:
:param kwargs:
:return:
"""
list1 = (i for i in range(100000000))
print(sum(list1))
return True |
def remove_list_from_list(all_list, list_to_remove):
"""
:param all_list: original list
:param list_to_remove: elements that will be removed from the original list.
:return: subtracted list
"""
return [value for value in all_list if value not in list_to_remove] |
def pyday_to_sqlday(pyday):
"""Converting weekday index from python to mysql."""
return (pyday + 1) % 7 + 1 |
def roundByD(angle, delta):
"""round angle by delta
angle:
delta:
>>> roundByD(8, 10)
10.0
>>> roundByD(-9.5, 10)
-10.0
"""
return delta*round(angle/float(delta)) |
def cell_get_units(value, default_units):
"""
Given a single string value (cell), separate the name and units.
:param value:
:param default_units:
:return:
"""
if '(' not in value:
return default_units
spl = value.split(' ')
name = ''
found_units = False
for sub in s... |
def get_port_definition_ports(app):
"""
:return: list
"""
port_definitions = app.get('portDefinitions', [])
return [p['port'] for p in port_definitions if 'port' in p] |
def num_pairs(num_elements):
"""Calculate the number of pairs
"""
return (num_elements * (num_elements - 1)) // 2 |
def _enzyme_path_to_sequence(path, graph, enzymes_sites):
"""Converts a path of successive enzymes into a sequence."""
return "".join(
[enzymes_sites[path[0]]]
+ [graph[(n1, n2)]["diff"] for n1, n2 in zip(path, path[1:])]
) |
def sundaram(N):
"""sundaram's sieve to find non primes"""
numbers = list(range(3, N, 2))
half = (N) // 2
init = 4
for step in range(3, N, 2):
for i in range(init, half, step):
numbers[i - 1] = 0
init += 2 * (step + 1)
if init > half:
return [2] + lis... |
def local_ij_delta_to_class(local_ij_delta):
"""
:param local_ij_delta: tuple (i, j) returned from local_ij_delta
:return: a value 0-5 for the each of the possible adjecent hexagons, or -1 if
the (i,j) tuple is representing a non-adjecent hexagon coordinate
"""
if (local_ij_delta == (0,... |
def compare_questionnaire_data(data_1, data_2):
"""
Compare two questionnaire data dictionaries and return the keywords
of the questiongroups which are not identical.
Args:
``data_1`` (dict): The first data dictionary.
``data_2`` (dict): The second data dictionary.
Returns:
... |
def flatten(L):
"""Turn a list of iterables and non-iterables into a single list of their elements"""
flat = []
for sublist in L:
try:
iter(sublist)
except TypeError:
flat.append(sublist)
else:
for item in sublist:
flat.append(item... |
def create_standard(i):
"""
create a standard matrix where all entries except the diagonal are 0, diagonals are 1
:param i: number of rows and columns
:return: list of lists of numerical values
"""
output_matrix = [[0 for j in range(i)] for b in range(i)]
for a in range(i):
output_matrix... |
def npow2(n: int) -> int:
""" return power of 2 >= n
"""
if n <= 0:
return 0
nfft = 2
while (nfft < n):
nfft = (nfft << 1)
return nfft |
def _duplicate_entry(i, keys, population, len):
"""
Args:
:i:
:keys:
:population:
:len:
Returns:
"""
hp_combinations = []
duplicate_indices = []
for val in range(len):
entry=''
for key in keys:
entry += str(population[key][val])... |
def countmatch(str1, str2, countstr):
"""checks whether countstr occurs the same number of times in str1 and str2"""
return str1.count(countstr) == str2.count(countstr) |
def _mac(possible_mac):
"""check if an object is a mac."""
valid = False
if len(possible_mac) == 12:
valid = True
for c in possible_mac:
if c not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']:
valid = False
break
return valid |
def containsAny(str, set):
""" Check whether 'str' contains ANY of the chars in 'set'
"""
return 1 in [c in str for c in set] |
def gcd(x: int, y: int) -> int:
"""Returns the largest positive integer that divides non-zero integers x and y."""
assert x != 0 and y != 0 and type(x) == int and type(y) == int, "Non-zero integers only."
if x < 0:
x *= -1
if y < 0:
y *= -1
# Euclid's algorithm
# assign the large... |
def get_schema_for_primitive(name, type_of_item, mutations):
"""
----
examples:
1) get_schema_for_primitive('', '', []) -> (0.1, [])
----
:param name:
:param type_of_item:
:return:
"""
mutation = 0.1
mutations.append(mutation)
return mutation, [] |
def merge_json_objects(a, b):
"""Merge two JSON objects recursively.
- If a dict, keys are merged, preferring ``b``'s values
- If a list, values from ``b`` are appended to ``a``
Copying is minimized. No input collection will be mutated, but a deep copy
is not performed.
Parameters
-------... |
def find_disorder_uid_using_file_id(data, xref2disorder):
""" gets the database ID used in annotation file and maps to existing disorder uuid
"""
using_id = data.get('DatabaseID')
if not using_id:
return
if using_id.startswith('ORPHA'):
map_id = using_id.replace('ORPHA', 'Orphanet')
... |
def term_frequency(v1, v2):
"""
Compute the term frequency by splitting the complex value.
"""
docid, tf, count1 = v1
_docid, _tf, count2 = v2
return (docid, tf, count1 + count2) |
def get_command_from_state(state):
"""
This method gets appropriate command name for the state specified. It
returns the command name for the specified state.
:param state: The state for which the respective command name is required.
"""
command = None
if state == 'present':
command ... |
def gcd(a, b):
"""
Get the greatest common denominator among the two inputs
:param a: An integer
:param b: Another integer
:return: The greatest common denominator as an integer among the two inputs
"""
print("a:", a, "- b:", b)
if a % b == 0:
return b
return gcd(b, a % b) |
def render_location(data):
"""
location (l)
"""
return data['location'] |
def str_to_binary(addrBin):
""" I should come up with a better name for this -- it's net-addr only """
return ''.join([chr(int(a)) for a in addrBin.split('.')]) |
def chr_type_format(chrom):
"""If chrom is an integer return 'int' else return 'str'
"""
try:
int(chrom)
return 'int'
except ValueError:
return 'str' |
def N2_depolarisation(wavelength):
"""
Returns the depolarisation of nitrogen :math:`N_2` as function of
wavelength :math:`\lambda` in micrometers (:math:`\mu m`).
Parameters
----------
wavelength : numeric
Wavelength :math:`\lambda` in micrometers (:math:`\mu m`).
Returns
----... |
def parse_command_list(config_str):
"""turn multi-line config entry into a list of commands
Args:
config_str (str): string from ConfigParser entry
Returns:
list: list of commands, blank-lines removed
"""
return [command for command in config_str.splitlines() if command] |
def merge_two_dicts(x, y):
"""
Merges 2 dictionary.
Overrides values from x with values from y, if key is the same.
Needed for Python < 3.5
See: https://stackoverflow.com/a/26853961
:param x:
:param y:
:return:
"""
z = x.copy() # start with x's keys and values
z.update(y)... |
def _flatten_dict(nested_dict, exclude_key=None):
"""
Return a list of the values of the values of a nested dictionary.
This is used to collect all ColumnDataSources except the one modified by the user
(e.g. by clicking on one of its parameters).
The ``source_dict`` has the structure {group: {param... |
def get_value_to_write(values_list):
"""Given a list of values, choose the one ranked highest.
Args:
values_list: list of value objects: {
"spatial_dim": the place this value is for,
"time_dim_value": the time of this measured value,
"time_period": the observation period,
... |
def get_buckets(ciphertext, key_length):
"""Breaks ciphertext into buckets for each key character
Args:
ciphertext (int array): Array representing the ciphertext.
key_length (int): The size of the key.
Returns:
Array of int arrays. Each int array represents parts of the ciphertext ... |
def has_any_permissions(user, permissions):
""" Retuns `True` if the user has any of the permissions """
for perm in permissions:
if user.has_perm(perm):
return True
return False |
def FillArrayType(service, elems, arrayType, elemName=None):
"""This method will create an 'ArrayOfX' object and then fill it with the array passed in.
This takes advantage of the fact that every ArrayOfX object follows the same pattern
(i.e., ArrayOfLong uses a "long" attribute. ArrayOfInt uses an "i... |
def git_root(*args):
"""
Returns the root path of the git repository (without trailing slash).
Any additional (and optional) arguments will be appended to the path
Examples
----------
> git_root()
/home/user/my_repo
> git_root('dir1', 'file')
/home/user/my_repo/dir1/file
... |
def find_varying(params, nvmax):
"""Returns list of keys with varying params (i.e. params with ranges).
params = {} : dictionary of params, each having array of length 1 or 2 (constant or varying)
nvmax = int : max number of varying params expected
"""
print('Finding variable parameters')
if... |
def _sort_practical_result(result):
"""Sort by appartus"""
practical_answers = {}
app = ""
for answer in result.values():
if app != answer[0]:
app = answer[0]
if not practical_answers.get(app):
practical_answers[answer[0]] = {}
#[applicati... |
def get_meta_value(line):
"""
docstring
"""
# line:
# '// @description some text'
# '// @version some text'
spl = line.split()
if len(spl) > 2:
return ' '.join(spl[2:]).strip()
else:
return '' |
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return va... |
def format_ad_timedelta(raw_value):
"""
Convert a negative filetime value to an integer timedelta.
"""
if isinstance(raw_value, bytes):
raw_value = int(raw_value)
return raw_value |
def serialize_response_cba(data):
"""."""
return {
'id': data.get("widgetId", None),
'type': 'water-risk-analysis',
'chart_type': data.get('chart_type', None),
'meta': data.get("meta", None),
'data': data.get('data', None)
} |
def repr(x,nchars=80):
"""limit string length using ellipses (...)"""
s = __builtins__.repr(x)
if len(s) > nchars: s = s[0:nchars-10-3]+"..."+s[-10:]
return s |
def get_exception_message(ex):
"""Build exception message with details.
"""
template = "{0}: {1!r}"
return template.format(type(ex).__name__, ex.args) |
def calculate_delta_percentage(delta_val, eu_min, eu_max):
"""Calculate the delta percentage given a value and min and max values."""
return delta_val / (eu_max - eu_min) |
def subdict(d, nested_keys=None):
""":return the dict nested hierarchically indicated by nested_keys
or None if key list is incorrect
:param nested_keys list of keys or a single keys
"""
if not isinstance(nested_keys, (tuple, list)):
nested_keys = [nested_keys]
for k in nested_keys:
... |
def convert_txt_bits(txt):
""" converts byte to bits """
bits = ''.join(bin(ord(c)) for c in txt).replace('b','')
return bits |
def get_feat_size(featurizer_type):
"""Get expected feature size for `featurizer_type`
:param featurizer_type: featurizer type
:type featurizer_type: str
:return: feature size
:rtype: int
"""
if featurizer_type == "dlib":
return 128
elif featurizer_type == "sbpycaffe" or featurizer_type == "sbcmdli... |
def code_compile_and_run(code = '', gv = {}, lv = {}, return_keys = []):
"""Compile and run the code given in the str 'code',
optionally including the global and local environments given
by 'gv', and 'lv'.
FIXME: check if 'rkey' is in str code and convert to '%s = %s' % (rkey, code) if it is not
R... |
def palindrome(word):
"""Return True if the given world is a palindrome"""
return word == word[::-1] |
def _update_hallu_record(
compute_hallu_stats, hallu_record,
layer_idx, layer_info_list, layer_dict):
"""
"""
if not compute_hallu_stats:
return hallu_record
hallu_indices, hallu_outputs, hallu_merge_pts = hallu_record
info = layer_info_list[layer_idx]
info_id = info.id
... |
def isleap(year):
"""Return True if year is a leap year, False otherwise."""
return year % 4 == 0 |
def make_draw_response(reason: str) -> str:
"""Makes a response string for a draw.
Parameters:
- reason: The reason for the draw, in the form of a noun, e.g.,
'stalemate' or 'insufficient material'.
Returns: The draw response string.
"""
return f"It's a draw because of ... |
def variant_object(variant_str):
"""Return a variant object from its string representation."""
if variant_str == '':
return None
return variant_str |
def kelvtorank(kelvin):
""" This function converts kelvin to Rankine, with kelvin as parameter."""
rankine = (kelvin * 1.8)
return rankine |
def isPalindrome(txt):
"""Given a string, determine weather its a palindrome or not"""
for i in range(len(txt)):
if txt[i] != txt[-(i + 1)]:
return False
return True |
def header_value(headers, name):
"""
Returns the header's value, or None if no such header. If a
header appears more than once, all the values of the headers
are joined with ','. Note that this is consistent /w RFC 2616
section 4.2 which states:
It MUST be possible to combine the multipl... |
def year_and_semester_to_value(s):
"""
Assigns a number to a section dict (see grade_section_json for format). Is used to
sort a list of sections by time.
"""
if s['semester'] == 'spring':
sem = 0
elif s['semester'] == 'fall':
sem = 2
else:
sem = 1
return 3 * int(... |
def __write_ldif_one(entry):
"""Write out entry as LDIF"""
out = []
for l in entry:
if isinstance(l[1], str):
vl = [l[1]]
else:
vl = l[1]
if l[0].lower() == 'omobjectclass':
out.append("%s:: %s" % (l[0], l[1]))
continue
... |
def get_min_units(sell_order, buy_order):
"""
Get the minimum units between orders
:param sell_order: sell order
:param buy_order: buy order
:return: minimum units between orders
"""
sell_units = sell_order['volume_remain']
buy_units = buy_order['volume_remain']
return min(sell_units... |
def get_keyword_index(lines, keyword):
"""
Helper function used for parsing TSPLIB files.
It searchs for the given `keyword` across the list of `lines`.
Parameters
----------
lines: list
List of lines. Each element of this list is a string.
keyword: str
The input keyword
Returns
-------
in... |
def is_transition_allowed(
constraint_type: str, from_tag: str, from_entity: str, to_tag: str, to_entity: str
):
"""
Given a constraint type and strings `from_tag` and `to_tag` that
represent the origin and destination of the transition, return whether
the transition is allowed under the given c... |
def epoch_s_to_ns(epoch_seconds):
"""
Converts epoch seconds to nanoseconds
"""
if type(epoch_seconds) is not str:
epoch_seconds = str(epoch_seconds)
return epoch_seconds + '000000000' |
def get_key_paths(data_dict,
keys_to_consider=None,
keys_not_to_consider=None,
root_path=None):
"""
Example:
get_key_paths({
'a' : {
'b': 1
},
'c' : 2
})
returns:
['a.b', 'c']
:param data_dict: (Nest... |
def top_k_frequent(words, k):
"""
Input:
words -> List[str]
k -> int
Output:
List[str]
"""
# Your code here
word_count = {}
#to check if word is in words
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count... |
def sizeof_fmt(num, suffix="B"):
"""
Returns a size in bytes to a human
readable format
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z", "Y"]:
if abs(num) < 1024.0:
return f"{num:.2f} {unit}{suffix}"
num /= 1024.0 |
def get_primitives(base):
"""Attempt to return formatting strings for all operators,
and selected operands.
Here, I use the term operator loosely to describe anything
that accepts an expression and can be used in an additional
expression.
"""
operands = []
operators = []
... |
def hasDistInfo(call):
"""Verify that a call has the fields required to compute the distance"""
requiredFields = ["mylat", "mylong", "contactlat", "contactlong"]
return all(map(lambda f: call[f], requiredFields)) |
def unpack_object_id(object_id):
"""Return ``(table_name, id)`` for ``object_id``::
>>> unpack_object_id(u'alkey:questions#1234')
(u'questions', 1234)
>>> unpack_object_id(u'alkey:questions#*')
(u'questions', None)
"""
s = object_id.replace(u'alkey:', '', 1)
pa... |
def get_centroids(vals):
"""Get bin centroids"""
cent = []
for i in range(len(vals)-1):
cent.append(0.5*(vals[i]+vals[i+1]))
return cent |
def csv_line_to_feature_parameters(row_mapping, row):
"""
Given a row mapping and a csv row, returns the needed parameters for a geojson feature:
lat, lng, title, description
as a list.
:param row_mapping:
:param row:
:return:
"""
returned = list()
returned.append(row[row_mappin... |
def make_polynomial(x, coeffs):
""" Returns a polynomial for ``x`` values for the ``coeffs`` provided.
Returns this polynomial as an array with y-values based on
that polynomial. Recommended to use through the plot_polynomial
function.
The coefficients must be in ascending order (``x**0`` to ``x**... |
def find_sorted_index(inputlist, gene_list):
"""get a list of index for mapping aftersort to inputlist
for multiple genes with the same name,just add the last one"""
indexlist = []
for key in gene_list:
if key not in inputlist:
continue
index = inputlist.index(key)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.