content stringlengths 42 6.51k |
|---|
def _to_addr(worksheet, row, col, row_fixed=False, col_fixed=False):
"""converts a (0,0) based coordinate to an excel address"""
addr = ""
A = ord('A')
col += 1
while col > 0:
addr = chr(A + ((col - 1) % 26)) + addr
col = (col - 1) // 26
prefix = ("'%s'!" % worksheet) if workshe... |
def get_ionic_current_list():
"""
Names of supported whole ionic currents (whole as in ions not channels, e.g. Na, Ca, K, rather than
Nav 1.7, Kdr, etc.
"""
return ['ina', 'ik', 'ica'] |
def level_up(current_level):
"""
-- finds out wht the experience threshold needed to level up. According to the equation [(level x 1000) x 1.25]
-- for example if you are level 2 the experience you need to get to level 3 is (2 x 1000) x 1.25 = 2500
:param current_level:
:return: [int]
"""
... |
def get_classic_document_webpage_uri(data):
"""
Recebe data
retorna uri no padrao
/scielo.php?script=sci_arttext&pid=S0001-37652020000501101&tlng=lang
/scielo.php?script=sci_pdf&pid=S0001-37652020000501101&tlng=lang
"""
if data.get("format") == "pdf":
script = "sci_pdf"
else:
... |
def undirected(edge):
"""Given EDGE, return an canonicalized undirected version."""
return tuple(sorted(edge)) |
def make_image_url(reg, path, name='', tag='', digest='', empty_name_ok=False):
"""Construct a string from (path, name, tag)
Essentially the opposite of parse_image_url()"""
if reg:
path = reg + '/' + path
if path.endswith('/'):
path = path[:-1]
if name:
if tag:
if digest:
image = name + ':' + ta... |
def magic_split_ext(filename, ext_check=True):
"""Splits a filename into base and extension. If ext check is enabled
(which is the default) then it verifies the extension is at least
reasonable.
"""
def bad_ext(ext):
if not ext_check:
return False
if not ext or ext.split... |
def euler100(lim=1000000000000):
"""Solution for problem 100."""
# P(BB) = (b/t) * ((b-1)/(t-1))
# P(BB) = 1/2
# => 2 * b * (b - 1) = t * (t - 1)
# https://oeis.org/A046090
b0, b1 = 1, 3
r0, r1 = 0, 1
while True:
if b0 + r0 > lim:
return b0
b0, b1 = b1, 6 * b... |
def longest_substr_same_letters_after_substt(s, k):
"""Find the length of the longest substring made of only one letter after
substituting at most k letters by any letters.
Time: O(n)
Space: O(1) # size of the alphabet is constant
>>> longest_substr_same_letters_after_substt("aabccbb", 2)
5
... |
def get_block_sizes(resnet_size):
"""
:return: block_sizes determined by resnet_size.
"""
return {
50: [3, 4, 6, 3],
101: [3, 4, 23, 3],
152: [3, 8 ,36, 3]
}.get(resnet_size) |
def try_values(*args):
"""Return the first valid value"""
for arg in args:
if arg:
return arg
return "" |
def to_github_uri(input_uri: str, git_sha: str = "master") -> str:
"""
A basic and crude function that attempts to convert an https://github or git@github.com uri to a github
format uri of github://<org>:<repo>@<sha>/<path>. if conversion can't be done the original uri is returned
:param input_uri: the... |
def pad_sents(sents, pad_token, max_len=200):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
Args:
sents: list[list[str]]list of sentences, where each sentence
is represente... |
def num_to_bin(num, nbits):
"""From decimal number to binary array.
num : decimal number
nbits : number of bits for the output array
The most significant digit is located in the last element of the binarray
"""
binary = []
while num != 0:
bit = num % 2
binary.append(bit)
... |
def is_pair(tiles):
"""
Checks if the tiles form a pair.
"""
return len(tiles) == 2 and tiles[0] == tiles[1] |
def rmse_expr(gray_only: bool = True) -> str:
"""Root Mean Squared Error string to be integrated in std.Expr.
Args:
gray_only (bool, optional):
If both actual observation and prediction are one plane each.
Defaults to True.
Returns:
str: Expression.
"""
retu... |
def in_circle (i,j,r,naxis1,naxis2) :
""" List of positions centered at i,j within r pixels of center """
c = []
r2 = r*r
for ii in range(i-r,i+r+1,1) :
for jj in range(j-r,j+r+1,1) :
rr = (ii-i)**2+(jj-j)**2
if rr < r2 :
if ii >= 0 and jj >= 0 and ii < naxis1 and jj < naxis2 :
c.append((ii,jj))
... |
def find_in_data(ohw_data, name):
"""
Search in the OpenHardwareMonitor data for a specific node, recursively
:param ohw_data: OpenHardwareMonitor data object
:param name: Name of node to search for
:returns: The found node, or -1 if no node was found
"""
if ohw_... |
def square(number):
"""
Return the number of grains on a square
"""
if number not in range(1, 65):
raise ValueError("square must be between 1 and 64")
return 2 ** (number - 1) |
def sumAvailable(value):
"""Sum available_in_bytes over all partitions."""
result = [x['available_in_bytes'] for x in value]
return sum(result) |
def get_URT(pg):
""" takes in 2 or 3 3x3 matricies
returns one if all have 0's in the upper rigth of the matrix
returns a 0 otherwise
"""
size = len(pg)
if size == 2:
condition12 = (pg[0][0][1] == 0) and (pg[1][0][1] == 0)
condition13 = (pg[0][0][2] == 0) and (pg[1][0][2]... |
def somar(a=0,b=0,c=0):
"""
-> faz a soma de 3 valores e mostra o resultado
:param a: primeiro valor
:param b: segundo valor
:param c: terceiro valor
"""
s = a + b + c
return s |
def reformat_filter(fields_to_filter_by):
"""Get a dictionary with all of the fields to filter
Args:
fields_to_filter_by (dict): Dictionary with all the fields to filter
Returns:
string. Filter to send in the API request
"""
filter_req = ' and '.join(
f"{field_key} eq '{fie... |
def _coerce_field_name(field_name, field_index):
"""
Coerce a field_name (which may be a callable) to a string.
"""
if callable(field_name):
if field_name.__name__ == '<lambda>':
return 'lambda' + str(field_index)
else:
return field_name.__name__
return field_... |
def label_map(value):
""" Function that determines the diagnosis according to the Glucose level of an entry.
The three possible diagnosis are: Hypoglycemia, hyperglycemia and normal
:param value: Glucose level
:return: Diagnosis (String)
"""
hypoglycemia_threshold = 70
hyperglycemia_thresho... |
def _make_old_dict(_contents):
"""Convert the new dictionary to the old one for consistency."""
if isinstance(_contents.get('claims', {}), list) and not _contents.get('sitelinks'):
return _contents
old_dict = _contents
new_dict = {
'links': {}, 'claims': [], 'desc... |
def _decompress(ranges):
"""
Decompresses a list with sequential entries that is stored as a string
created from _compress().
See the help of _compress() for more information. Also see below for
examples on the format of the input.
:param ranges: Specially formatted strings containing the rang... |
def get_next_version(req_ver):
"""Get the next version after the given version."""
return req_ver[:-1] + (req_ver[-1] + 1,) |
def word_to_ids(words, word2id_dict, word_replace_dict, oov_id=None):
"""convert word to word index"""
word_ids = []
for word in words:
word = word_replace_dict.get(word, word)
word_id = word2id_dict.get(word, oov_id)
word_ids.append(word_id)
return word_ids |
def comma_separated_arg(string):
""" Split a comma separated string """
return string.split(',') |
def _max_depth(z):
"""get maximal length of lists stored in a dictionary"""
depth = 0
for _, v in z.items():
if type(v) is list or type(v) is tuple:
depth = max(depth, len(v))
return depth |
def valid_symbol(symbol):
"""Returns whether the given symbol is valid according to our rules."""
if not symbol:
return 0
for s in symbol:
if not s.isalnum() and s != '_':
return 0
return 1 |
def has_all_sequences(seeds_for_sequences, length):
"""Return True if we have all permutations up to the length specified."""
return len(seeds_for_sequences) == 2 ** (length + 1) - 2 |
def word_check(seq1,seq2,word):
"""Returns False and aborts if seq2 contains a substring of seq1 of length word. Returns True otherwise"""
for i in range(len(seq1)-word+1):
if seq2.find(seq1[i:i+word])>-1: return seq2.find(seq1[i:i+word])
return -1 |
def cal_sort_key(cal):
"""
Sort key for the list of calendars: primary calendar first,
then other selected calendars, then unselected calendars.
(" " sorts before "X", and tuples are compared piecewise)
"""
if cal["selected"]:
selected_key = " "
else:
selected_key = "X"
if cal["primary"]:
p... |
def normalizeScifloArgs(args):
"""Normalize sciflo args to either a list or dict."""
if isinstance(args, dict) or \
(isinstance(args, (list, tuple)) and (len(args) != 1)):
return args
elif isinstance(args, (list, tuple)):
if isinstance(args[0], (list, tuple, dict)):
... |
def match_context_key(key):
"""Set the case of a context key appropriately for this project, JWST
always uses upper case.
"""
return key.upper() |
def _mock_coordinate_converter(x, y, z):
"""
Mocks the following pyproj based converter function for the values
encountered in the test. Mocks the following function::
import pyproj
proj_wgs84 = pyproj.Proj(init="epsg:4326")
proj_gk4 = pyproj.Proj(init="epsg:31468")
def my_c... |
def is_complex_list(in_list):
"""
Return True if at least one element in in_list is complex, else return False
"""
isComplex = [isinstance(x, complex) for x in in_list]
if True in isComplex:
return True
else:
return False |
def get_highest_scoring_ids(ids_set, id2sc_dic,
scfp_list=False):
"""
Given a set of IDs, and a ID to score mapping, return highest
scoring ID(s) in list.
scfp_list:
If score is stored in first position of list, with ID
mapping to list in id2sc_dic.
>>> ... |
def check_ama_installed(ama_vers):
"""
Checks to verify AMA is installed and only has one version installed at a time
"""
ama_installed_vers = ama_vers
ama_exists = (len(ama_installed_vers) > 0)
ama_unique = (len(ama_installed_vers) == 1)
return (ama_exists, ama_unique) |
def find_order_field(fields, field_position, order_sequence):
"""applies only to BPL order export"""
try:
return fields[field_position].split("^")[order_sequence]
except IndexError:
return "" |
def convert_temperature(val, old_scale="fahrenheit", new_scale="celsius"):
"""
Convert from a temperatuure scale to another one among Celsius, Kelvin
and Fahrenheit.
Parameters
----------
val: float or int
Value of the temperature to be converted expressed in the original
scale.... |
def column_type(schema_property):
"""Take a specific schema property and return the snowflake equivalent column type"""
property_type = schema_property['type']
property_format = schema_property['format'] if 'format' in schema_property else None
col_type = 'text'
if 'object' in property_type or 'arra... |
def smallest_multiple(div_by):
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
even = lambda x, y: x % y == 0
solved ... |
def pattern_count(text: str, pattern: str) -> int:
"""Count the number of occurences of a pattern within text
Arguments:
text {str} -- text to count pattern in
pattern {str} -- pattern to be counted within text
Returns:
int -- The number of occurences of pattern in the test
... |
def is_prime(number):
"""Return True if *number* is prime."""
if (number <= 0):
raise ValueError("Negative numbers or 0 not allowed")
if (round(number) != number):
raise ValueError("This functions is for integers only")
if number == 1: return False
for element in range(2,nu... |
def _get_display_name(name, display_name):
"""Returns display_name from display_name and name."""
if display_name is None:
return name
return display_name |
def is_power_of_two(value: int) -> bool:
"""
Check if ``value`` is a power of two integer.
"""
if value == 0:
return False
else:
return bool(value and not (value & (value - 1))) |
def isnamedtupleinstance(x):
"""From https://stackoverflow.com/a/2166841/6067848"""
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f) |
def kinda_close_tuples(iter, error = 0.05):
"""
Checks if each tuple in the iter contain
2 kinda close elements
"""
for tup in iter:
a = tup[0]
b = tup[1]
if abs((a - b)/max([a, b])) >= error:
print(str(a) + " is not that close to " + str(b))
return Fa... |
def area(l, w):
""" Calculates the area using the length and width of squares and rectangles """
area = (l * w)
return area |
def sleep(seconds):
# type: (float) -> str
"""
Function that returns UR script for sleep()
Args:
time: float.in s
Returns:
script: UR script
"""
return "sleep({})\n".format(seconds) |
def remove_redundant_classes(classes_lvl, keepFirst=True):
"""
Remove classes that appears more than once in the classes' levels
:param classes_lvl: list of each level of classes as list : [[ lvl 0 ], [ lvl 1 ], ...]
:param keepFirst: if True, class will be kept in the min level in which it is present, ... |
def get_encoded_transfers(their_transfer, our_transfer):
"""Check for input sanity and return the encoded version of the transfers"""
if not their_transfer and our_transfer:
raise ValueError(
"There is no reason to provide our_transfer when their_transfer"
" is not provided"
... |
def phedex_url(api=''):
"""Return Phedex URL for given API name"""
return 'https://cmsweb.cern.ch/phedex/datasvc/json/prod/%s' % api |
def parse_join_type(join_type: str) -> str:
"""Parse and normalize join type string. The normalization
will lower the string, remove all space and ``_``, and then
map to the limited options.
Here are the options after normalization: ``inner``, ``cross``,
``left_semi``, ``left_anti``, ``left_outer``... |
def to_utf(line):
"""Converts a bytecode string to unicode. Ignores lines that have unicode
decode errors.
Args:
line (string) a single line in the file
Returns:
a single line that's been cleaned
"""
utf_line = ''
try:
utf_line = str(line, 'utf8')
return utf_l... |
def getAllFilesInRevision(files_info):
"""Checks for existing files in the revision.
Anything that's A will require special treatment (either a merge or an
export + add)
"""
return ['%s/%s' % (f[2], f[3]) for f in files_info] |
def len_or_1(a):
"""
Returns len(a) if a is Iterable. Returns 1 otherwise.
"""
try:
return len(a)
except TypeError:
return 1 |
def SumSquares(lst):
""" sum_squares == PEP8 (forced PascalCase by Codewars) """
try:
return sum(SumSquares(a) for a in lst)
except TypeError:
return lst ** 2 |
def isFrame(obj):
"""Returns true if the object is frame, false if not
@return: If the object is a frame
@rtype: bool"""
return obj.__class__.__name__ == "Frame" |
def intersection(items):
"""Returns the intersecting set contained in items
Args:
items: Two dimensional sequence of items
Returns:
Intersecting set of items
Example:
>>> items = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
>>> intersection(items)
{3}
"""
return ... |
def clean_space(string):
"""
Replace underscores by spaces, replace non-breaking space by normal space,
remove exotic whitespace, normalize duplicate spaces, trim whitespace
(any char <= U+0020) from start and end.
Method adapted from org.dbpedia.extraction.util.WikiUtil class (extraction-framework ... |
def get_file_arg(namespace, files):
"""Detect that a file has been selected to edit or view.
:param namespace: The ``ArgumentParser`` ``Namespace.__dict__``.
:param files: The files dictionary returned from
``src.data.Data``.
:return: Return an absolute path o... |
def hard_is_palindrome(a):
"""Takes in a string of length 1 or greater and returns True if it is a palindrome."""
return ''.join(reversed(a)) == a |
def getAttrSafe(attr, key):
"""
fails safely for accessing optional parameters
:returns value defined for key or None if undefined
"""
ret = None
if key in attr:
ret = attr[key]
return ret |
def bin_search_recur(arr: list, left: int, right: int, key: int) -> int:
"""Recursive Binary Search"""
if right >= left:
mid = left + (right - left) // 2
if arr[mid] == key:
return mid
if arr[mid] > key:
return bin_search_recur(arr, left, mid - 1, key)
els... |
def bake_cupcake(f_cupcake_choice, f_raw_materials, d_raw_materials):
"""Bake cupcake from raw materials
Params:
f_cupcake_choice: str
f_raw_materials: dict
d_raw_materials: dict
Returns:
str
"""
for f_raw_material in f_raw_materials:
d_raw_materials[f_raw_m... |
def merge_parameter(base_params, override_params):
"""
Update the parameters in ``base_params`` with ``override_params``.
Can be useful to override parsed command line arguments.
Parameters
----------
base_params : namespace or dict
Base parameters. A key-value mapping.
override_par... |
def is_str(obj):
"""
Check if object is a string or bytes.
"""
return isinstance(obj, (bytes, str)) |
def oneHotEncodingToClass(oneHotEncodings):
"""
Generates a dictionary where the key is the index of the one hot encoding,
and the value is the class name.
input:
oneHotEncoding: dict, a dictionary where the key is the class name,
and the value is the one hot encoding
output:
... |
def format_array(arr):
""" format dictionary for Athena Project file"""
o = ["'%s'" % v for v in arr]
return ','.join(o) |
def pascal2snake(string: str):
"""String Convert: PascalCase to snake_case"""
return ''.join(
word.title() for word in string.split('_')
) |
def standard_dict(text):
"""Count with standard dict.
"""
d = {}
for key in text:
d.setdefault(key, 0)
d[key] += 1
return d |
def _unfill(v, l = 5):
"""unfill takes a zfilled string and returns it to the original value"""
return [
str(int(v[l * i:l * (i + 1)]))
for i in range(len(v) // l)
] |
def get_det_prefix(pv_info):
"""
Determines which prefix will be passed into the detector init.
Parameters
----------
pv_info: ``str``
The second element in a camview cfg line.
Returns
-------
detector_prefix: ``str``
The prefix to use in the detector init.
"""
... |
def bb_intersection_over_union(boxA, boxB):
"""
Computes IoU (Intersection over Union for 2 given bounding boxes)
Args:
boxA (list): A list of 4 elements holding bounding box coordinates (x1, y1, x2, y2)
boxB (list): A list of 4 elements holding bounding box coordinates (x1,... |
def str2bool(option):
"""Convert a string value to boolean
:param option: yes, true, 1, no, false, 0
:type option: String
:rtype: Boolean
"""
option = option.lower()
if option in ("yes", "true", "1"):
return True
elif option in ("no", "false", "0"):
return False
els... |
def is_module_installed(name):
"""Checks whether module with name 'name' is istalled or not"""
try:
__import__(name)
return True
except ImportError:
return False
except:
import warnings
warnings.warn("There appears to be an error in '{}'.".format(name),UserWarni... |
def _get_bin_num(frequency, bin_size):
"""
Gets the number of the frequency bin whose center is closest to
the specified frequency.
"""
return int(round(frequency / bin_size)) |
def absolute_value (num):
"""
this function returns the absolute
value of the entered number
"""
if num >=0:
return num
else:
return -num |
def checkElementInArray(array:list, x:int, n:int=0):
"""
Check if the given number `x` is present in the
array or not recursively
"""
if n == len(array):
return -1
if array[n] == x:
return n
return checkElementInArray(array,x,n+1) |
def btc(value):
"""Format value as BTC."""
return f"{value:,.8f}" |
def write_zmat_molden(zfile, zmat_atom, zmat_ref, zmat):
"""
Write a Z-matrix in Molden format into zfile.
File is open already and is writeable.
"""
zfile.write('zmat angstroms\n')
zfile.write(str(zmat_atom[0]) + '\n')
if len(zmat_atom) > 1:
zfile.write(str(zmat_atom[1]) + ' ... |
def _reduce_states(state_batch, env_idx):
"""
Reduce a batch of states to a batch of one state.
"""
if state_batch is None:
return None
elif isinstance(state_batch, tuple):
return tuple(_reduce_states(s, env_idx) for s in state_batch)
return state_batch[env_idx: env_idx+1].copy() |
def damage_function_roads_v1(flood_depth, multiplication_factor):
"""
Damage curve adapted from:
Tariq, M.A.U.R., Hoes, O. and Ashraf, M., 2014.
Risk-based design of dike elevation employing alternative enumeration.
Journal of Water Resources Planning and Management, 140(8), p.05014002.
... |
def resolve_overlap_runtimes(runtime_raw):
"""
Find the individual runtime of a list of concurrently running processes
based on the intervals the that the processes are co-running.
i.e.
(i) A --------------------------------- B
(ii) C-------------------------------------D
... |
def str_to_flt(text):
"""
Convect string to float.
:param text: (str) String chunk
:return: (float) or original input string.
"""
try:
return float(text) if text[0].isnumeric() else text
except ValueError:
return text |
def d(x1, y1, x2, y2):
"""Manhattan distance between (x1,y1) and (x2,y2)"""
return abs(x2 - x1) + abs(y2 - y1) |
def _tokenize_chinese_chars(text):
"""
:param text: input text, unicode string
:return:
tokenized text, list
"""
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
... |
def insert_sublist_at(list, index, sublist):
"""
Return the given list with the given sublist inserted at the given
index. If the index is one past the end, append the sublist. If
the index is otherwise out of bounds, return the list unmodified.
"""
if index == 0:
if sublist == ():
... |
def test_conflict_pre(N):
"""A 1-SAT problem that requires N variables to all be true, and the last one to also be false"""
return [[i+1] for i in range(N)] + [[-N]] |
def lstrip_ws_and_chars(string, chars):
"""Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>>... |
def LOS(x1, y1, x2, y2):
"""returns a list of all the tiles in the straight line from (x1,y1) to (x2, y2)"""
point_in_LOS = []
y=y1
x=x1
dx = x2-x1
dy = y2-y1
point_in_LOS.append([x1, y1])
if(dy<0):
ystep=-1
dy=-dy
else:
ystep=1
if dx<0:
xstep=-... |
def is_multioutput(y):
"""Whether the target y is multi-output (or multi-index)"""
return hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1 |
def short_hex(value):
"""
Convert to a nice hex number without the 0x in front to save screen space
:param value: value
:return: short string hex representation
"""
hex1 = hex(value)
hex2 = hex1[2:]
if len(hex2) == 1: hex2 = "0" + hex2
return hex2 |
def ecosystemIsEmpty(ecosystem):
"""
Checks to see that there is at least one mating pair in the ecosystem
If there is at least one mating pair, returns False, or else returns True
"""
returnValue = True
for flock in ecosystem:
if len(flock['adults']) == 2: # having mating pair
... |
def Main(num):
"""
:param num: First input number of concern
:type num: int
:return: Square of the input number
:rtype: int
"""
result = num * num # It is a good practice to always allocate calculated value to a local variable instead of chaining to return or another function
return res... |
def insert_new_targets(start, end, make_lines, targets):
"""
Insert new targets in Makefile between mkgen annotations
"""
return make_lines[: start + 1] + targets + make_lines[end:] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.