content stringlengths 42 6.51k |
|---|
def split_wiki(wikiurl):
"""
Split a wiki url.
*** DEPRECATED FUNCTION FOR OLD 1.5 SYNTAX - ONLY STILL HERE FOR THE 1.5 -> 1.6 MIGRATION ***
Use split_interwiki(), see below.
@param wikiurl: the url to split
@rtype: tuple
@return: (tag, tail)
"""
# !!! use a regex here!
try:
... |
def isNumber(n):
"""retorna true si 'n' es un numero"""
return all(n[i] in "0123456789" for i in range(len(n))) |
def normalize(*args) -> list:
"""Takes the provided arguments, and attempts to replace all
iterables with lists
Non-iterable arguments will be ignored and kept in the list."""
_normd = []
for arg in args:
try:
_normd += list(arg)
except ValueError:
_normd.ap... |
def seen(params):
"""'.seen' & user || Report last time Misty saw a user."""
msg, user, channel, users = params
if msg.startswith('.seen'):
return "core/seen.py"
else:
return None |
def _set_survey_pad(survey_pad, ndim):
"""Check survey_pad, and convert to a list if it is a scalar."""
# Expand to list
if isinstance(survey_pad, (float, type(None))):
survey_pad = [survey_pad] * 2 * ndim
# Check is non-negative or None
if not all((pad is None) or (pad >= 0) for pad in sur... |
def Conv_name_to_c(name):
"""Convert a device-tree name to a C identifier
Args:
name: Name to convert
Return:
String containing the C version of this name
"""
str = name.replace('@', '_at_')
str = str.replace('-', '_')
str = str.replace(',', '_')
str = str.replace('/',... |
def lower_string(text):
"""Summary
Args:
text (TYPE): Description
Returns:
TYPE: Description
"""
if text is not None and len(text) > 0:
return text.lower()
return text |
def age_bin(age, labels, bins):
""" Return a label for a given age and bin.
Argument notes:
age -- int
labels -- list of strings
bins -- list of tuples, with the first tuple value being
the inclusive lower limit, and the higher tuple
value being the exclusive upper lim... |
def device(portnum):
"""Turn a port number into a device name"""
return 'COM%d' % (portnum+1) |
def hgvs_justify_dup(chrom, offset, ref, alt, genome):
"""
Determines if allele is a duplication and justifies.
chrom: Chromosome name.
offset: 1-index genomic coordinate.
ref: Reference allele (no padding).
alt: Alternate allele (no padding).
genome: pygr compatible genome object.
Ret... |
def get_list_of_free_fields(board):
"""the function browses the board and builds a list of all the free squares;\
the list consists of tuples, while each tuple is a pair of row and column numbers
"""
available_pos_list = []
for row_list in board:
for column_number in row_list:
if... |
def any_in(a, b):
"""Checks if 'a in b' is true for any element of a."""
return any(x in b for x in a) |
def common_base(cls: type, *clss: type) -> type:
"""
Overview:
Get common base class of the given classes.
Only ``__base__`` is considered.
Arguments:
- cls (:obj:`type`): First class.
- clss (:obj:`type`): Other classes.
Returns:
- base (:obj:`type`): Common ba... |
def parcours_zigzag(n):
"""Retourne la liste des indices (ligne,
colonne) des cases correspondant a un parcours sinusoidal d'un
tableau de taille n x n.
Ex: pour T = [ [1,2,3],
[4,5,6],
[7,8,9] ]
le parcours correspond aux cases 1,2,3,6,5,4,7,8,9 et la
fonc... |
def hello_name(name):
"""Return Hello World"""
return "Hello {}!".format(name) |
def dict_to_seconds(dict_duration):
"""
Convert a Replicon API duration dict to an integer of the total seconds
"""
seconds = 0
seconds += int(dict_duration['hours']) * 60 * 60
seconds += int(dict_duration['minutes']) * 60
seconds += int(dict_duration['seconds'])
return seconds |
def attribute_is_valid(attribute, key):
"""
Method to return if the attribute is valid
:param attribute:
:param key:
:return:
"""
return attribute.lower().startswith(key) |
def str_to_vim(obj):
"""Encode Python object `obj` as vim string.
Parameters
----------
obj : :obj:
Object to be encoded.
Returns
-------
str
Double-quoted string.
"""
# pylint: disable=undefined-variable # unicode
# Encode
if not isinstance(obj, bytes):
... |
def diff_object_types_histograms(new_histo, old_histo):
""" Returns a new histogram that is the difference of it inputs """
all_keys = set(new_histo.keys()).union(old_histo.keys())
dd = {
k: new_histo[k] - old_histo[k]
for k in all_keys if new_histo[k] - old_histo[k] != 0
}
return d... |
def remove_suffix(name):
"""
remove suffix from given name string
@param name: str, given name sting to process
@return: str, name without suffix
"""
edits = name.split('_')
if len(edits) < 2:
return name
no_suffix = "_".join(edits[:-1])
return no_suffix |
def matrix_add(list1, list2):
"""
Accepts two lists-of-lists of numbers and returns one
list-of-lists with each of the corresponding numbers in the
two given lists-of-lists added together.
Example:
>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
... |
def from_byte( raw_bytes, offset ):
""" Returns a single byte from an array of bytes. """
return raw_bytes[ offset ], offset + 1 |
def digits_count(value):
"""Count the number of digits in the string representation of a scalar
value.
Parameters
----------
value: scalar
Scalar value in a data stream.
Returns
-------
int
"""
return sum(c.isdigit() for c in str(value)) |
def HallucinateNegatives(pos_list):
"""
Reads a list of positive examples and returns a list of negative examples
based on the provided content.
@method HallucinateNegatives
@param {list} pos_list list of positive examples
@return {list} neg_list list of negativ... |
def prec_satoshi(a, b) -> float:
"""
:return: True if A and B differs less than one satoshi.
"""
return abs(a - b) < 0.00000001 |
def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
... |
def getFullUrlForGoogleSheet(sheetId, sheetName='repositories'):
"""Returns spreadsheet csv export compatible export url."""
return f'https://docs.google.com/spreadsheets/d/{sheetId}/gviz/tq?tqx=out:csv&sheet={sheetName}' |
def calc_geometric_spreading(dist, params):
"""Geometric spreading defined by piece-wise linear model.
Parameters
----------
dist : float
Closest distance to the rupture surface (km).
params : List[(float,Optional[float])]
List of (slope, limit) tuples that define the attenuation. F... |
def days_in_month(x):
"""function returning days in the month"""
res = {"January":31, "February":28, "March":31, "April":30, "May":31,
"June":30, "July":31, "August":31, "September":30, "October":31,
"November":30, "December":31}
ans = res.get(x, None)
return ans |
def rescale_minmax_range(data, min_val, max_val, min_scale, max_scale):
"""
Rescales back a dataset using a minmax function with range
:param data:
:param min_val:
:param max_val:
:param min_scale:
:param max_scale:
:return:
"""
return (data - min_scale) / (max_scale - min_scale)... |
def two_of_three(a, b, c):
"""
*** write a proper docstring here ***
>>> two_of_three(1, 2, 3)
13
>>> two_of_three(5, 3, 1)
34
*** add two more testcases here ***
"""
# *** YOUR CODE HERE ***
return a |
def paritysort_list(arr):
"""Move all even numbers to the left and all odd numbers to the right
Args:
arr list[int] - a list of integers to be sorted
Returns:
arr [list] - mutated in place
swap_count (int) - number of exchanges needed to complete the sorting
"""
larr = len(... |
def skip_nulls(dict_obj):
"""
drops key/val pairs where js value is null, not needed in the JSON
:param o: needs to be dict
:return:
"""
reduced = {k: v for k, v in list(dict_obj.items()) if v is not None}
return reduced |
def return_DN_actions_indices(all_actions):
"""To only list the actions which are the same as the default configuration
(also called the "do-nothing actions")"""
return (len(all_actions) - 1) |
def pos_in_rect(rect, pos):
"""Return True if pos is in the rectangle"""
pos_x, pos_y = pos
x, y, width, height = rect
return (x <= pos_x <= x + width
and y <= pos_y <= y + height) |
def construct_string_literal(input_string, language_tag=""):
"""
Constructs an English (@en) string literal in turtle format.
:param input_string: The string to be formatted as turtle sting literal.
:return: English string literal in turtle format
:example:
construct_string_literal(current... |
def cancel_run_endpoint(host):
"""
Utility function to generate the get run endpoint given the host.
"""
return 'https://{}/api/2.0/jobs/runs/cancel'.format(host) |
def _get_dividers(number):
"""
:param number: int from 1 to 1000
:return: all dividers of this number
"""
dividers = []
for i in range(1, number + 1):
if number % i == 0:
dividers.append(i)
return dividers |
def to_int_special(cval, spec, sint):
"""basically return int(cval), but if cval==spec, return sint
cval: int as character string
spec: special value as string
sint: special value as int"""
if cval == spec: return sint
else: return int(cval) |
def get_clusters(vad, tolerance=10):
""" Cluster speech segments.
:param vad: list with labels - voice activity detection
:type vad: list
:param tolerance: accept given number of frames as speech even when it is marked as silence
:type tolerance: int
:returns: clustered spee... |
def remove_characters_from_entities(characters, entities):
"""
Consolidate character and entities found by removing characters from entities.
Parameters:
characters: list of the characters found
entities: list of the entities found
Returns:
updated characters and entities lists
""... |
def get_output_image_filename(output_image_file: str) -> str:
"""
Return the output filename from the an expected file name
(the lib only support PNG files as output format)
"""
if not output_image_file:
output_image_file = 'output.png'
else:
# If output image doesn't have png su... |
def main_REVC(dna):
"""Find complementing a strand of DNA."""
if len(dna) <= 0 or len(dna) > 1000:
raise Exception('Input Error')
sequence_dic = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
return ''.join([sequence_dic[b] for b in reversed(dna)]) |
def dict_merger(dict1, dict2):
"""
Merge rekursively two nested python dictionaries.
If key is in both digionaries tries to add the entries in both dicts.
(merges two subdicts, adds strings and numbers together)
:return: dict
"""
new_dict = dict1.copy()
if not dict1:
return di... |
def normalize_url(url: str) -> str:
"""
Remove leading and trailing slashes from a URL
:param url: URL
:return: URL with no leading and trailing slashes
:private:
"""
if url.startswith('/'):
url = url[1:]
if url.endswith('/'):
url = url[:-1]
return url |
def fi(d, f, n):
"""
Calculates the index of a certain frequency f in np.fft.fftfreq(n, d=d)
The result is rounded to the next integer, if there is no frequency bin
that fits this frequency exactly.
f(requency) = i(ndex) / (d * n)
=> i = f * d * n
Args:
d (float):
step size between the s... |
def volume_of_rectangle(bounds):
"""
Computes the volume of the rectangle whose bounds are given
Args:
bounds (List[List[float]]): A list of the intervals which composed
the rectangle
"""
product = 1
for a, b in bounds:
product *= b - a
return product |
def merge(a, b, path=None, overwrite=True):
"""merges b into a
Examples
--------
>>> from pprint import pprint
>>> pprint(merge({'a':{'b':1},'c':3},{'a':{'b':2}}))
{'a': {'b': 2}, 'c': 3}
"""
if path is None:
path = []
for key in b:
if key in a:
if isins... |
def is_power_of_two_brian_kernighan(number):
"""Checks whether a given integer is a power of 2
It uses the Brian Kernighan algorithm used to count the set bits.
We know that powers of 2 only have 1 set bit.
e.g 2^0 = 1, 2^1= 10, 2^2= 100 ...
By applying a bitwise & to the given integer and the nex... |
def list2cmdline(seq):
""" Extended version of list2cmdline from subprocess.
Additional conditions sufficient to wrap argument with double quotes are added:
* argument contains parenthesis.
"""
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to se... |
def URLify(s: str) -> str:
"""Replaces all spaces in a string with "%20".
>>> URLify("Mr John Smith")
'Mr%20John%20Smith'
>>> URLify("MrJohnSmith")
'MrJohnSmith'
>>> URLify("Jack and Jill went up the hill")
'Jack%20and%20Jill%20went%20up%20the%20hill'
"""
characters = []
for ... |
def associate(first_list, second_list, offset, max_difference):
"""
Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim
to find the closest match for every input tuple.
Input:
first_list -- first dictionary of (stamp,data) tuples
second_list -- second... |
def makearglist(args, kwargs, exarg = None, exkwarg = None):
"""
Generates argument list for a function
Arguments:
args = list of names of arguments or None if none
kwargs = dict of keyword argument names to default values as strings,
or None if none
"""
arglist... |
def height(tree):
"""Return the height of an AVL tree. Relies on the balance factors
being consistent."""
if tree is None:
return 0
else:
l, v, r, b = tree
if b <= 0:
return height(l) + 1
else:
return height(r) + 1 |
def median_solution_1(a, b, c):
"""
compute the median of three values using if statements
Parameters
----------
a : float, int
the first value
b : float, int
the second value
c : float, int
the third value
Returns
-------
the median of values a,... |
def remove_white_space(str_list: list) -> list:
"""Removes any leading / tailing white space"""
return [string.strip() for string in str_list] |
def correct_col(column_name):
"""
Takes HuID country names and returns the corresponding
country name from the Friedlingstein et al (2019)
national data.
"""
corr_col_name = column_name
# Corrected South America
if 'Bolivia' in column_name:
corr_col_name = 'Bolivia'
elif 'Ven... |
def sr( redchan, nirchan ):
"""
Simple Vegetation ratio
sr( redchan, nirchan )
"""
redchan = 1.0*redchan
nirchan = 1.0*nirchan
result =(nirchan/redchan)
return result |
def mult_pair(pair):
"""Return the product of two, potentially large, numbers."""
return pair[0]*pair[1] |
def objective_function_dh(p, g, pub_key, a):
"""
Computes the objective function for discovering one of Diffie-Hellman private keys with the hill climbing algorithm
"""
return -abs((g ** a) % p - pub_key) |
def _gpath( path ):
"""
"https://test.backlog.jp/" -> "https://test.backlog.jp/"
"https://test.backlog.jp" -> "https://test.backlog.jp/"
"""
if path == "":
return "./"
elif path.endswith( "/" ):
return path
else:
return path + "/" |
def is_command(text):
"""
Checks if `text` is a command. Telegram chat commands start with the '/' character.
:param text: Text to check.
:return: True if `text` is a command, else False.
"""
if text is None:
return None
return text.startswith('/') |
def formatASet(theSet):
"""Format a set of strings as a string.
The given set is returned enclosed by braces and with elements
separated by commas.
Args:
theSet (set of str): The set to be formatted.
Returns:
str: A string representing theSet, enclosed by braces and with
... |
def groupkeys(keys, patterns):
"""Groups the given set of keys using the given patterns.
It runs through the patterns sequentially, removing those from keys.
Returns a dict with {pattern: [matching keys]}.
Unmatches keys are added with None as the key."""
from collections import defaultdict
from... |
def generate_candidate_one_itemset(transactions):
"""Generates candidate 1-itemset."""
return {frozenset([item, item]) for item in set.union(*transactions)} |
def is_module_installed(module_name):
"""
Simpler version of spyder.utils.programs.is_module_installed.
"""
try:
mod = __import__(module_name)
# This is necessary to not report that the module is installed
# when only its __pycache__ directory is present.
if getattr(mod, ... |
def varsdict(obj, hidden=False, callables=False):
"""
Creates a dict of the attributes of a specified object.
Works (unlike __builtin__.vars) even on objects without a __dict__ attribute.
Adapted from: http://stackoverflow.com/a/31226800
:param obj: the object/value.
:param hidden: If True, e... |
def split_filtStr(filtStr):
"""
...doctest:
>>> split_filtStr('a>b;c<=d; e == f; bc=[0,1]')
['a>b', 'c<=d', 'e == f', 'bc=[0,1]']
>>> split_filtStr('a>b AND c<=d AND e == f')
['a>b', 'c<=d', 'e == f']
>>> split_filtStr('bc=[0,1]')
['bc=[0,1]']
>>> split_f... |
def has_nth_bit_set(number, n):
"""
Check if a specific bit is set in a number.
:param number: The number to check.
:param n: The bit if set
:return:
"""
return ((1 << n) & number) > 0 |
def check_all_shapes_equal(iterable) -> bool:
"""
Check if the shape attribute of all elements of an iterable (e.g., list) are equal.
:param iterable: iterable to check
:return: bool saying if all elements are equal
"""
iterator = iter(iterable)
try:
first = next(iterator)
excep... |
def element_finder(compound_list):
"""
Args:
compound_list (list) - list of the compounds in the reaction with correct spacing and capitalization
Returns (list):
list of elements in the reaction
Example:
>>>element_finder(["H2O", "C6H12O6", "CH3CH2(CHO)CH3"])
... |
def keep_comment(text, min_ascii_fraction=0.75, min_length=1):
""" For purposes of vocabulary creation ignore non-ascii documents """
len_total = len(text)
if len_total < min_length:
return False
len_ascii = sum(c.isalpha() for c in text)
frac_ascii = float(len_ascii) / float(len_total)
if frac_ascii < ... |
def change_lists_to_strings(results):
"""
updates lists to strings for loading into Pandas
:param dict results: dictionary of results to process
:return dict: dictionary of results
"""
for row in results:
for data in row:
if type(row[data]) == list:
# if there... |
def set_predict(kwargs):
"""Set attr argument and proba"""
out = dict()
proba = kwargs.pop('proba', False)
if proba:
out['proba'] = proba
out['attr'] = 'predict_proba' if proba else 'predict'
return out |
def get_value(obj, key, default_value):
"""
:param obj: dictionary
:param key: key
:param default_value: return default value if obj[key] is not existed.
:return: the value of an argument. If no such an argument, return a default value
"""
return obj[key] if type(obj) is dict and key in ob... |
def get_highest_rated_show(shows):
"""
This function loops through a list of shows and returns the name and creators of
the highest rated show
Parameters:
shows (list): A list of shows
Returns:
(list): A list representing the show with the highest rating
"""
highest_rating ... |
def do_some_stuffs_with_input(input_string):
"""
This is where all the processing happens.
Let's just read the string backwards
"""
print("Processing that nasty input!")
return "Pong!" |
def source_metadata(calexp, src, **kwargs):
""" Metadata from source catalogue.
Args:
task_result (dict): The result of ProcessCcdTask.
Returns:
dict: The dictionary of results
"""
result = {}
# Count the number of sources
result["n_src_char"] = len(src)
return result |
def _split(text):
"""Split a line of text into two similarly sized pieces.
>>> _split("Hello, world!")
('Hello,', 'world!')
>>> _split("This is a phrase that can be split.")
('This is a phrase', 'that can be split.')
>>> _split("This_is_a_phrase_that_can_not_be_split.")
('This_is_a_phrase_th... |
def handle_dots(string):
"""Handle `.` chars accordingly, i.e. remove if last and add a space after
:argument string: string to handle dots in
:type string: str
:returns str
"""
if '.' in string:
if string[-1] == '.':
string = string[:-1]
else:
string =... |
def isBase64(sb):
"""
Check if both string and bytes objects are in base64.
"""
import base64
try:
if isinstance(sb, str):
# If there's any unicode here, an exception will be thrown and the function will return false
sb_bytes = bytes(sb, 'ascii')
... |
def get_vector18():
"""
Return the vector with ID 18.
"""
return [
0.37406776,
0.25186448,
0.37406776,
] |
def mem_add_payload(mem_default_payload):
"""Provide a membership payload for adding a member."""
add_payload = mem_default_payload
add_payload["action"] = "added"
return add_payload |
def has_only(string, chars):
"""
Check whether the string contains only the specified characters.
"""
for char in string:
if not char in chars: return False
return True |
def hb_tag (tag):
"""Convert a tag to ``HB_TAG`` form.
Args:
tag (str): An OpenType tag.
Returns:
A snippet of C++ representing ``tag``.
"""
return u"HB_TAG('%s','%s','%s','%s')" % tuple (('%-4s' % tag)[:4]) |
def build_concentartion(species_id, number):
"""
Builds the concentration component for each species
Parameters
----------
species_id : int
species id from the species_indices dictionary
number : float
stoichiometric co-eff of the species
... |
def primedigits(n):
""" Counts the number of prime digits in a given integer
"""
try:
if type(n) is int:
return sum([True for d in str(n) if int(d) in [2, 3, 5, 7]])
else:
raise TypeError("Given input is not a supported type")
except TypeError as e:
print(... |
def compact_dict(dictionary):
"""Return a copy of dictionary with None values filtered out."""
return {k: v for k, v in dictionary.items() if v is not None} |
def fold_spaces(low_spaces, high_spaces):
"""
Creates all possible combinations of hyperspaces.
Parameters
----------
* `low_spaces` [list, shape=(n_spaces,)]:
lower spaces defined by hyperspace classes.
* `high_spaces` [list, shape=(n_spaces,)]:
lower spaces defined by hypersp... |
def check_multi_location(alignment, tags, log=None):
"""
See if the read was mapped at multiple locations.
if so, it returns True and can be counted in the optional log
:param alignment: the read
:param tags: alignment tags as dict
:return:
"""
if 'XA' in tags:
alignme... |
def fortrandouble(x):
"""Converts string of Fortran double scientific notation to python float.
Example
-------
>>> val = '-0.12345D+03'
>>> print(fortrandouble(val))
-123.45
"""
return float(x.replace('D', 'E')) |
def get_alma_barcode(identifiers_list):
"""Prend une liste d'identifiant et retourne un code-barre
"""
for identifier in identifiers_list:
if identifier['id_type']['value'] == 'BARCODE':
return identifier['value']
return "None" |
def sqrt(x):
""" Calculate the square root of the input AD object, integer, or float
INPUTS
=======
x: input value, an AD object, int, or float
RETURNS
========
result: square root of x
EXAMPLES
=========
>>> x = ad.AD(2.0, [1.0,0.0])
>>> y = ad.AD(3.0, [0.0,1.... |
def try_lower(x):
"""Opportunistically lower() a string if it is a string."""
return x.lower() if hasattr(x, 'lower') else x |
def scored(age):
"""Score a file based on its size and scaled age where
AgeScore = nBytesFile * ageScoreFile
@param age <float>:
Age of file in days
@ return score <float>:
Age-scaled score of a file
"""
# Default score for files older than 1000 days
score = 1.0 # or ~2.7 ye... |
def get_train_valid_test_split_(splits_string, size):
""" Get dataset splits from comma or '/' separated string list."""
splits = []
if splits_string.find(',') != -1:
splits = [float(s) for s in splits_string.split(',')]
elif splits_string.find('/') != -1:
splits = [float(s) for s in sp... |
def binary_search_parameters(length):
""" The TTF specification has several places that require binary search
parameters. For an example look at the CMAP Format 4 table.
:param length: The range over which the search will be performed.
:return: The 2 parameters required.
"""
search_range = 2... |
def mult(c,n):
""" mult uses only a loop and addition
to multiply c by the integer n
"""
result = 0
for x in range(n):
result += c
return result |
def merge_successors(strings):
"""
Merges every string which is a prefix to one other string
:param strings:
:return:
"""
to_remove = set()
for n, string in enumerate(strings):
same_beginnings = (s for s in strings if s.startswith(string)
and s != string)
... |
def make_gauge(name, value, m_type='gauge'):
"""Return a dict for use as a gauge."""
return {
'name': name,
'value': value,
'type': m_type
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.