content stringlengths 42 6.51k |
|---|
def get_num_atoms_in_formula_unit(configuration):
"""Return the number ot atoms per formula unit.
For unaries, it's the number in the primitive cell: 1 for SC, BCC, FCC; 2 for diamond.
"""
mapping = {
'XO': 2,
'XO2': 3,
'X2O': 3,
'X2O3': 5,
'XO3': 4,
'X2O... |
def parse_tsv(s):
"""Parse TSV-formatted string into a list of dictionaries.
:param s: TSV-formatted string
:type s: str
:return: list of dictionaries, with each dictionary containing keys from
the header (first line of string)
:rtype: list
"""
lines = s.strip().splitlines()
... |
def generate_anchor_tag(url: str, description: str) -> str:
"""
Fungsi yang menerima input berupa string url dan string description
dan mengembalikan string yang berisi tag anchor dengan isi url dan
description yang sama dengan input.
Fungsi ini akan mengembalikan tag anchor dengan url yang berisi ... |
def christmas_log(ingredients: str, mix: int) -> str:
"""Created the Christmas log
Args:
ingredients (str): list of ingredients
mix (int): number of mixes to be made
Returns:
str: The christmas lgo
"""
return ingredients[-mix:] + ingredients[:-mix] |
def getFloatFromStr(number: str) -> float:
""" Return float representation of a given number string.
HEX number strings must start with ``0x``.
Args:
numberStr: int/float/string representation of a given number.
"""
numberStr = number.strip()
isNegative = False
if "-" in numberStr:
... |
def normalize_whitespace(text, base_whitespace: str = " ") -> str:
""" Convert all whitespace to *base_whitespace* """
return base_whitespace.join(text.split()).strip() |
def _remove_dups(L):
"""
Remove duplicates AND preserve the original order of the elements.
The set class is not guaranteed to do this.
"""
seen_before = set([])
L2 = []
for i in L:
if i not in seen_before:
seen_before.add(i)
L2.append(i)
return L2 |
def max_profit(stocks):
"""Computes the maximum benefit that can be done by buying and selling once a stock based on a list of stock values
O(n) time complexity as we only go through the list of values once"""
if stocks == []:
return []
current_max_profit = 0
min_stock = stocks[0]
solut... |
def flatten_lists_one_level(potential_list_of_lists):
"""
Wrapper to unravel or flatten list of lists only 1 level
:param potential_list_of_lists: list containing lists
:return: flattened list
"""
flat_list = []
for potential_list in potential_list_of_lists:
if isinstance(potential_l... |
def edit_distance(s1, s2):
"""
:param s1: list
:param s2: list
:return: edit distance of two lists
"""
if len(s1) < len(s2):
return edit_distance(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerat... |
def collatz_step(n: int) -> int:
"""Returns the next number in the Collatz sequence following n."""
return n // 2 if n % 2 == 0 else 3 * n + 1 |
def normalize_page_number(page_number, page_range):
"""Handle a negative *page_number*.
Return a positive page number contained in *page_range*.
If the negative index is out of range, return the page number 1.
"""
try:
return page_range[page_number]
except IndexError:
return page... |
def failures_message(failed):
"""Format a list of failed recipes for a slack message"""
failures_msg = [
{
"color": '#f2c744', "blocks": [
{
"type": "divider"
},
{
"type": "section", "text": ... |
def dict_sorted(src: dict, is_reverse: bool=False) -> dict:
"""Convert the dictionary data to sorted data."""
assert isinstance(src, dict)
assert isinstance(is_reverse, bool)
return dict(sorted(src.items(), key=lambda x: x[0], reverse=is_reverse)) |
def capfirst(value, failure_string='N/A'):
"""
Capitalizes the first character of the value.
If the submitted value isn't a string, returns the `failure_string` keyword
argument.
Cribbs from django's default filter set
"""
try:
value = value.lower()
return value[0].upper() ... |
def factorial(n):
""" Calculates factoriel of give number
that uses a recursion """
if n == 0:
return 1
return n * factorial(n-1) |
def one_feature():
"""Returns feature object response in token, and list of feature permissions"""
return {'feature': ['permission']}, ['feature.permission'] |
def corr_exon_num_or_no_fs(codon, exon_num):
"""Need to decide which exon num to assign."""
# count letters in the left and rigth exon
cut_at = codon["split_"]
left_side_ref = codon["ref_codon"][:cut_at]
left_side_que = codon["que_codon"][:cut_at]
# count gaps on each side
ls_ref_gaps = left... |
def unknownEvaluationFunction(current: list, target: list):
"""
Some really tricky evaluation function, as shown in:
Ma, S. P. et al(2004). Search Problems. In Artificial Intelligence(pp. 26-49). Beijing, Beijing: Tsinghua University Press
"""
count = 0
curr_1d = []
tgt_1d = []
for i in ... |
def get_microphysics_name(config):
"""Get name of microphysics scheme from configuration dictionary
Args:
config (dict): a configuration dictionary
Returns:
str: name of microphysics scheme
Raises:
NotImplementedError: no microphysics name defined for specified
imp... |
def same_padding_calc(inp_shape, kernel_shape, stride):
"""
!Attention - only square image padding calculation implemented!
Calculates the size of 'same' padding for CONV layers.
Args:
kernel_shape (int or tuple): the shape of the kernel(filter).
inp_shape (int or tuple): the sh... |
def EDSD(libitem, index):
"""
Exponentially decreasing space density prior
Define characteristic length scale k in kpc
"""
k = 1.35
return k |
def zstr(s):
""" if s contains None, it replaced with 'noraffice' string
"""
return s or "notraffic" |
def _get_line_with_str(lines, string, index):
"""Extracts the index-th line containing a string.
Args:
lines (list[str]): List of strings (typically lines from a file).
string (str): Substring to filter lines by.
index (int): Which filtered string to return.
Returns:
str: T... |
def _get_names(_dict):
"""Recursively find the names in a serialized column dictionary.
Parameters
----------
_dict : `dict`
Dictionary from astropy __serialized_columns__
Returns
-------
all_names : `list` [`str`]
All the column names mentioned in _dict and sub-dicts.
... |
def metric7(gold, predicted):
"""Evaluate labeling as being clause-classification on clause level"""
counts = {"tp": 0, "tn": 0, "fp": 0, "fn": 0}
for gclause, pclause in zip(gold, predicted):
gold_binary = "B" in gclause or "I" in gclause
predicted_binary = "B" in pclause or "I" in pclause
... |
def compute_spiral_diagonal_sum(first_elem, loop_wh):
"""
Compute the sum of the four diagonal elements for the given loop
first_elem: First element (in the right-most, second-down element of this loop)
loop_wh: Width / height of the spiral's loop to compute the diag-sum
return: sum of the four diag... |
def find_average(data):
"""
averages total amounts from database dumps
:param data: accepts multi-dimensional iterable data type
:return: returns the average in a FLOAT
"""
total = 0
amount = len(data)
for entry in data:
total += entry[0]
average = total / amount
... |
def set_spat_info(location=None, primary_spatial_reference="string", resolution="string", srid=0):
"""
function to create a dictionary with typicial values of spatial information for the dataset
:param location:
:param primary_spatial_reference:
:param resolution:
:param srid:
:return: ... |
def incsum(prevsum, prevmean, mean, x):
"""Caclulate incremental sum of square deviations"""
newsum = prevsum + (x - prevmean) * (x - mean)
return newsum |
def _to_str(value):
"""Convert value to str for bmfont file."""
if isinstance(value, str) :
return '"{}"'.format(value)
if isinstance(value, (list, tuple)):
return ','.join(str(_item) for _item in value)
return str(int(value)) |
def to_mmol(value):
"""
Convert a given value in mg/dL to mmol/L rounded to 1 decimal place.
"""
return round((float(value) / 18.018), 1) |
def get_display_name(record):
"""Get the display name for a record.
Args:
record
A record returned by AWS.
Returns:
A display name for the cluster.
"""
return record["clusterName"] |
def l2s(x):
"""
[1,2,3,4,5,6,7,8] -> '1,2,...,7,8'
"""
if len(x)>5: x = x[:2] + ['...'] + x[-2:]
y = [str(z) for z in x] # convert to list of strings, eg if list of int
y = ",".join(y)
return y |
def Beta(x, norm=1., beta=1., r=1.):
"""
Beta profile.
Parameters
----------
x : number
The input number for calculation.
norm : number
The normalization at the center of the cluster.
beta : number
The beta parameter.
r : number
The core radius.
Refe... |
def quantile(percent, data):
"""
Compute the quantile such that 100p% of data lies above the output
value.
"""
if not data:
return data
data.sort()
index = int(percent*len(data) + 0.5) - 1
if index < 0:
index = 0
return data[index] |
def _get_argument_type(value):
"""Get the type of a command line argument."""
type_ = "string"
try:
value = int(value)
type_ = "int"
except ValueError:
pass
return value, type_ |
def textToInt(text, defaultInt):
"""Converts text to an integer by using an eval and returns the integer.
If something goes wrong, returns default Int.
"""
try:
returnInt = int(text)
except Exception:
returnInt = defaultInt
return returnInt |
def get_best_trial(trial_list, metric):
"""Retrieve the best trial."""
return max(trial_list, key=lambda trial: trial[metric]) |
def to_element_case(el):
"""Convert an uppercase elemnt to element case, e.g. FE to Fe, V to V."""
return el[0].upper() + el[1:].lower() |
def _calculate_verification_code(hash: bytes) -> int:
"""
Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed.
See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm
"""
return ((0xFC & hash[0]) << 5) |... |
def _GuessCharset(text):
"""Guesses the character set of a piece of text.
Args:
text: A string that is either a US-ASCII string or a Unicode string that was
encoded in UTF-8.
Returns:
The character set that is needed by the string, either US-ASCII or UTF-8.
"""
try:
text.decode('us-ascii... |
def get_av_num(link):
""" get av num"""
av_num = link.split('/')[-1]
return av_num |
def clean_data(data):
"""Return the list of data, replacing dashes with zeros.
Parameters
----------
data : list or str
The data to be cleaned
Returns
-------
cleaned_data : list of str
The data with dashes replaced with zeros
"""
cleaned_data = []
for item in ... |
def is_event_match_for_list(event, field, value_list):
"""Return if <field> in "event" match any one of the value
in "value_list" or not.
Args:
event: event to test. This event need to have <field>.
field: field to match.
value_list: a list of value to match.
Returns:
... |
def calc_specificity(true_neg, false_pos):
"""
function to calculate specificity/true negative rate
Args:
true_neg: Number of true negatives
false_pos: Number of false positives
Returns:
None
"""
try:
spec = true_neg / float(true_neg + false_pos)
return round(spec, 3)
except BaseExce... |
def func_nogoal(x):
"""Map goals scored to nogoal flag.
INPUT:
x: Goals scored
OUTPUT:
1 (no goals scored) or 0 (at least 1 goal scored)
"""
if x == 0:
return 1
else:
return 0 |
def get_ratelimiter_config(global_configs, api_name):
"""Get rate limiter configuration.
Args:
global_configs (dict): Global configurations.
api_name (String): The name of the api.
Returns:
float: Max calls
float: quota period)
"""
max_calls = global_configs.get(ap... |
def get_value(amps, path):
"""
This function extracts a value from a nested dictionary
by following the path of the value.
"""
current_value = amps
for key in path.split('/')[1:]:
current_value = current_value[key]
return current_value |
def distance_abs(x_dict, y_dict):
"""
Distance function for use in pyABC package, which takes dictionary arguments
"""
x = x_dict['X_2']
y = y_dict['X_2']
dist = 0
for idx_time in range(9):
sim_hist = x[idx_time]
data_hist = y[idx_time]
for idx_el in rang... |
def get_hashtags(content) -> str:
"""
Get hashtags from json
"""
mentions = list()
for name in content['entities']['hashtags']:
mentions.append(name['text'])
return '|'.join(mentions) |
def _check_substituted_domains(patchset, search_regex):
"""Returns True if the patchset contains substituted domains; False otherwise"""
for patchedfile in patchset:
for hunk in patchedfile:
if not search_regex.search(str(hunk)) is None:
return True
return False |
def invert(object):
"""Same as R.invertObj, however this accounts for objects with
duplicate values by putting the values into an array"""
if type(object) is dict:
o = object.items()
else:
o = enumerate(object)
out = {}
for key, value in o:
try:
out[value].ap... |
def get_file_name(path):
"""
Extracts the name of the file from the given path
:param path: location of the file in which the name will be extracted from
:return:
"""
split_path = path.split("/")
file_name = split_path[len(split_path) - 1]
return file_name |
def _inject_key(key, infix):
"""
OSM keys often have several parts, separated by ':'s.
When we merge properties from the left and right of a
boundary, we want to preserve information like the
left and right names, but prefer the form "name:left"
rather than "left:name", so we have to insert an
... |
def golden_section(f, a, b, tol=1e-5, **kwargs):
"""
Golden section search.
Stolen from https://en.wikipedia.org/wiki/Golden-section_search
Given a function f with a single local minimum in
the interval [a,b], gss returns a subset interval
[c,d] that contains the minimum with d-c <= tol.
... |
def p1_for(input_list):
"""Compute some of numbers in list with for loop."""
out = 0
for i in input_list:
out += i
return out |
def superpack_name(pyver, numver):
"""Return the filename of the superpack installer."""
return 'scipy-%s-win32-superpack-python%s.exe' % (numver, pyver) |
def split_link_alias(link_alias):
"""Return (alias_root, link_id) from link alias."""
alias_root, alias_id = link_alias.split('#', 1)
return alias_root, int(alias_id) |
def field_to_list(row, key):
"""
Transforms key in row to a list. We split on semicolons if they exist in the string,
otherwise we use commas.
Args:
row: row of data
key: key for the field we want
Reutrns:
row: modified row
"""
if ";" in row[key]:
row[key] = ... |
def get_class(x):
"""
x: index
"""
# Example
distribution = [99, 198, 297, 396, 495]
x_class = 0
for i in range(len(distribution)):
if x > distribution[i]:
x_class += 1
return x_class |
def call_filter(to_call, value, base):
"""
Encapsulates the logic for handling callables in the filter.
Call the callable to_call with value and possibly base.
"""
# Callables can take either one or two values
try:
return to_call(value, base)
except TypeError:
return to_call... |
def romberg_iterativo(f, i, lim):
""" Funcion para ejecutar el metodo de Romberg iterativo.
Esta funcion trata de ejecutar el metodo de Romberg iterativo
con un acercamiento iterativo. Regresara el valor calculado,
con la condicion de termino i == 0 donde no se llamara a si
misma de nuevo.
... |
def power_intercept(popt, value=1):
"""At what x value does the function reach value."""
a, b = popt
assert a > 0, f"a = {value}"
assert value > 0, f"value = {value}"
return (a / value) ** (1 / b) |
def h(host_num: int) -> str:
""" Returns the host name for a given host number """
return f'h{host_num}' |
def convert_to_post(input_data):
"""
Api to get POST json data using PATCH/PUT json data
Author: Ramprakash Reddy (ramprakash-reddy.kanala@broadcom.com)
:param: input_data (PATCH/PUT data)
:return: POST data
"""
post_data = dict()
temp = list(input_data.keys())[0]
if isinstance(input... |
def colSel(idxes, iterable):
"""
colSel(idxes, iter: iterable)
example:
idxes = 1; iter = [1,2,3] => 2
idxes = [1,2]; iter = [1,2,3] => [2, 3]
idxes = ("b", "a"); iter = {"a":"a", "b":"b"} => ["b", "a"]
"""
if type(idxes) not in (list, tuple):
... |
def get_sample_ids_to_label(samples_file):
""" Get sample id, label tuples to be highlighted """
sample_label_tuples = []
for line in open(samples_file, 'rU'):
if line[0] == '#':
continue
line_pieces = [x.strip() for x in line.split('\t')]
if len(line_pieces) == 2:
... |
def types_functions_to_json(json_types, functions):
"""Creates string for JSON output from types and functions."""
return {'functions': functions, 'types': json_types} |
def find_peaks(list_of_intensities):
"""Find peaks
Find local maxima for a given list of intensities or tuples
Intensities are defined as local maxima if the
intensities of the elements in the list before and after
are smaller than the peak we want to determine.
For example given a list:
... |
def dec(text):
""" Create a declarative sentence """
formatted = '%s%s.' % (text[0].capitalize(), text[1:len(text)])
return formatted |
def sum_pairs(ints, s):
"""
Given a list of integers and a single sum value,
return the first two values (parse from the left please)
in order of appearance that add up to form the sum.
sum_pairs([4, 3, 2, 3, 4], 6)
^-----^ 4 + 2 = 6, indices: 0, 2 *
^-----^ 3 + 3 = 6, i... |
def _convert_now(arg_list):
"""
Handler for the "concatenate" meta-function.
@param IN arg_list List of arguments
@return DB function call string
"""
nb_args = len(arg_list)
if nb_args != 0:
raise Exception("The 'now' meta-function does not take arguments (%d provided)" % nb_args)
... |
def encodeFormData(arg, value):
"""Encode data as a multipart/form-data
"""
BOUNDARY = '----------BOUNDARY'
l = []
l.append('--' + BOUNDARY)
l.append('Content-Disposition: form-data; name="%s"' % arg)
l.append('')
l.append(value)
l.append('--' + BOUNDARY + '--')
l.append(''... |
def post_legacy(post):
"""Return legacy fields which may be useful to save.
Some UI's may want to leverage these, but no point in indexing.
"""
_legacy = ['id', 'url', 'root_comment', 'root_author', 'root_permlink',
'root_title', 'parent_author', 'parent_permlink',
'max_ac... |
def bubble_sort(array):
""" Bubble sort implementation
Arguments:
- array : (int[]) array of int to sort
Returns:
- array : (int[]) sorted numbers
"""
for i in range(len(array)):
for j in range(len(array)-1-i):
if array[j] > array[j+1]:
array[j... |
def get_pip_installation_line(package_name: str, package_version: str, package_url: str) -> str:
"""Return installation line for a pip installable package."""
extras_operators = ("[", "]")
versions_operators = ("==", ">=", ">", "<=", "<")
if any(operator in package_version for operator in extras_operato... |
def node_para(args):
"""
:param args: args
:return: node config or test node config list
"""
node_list = []
i = 0
if args.find("//") >= 0:
for node in args.split("//"):
node_list.append([])
ip, name, passwd = node.split(",")
node_list[i].append(ip)... |
def getTotalInAge(nodeState, ageTest):
"""Get the size of the population within an age group.
:param nodeState: The disease states of the population stratified by age.
:type nodeState: A dictionary with a tuple of (age, state) as keys and the number of individuals
in that state as values.
:param ag... |
def remove_last_range(some_list):
"""
Returns a given list with its last range removed.
list -> list
"""
return some_list[:-1] |
def escape_quotes(string):
"""Escape double quotes in string."""
return string.replace('"', '\\"') |
def SET_DIFFERENCE(*expressions):
"""
Takes two sets and returns an array containing the elements that only exist in the first set.
https://docs.mongodb.com/manual/reference/operator/aggregation/setDifference/
for more details
:param expressions: The arrays (expressions)
:return: Aggregation ope... |
def GetSubstitutedResponse(response_dict, protocol, response_values):
"""Substitutes the protocol-specific response with response_values.
Args:
response_dict: Canned response messages indexed by protocol.
protocol: client's protocol version from the request Xml.
response_values: Values to be substitute... |
def _get_topic_name_from_ARN(arn):
"""
Returns undefined if arn is invalid
Example
arn: "arn:aws:sns:us-east-1:123456789012:notifications"
"""
return arn.split(":")[-1] |
def get_adjacent_digits(n, tuple_length):
"""
Returns a list of numbers where each numbre is the tuple_length
group of adjacent digits
Ex: get_adjacent_digits(2345, 2) => [23, 34, 45]
Ex: get_adjacent_digits(2345, 1) => [1, 2, 3, 4]
"""
result = []
limit = (10 ** (tuple_length - 1)) - 1
divisor = in... |
def get_clean_urls(raw_urls):
"""
Known problems so far:
https vs http
https://www.test.de vs https://test.de
https://www.test.de/something vs https://www.test.de/something#something
https://www.test.de/something.html vs https://www.test.de/something.html?something
"""
cleaned_urls = []
... |
def compute_boundary(max_item_id, max_user_id, num_workers):
"""
Compute the indexing boundary
"""
# Assume index is from 0
item_step = int((max_item_id+1) / num_workers)
user_step = int((max_user_id+1) / num_workers)
mov_interval = []
usr_interval = []
for idx in range(num_workers... |
def coluna_para_inteiro(c):
"""
Devolve um inteiro correspondente a coluna da posicao inserida.
:param c: string, coluna da posicao.
:return: int, valor correspondente da coluna.
"""
c_int = {'a': 0, 'b': 1, 'c': 2}
return c_int[c] |
def wrap_around(number: int, start: int, limit: int) -> int:
"""Returns the given number, wrapped around in range `[start, limit[`"""
return start + ((number - start) % (limit - start)) |
def Commas(value):
"""Formats an integer with thousands-separating commas.
Args:
value: An integer.
Returns:
A string.
"""
if value < 0:
sign = '-'
value = -value
else:
sign = ''
result = []
while value >= 1000:
result.append('%03d' % (value % 1000))
value /= 1000
result.... |
def process_json(json_parsed):
"""
Clear outputs from Notebook saved in JSON format
"""
if isinstance(json_parsed, dict):
if 'cells' in json_parsed.keys():
for obj in json_parsed['cells']:
if 'outputs' in obj.keys():
obj['outputs'] = []
els... |
def correct_vgene(v, chain='B'):
"""Makes sure that the given v gene is in correct format,
handles a few different formatsformats."""
if chain is 'B':
v = v.replace('TCR','TR').replace('TRBV0','TRBV').replace('-0','-')
elif chain is 'A':
v = v.replace('TCR','TR').replace('TRAV0','TRAV').... |
def split_lines_by_comment(lines):
"""Doc."""
lines_list = []
new_lines = []
in_multi_line_comment = False
for line in lines:
line = line.strip()
if not line:
continue
if not in_multi_line_comment:
if line.startswith('/*'):
in_multi_l... |
def _group(template, resource, action, proid):
"""Render group template."""
return template.format(
resource=resource,
action=action,
proid=proid
) |
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument |
def valid(candidate):
"""Utility function that returns whether a pass permutation is valid"""
permutation = str(candidate)
# six digit number
if not isinstance(candidate, int) or len(str(candidate)) != 6:
# not a size digit number
return False
# increasing (next digit is > or ==)
... |
def merge_sort(collection):
"""
Counts the number of comparisons (between two elements) and swaps
between elements while performing a merge sort
:param collection: a collection of comparable elements
:return: total number of comparisons and swaps, and the sorted list
"""
comparisons, swaps ... |
def get_local_pod(module, array):
"""Return Pod or None"""
try:
return array.get_pod(module.params["name"])
except Exception:
return None |
def convert_to_list(array_):
"""
Convert all elements and array_ itself to a list.
array_ is returned as is if it can't be converted to a list.
"""
if isinstance(array_, str):
as_list = array_
else:
try:
as_list = list(convert_to_list(i) for i in array_)
excep... |
def __parse_search__(query):
"""
Parse the search by.
First checks if a string is passed and converts = to : in order to later create a dictionary.
If multiple parameters are provided a list is created otherwise the list will only contain one criteria.
NOTE: This must be done because falcon parse t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.