content stringlengths 42 6.51k |
|---|
def _DiscardUnusedTemplateLabelPrefixes(labels):
"""Drop any labels that end in '-?'.
Args:
labels: a list of label strings.
Returns:
A list of the same labels, but without any that end with '-?'.
Those label prefixes in the new issue templates are intended to
prompt the user to enter some label... |
def iobes2iob(iobes):
"""Converts a list of IOBES tags to IOB scheme."""
dico = {pfx: pfx for pfx in "IOB"}
dico.update({"S": "B", "E": "I"})
return [dico[t[0]] + t[1:] if not t == "O" else "O" for t in iobes] |
def doc_has_content(doc):
"""Check if doc has content"""
len_title = len(doc['title'].split())
len_content = len(doc['content'].split())
# 50: mean_len_content - 2*mean_len_content*standard_deviation in v1
return len_content - len_title > 50 |
def matrix(user_item, item_users):
"""Cria a matrix user (linha) x itens (coluna)"""
list_itens = []
#matriz_user_item = numpy.zeros( len( item_users))
matriz_user_item = []
index_itens = dict()
cont=0
for item_user in item_users.keys():
index_itens[item_user] = cont
... |
def compute_TF_FP_FN_micro(label_dict):
"""
compute micro FP,FP,FN
:param label_dict_accusation: a dict. {label:(TP, FP, FN)}
:return:TP_micro,FP_micro,FN_micro
"""
TP_micro, FP_micro, FN_micro = 0.0, 0.0, 0.0
for label, tuplee in label_dict.items():
TP, FP, FN = tuplee
TP_micro = TP_micro + TP
... |
def modulo_expo(a, b, m):
""" compute a^b mod m """
if b == 0:
return 1
temp = modulo_expo(a, b >> 2, m)
temp *= 2
if b & 1 > 0:
temp *= a
temp %= m
return temp |
def get_concordance_string(text,
keyword,
idx,
window):
"""
For a given keyword (and its position in an article), return
the concordance of words (before and after) using a window.
:param text: text
:type text: string
:param keyword: ... |
def invert_for_next(current):
"""
A helper function used to invert
the orientation indicator of the
next panel based on the current panel
i.e. if a parent is horizontal a
child panel must be vertical
:param current: Current parent
orientation
:type current: str
:return: child... |
def hello(name: str) -> str:
"""
Say hello
:param name: Who to say hello to
:return: hello message
"""
return f"Hello {name}!" |
def find_winner_line(line):
"""Return the winner of the line if one exists.
Otherwise return None.
A line is a row, a column or a diagonal.
"""
if len(line) != 3:
raise ValueError('invalid line')
symbols = set(line)
if len(symbols) == 1:
# All equal.
return line[0] ... |
def _upper_first(name):
"""Return name with first letter uppercased."""
if not name:
return ''
return name[0].upper() + name[1:] |
def check_if_odd(num):
"""
Checks if number is odd
Args:
num :
(Generated by docly)
"""
return True if num % 2 != 0 else False |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
int value of interval in milliseconds
None if interval p... |
def encode_str(s):
"""Returns the hexadecimal representation of ``s``"""
return ''.join("%02x" % ord(n) for n in s) |
def group_lines(lines):
"""Split a list of lines using empty lines as separators."""
groups = []
group = []
for line in lines:
if line.strip() == "":
groups.append(group[:])
group = []
continue
group.append(line)
if group:
groups.append(g... |
def distance_km(point1, point2):
"""
Convert from degrees to km - approximate."
Args:
point1: Array-like with 2 members (lat/long).
point2: Array-like with 2 members (lat/long).
Returns:
float: distance in kilometres
"""
return ((point1[0] - point2[0]) ** 2 + (point1[1] ... |
def json_filename(symbol):
"""Appends .json to the string SYMBOL"""
return "stockJSON/" + symbol + ".json" |
def is_power_of_two(number: int) -> bool:
"""Check if input is a power of 2.
Parameters
----------
number: int
Returns
-------
bool
"""
return number != 0 and ((number & (number - 1)) == 0) |
def incrementing_pattern(size: int) -> bytes:
"""
Return `size` bytes with a pattern of incrementing byte values.
"""
ret = bytearray(size)
for i in range(0, size):
ret[i] = i & 0xff
return bytes(ret) |
def num_segments(paths):
"""How many individual line segments are in these paths?"""
return sum(len(p)-1 for p in paths) |
def local_rank(worker_id):
""" use a different account in each xdist worker """
if "gw" in worker_id:
return int(worker_id.replace("gw", ""))
elif "master" == worker_id:
return 0
raise RuntimeError("Can not get rank from worker_id={}".format(worker_id)) |
def one_hot_encode(integer_encoding, num_classes):
""" One hot encode.
"""
onehot_encoded = [0 for _ in range(num_classes)]
onehot_encoded[integer_encoding] = 1
return onehot_encoded |
def get_workflow_id(identifier: int) -> str:
"""Get a hexadecimal string of eight characters length for the given
integer.
Parameters
----------
identifier: int
Workflow indentifier
Returns
-------
string
"""
return hex(identifier)[2:].zfill(8).upper() |
def compile_continued_fraction_representation(seq):
"""
Compile an integer sequence (continued fraction representation) into its corresponding fraction.
"""
from fractions import Fraction
# sanity check
assert seq
# initialize the value to be returned by working backwards from the last numb... |
def _validate_bool(value):
"""Return parameter value as boolean.
:param str value: The raw parameter value.
:param dict content: The template parameter definition.
:returns: bool
"""
if value in [True, False]:
return value
try:
if str(value).lower() == 'true':
ret... |
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
length =0
for letter in hand:
length += hand[letter]
return length |
def partitionByFunc(origseq, partfunc):
"""Partitions a sequence into a number of sequences, based on the `partfunc`.
Returns ``(allseqs, indices)``, where:
- `allseqs` is a dictionary of output sequences, based on output values
of `partfunc(el)`.
- `indices` is a dictionary of ``(outv... |
def _stringify_time_unit(value: int, unit: str):
"""
Returns a string to represent a value and time unit,
ensuring that it uses the right plural form of the unit.
>>> _stringify_time_unit(1, "seconds")
"1 second"
>>> _stringify_time_unit(24, "hours")
"24 hours"
>>> _stringify_time_unit(... |
def inverse_mod(a, m):
"""Inverse of a mod m."""
if a < 0 or m <= a:
a = a % m
# From Ferguson and Schneier, roughly:
c, d = a, m
uc, vc, ud, vd = 1, 0, 0, 1
while c != 0:
q, c, d = divmod(d, c) + (c,)
uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc
# At this po... |
def process_predictions(lengths, target, raw_predicted):
"""
Removes padded positions from the predicted/observed values and
calls inverse_transform if available.
Args:
lengths: Lengths of the entries in the dataset.
target: Target feature instance.
raw_predicted: Raw predicted/... |
def is_user_info_complete(user):
"""
Returns True if the user has provided all of the required registration info
Args:
user (django.contrib.auth.models.User):
Returns:
bool: True if the user has provided all of the required registration info
"""
return (
hasattr(user, "... |
def get_all_context_names(context_num):
"""Based on the nucleotide base context number, return
a list of strings representing each context.
Parameters
----------
context_num : int
number representing the amount of nucleotide base context to use.
Returns
-------
a list of st... |
def pretty_concat(strings, single_suffix='', multi_suffix=''):
"""Concatenates things in a pretty way"""
if len(strings) == 1:
return strings[0] + single_suffix
elif len(strings) == 2:
return '{} and {}{}'.format(*strings, multi_suffix)
else:
return '{}, and {}{}'.format(', '.joi... |
def getDim(scale,supercell):
"""
Helper function for to determine periodicity of a crystal, used in
various functions
inputs
--------
scale (float): The ratio of final and initial network size
supercell (int): The supercell size used to generate the new
... |
def remove_dups(lst):
""" return a copy of lst with duplicates of elements eliminated. For example, for lst = [a, a, a, a, b, c, c, a, a, d, e, e, e, e], the returned list is [a, b, c, d, e]. """
s = sorted(lst)
return [v for i, v in enumerate(s) if i == 0 or v != s[i-1]] |
def bin2sint(data):
"""Convert a byte-string to a signed integer."""
number = 0
# convert binary bytes into digits
arr = list()
for byte in data:
arr.append(byte)
byteslen = len(data)
# Now do the processing
negative = False
if arr[byteslen - 1] >= 128:
negative = Tr... |
def check_if_param_valid(params):
"""
Check if the parameters are valid.
"""
for i in params:
if i == "filter_speech_first":
if not type(params["filter_speech_first"]) == bool:
raise ValueError("Invalid inputs! filter_speech_first should be either True or False!")
... |
def expand_range(val):
"""Expands the Haskell-like range given as a parameter
into Python's `range` object. The range must be finite.
Args:
val (str): a range to expand.
Returns:
range: resulting range.
Raises:
ValueError: if given an invalid Haskell-like range.
>>> e... |
def _get_entity(response):
"""Returns the entity from an API response.
"""
path = response['next'].split('?')[0]
return path.split('/')[3] |
def conform_to_argspec(args,kwargs,argspec):
"""Attempts to take the arguments in arg and kwargs and return only those which can be used
by the argspec given."""
regargs, varargs, varkwargs, defaults = argspec
N = len(regargs)
# shallow copy arguments
newargs = list(args)
newkwargs = kwa... |
def get_page(data, page):
"""Get nth page of a data, with each page having 20 entries."""
begin = page * 20
end = page * 20 + 20
if begin >= len(data):
return []
elif end >= len(data):
return data[begin:]
else:
return data[begin:end] |
def color_to_rgb(c):
"""Convert a 24 bit color to RGB triplets."""
return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF) |
def determine_end_of_role(prev_prefix, prefix):
"""
determine whether the previous token was the last one of the role
:param str prev_prefix: prefix of the previous BIO annotation
:param str prefix: current prefix of BIO annotation
:rtype: bool
:return: True -> previous token was the last one,... |
def potential_snow_layer(ndsi, green, nir, tirs1):
"""Spectral test to determine potential snow
Uses the 9.85C (283K) threshold defined in Zhu, Woodcock 2015
Parameters
----------
ndsi: ndarray
green: ndarray
nir: ndarray
tirs1: ndarray
Output
------
ndarray:
boole... |
def factorial(n: int) -> int:
"""
Return the factorial of a number.
:param n: Number to find the Factorial of.
:return: Factorial of n.
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(10))
True
>>> factorial(-5) # doctest: +ELLIPSIS
Traceback (mos... |
def check_if_advanced_options_should_be_enabled(advanced_fields) -> bool:
"""
Checks whether the advanced options box should be enabled by checking if any of the advanced options have existing values.
:param advanced_fields: the field group
"""
return any(item is not None for item in advanced_fields... |
def space_space_fix(text):
"""Replace "space-space" with "space".
Args:
text (str): The string to work with
Returns:
The text with the appropriate fix.
"""
space_space = ' '
space = ' '
while space_space in text:
text = text.replace(space_space, space)
return t... |
def triangle_area(base, height):
"""Returns the area of a triangle"""
return base * height / 2 |
def call_and_return(callee, returnee):
"""
A helper function to wrap a side effect (callee) in an expression.
@param callee: a 0-ary function
@param returnee: a value
@rtype: type of returnee
"""
callee()
return returnee |
def intersection(d1, d2):
"""Intersection of two dicts.
Return data in the first dict for the keys existing in both dicts."""
ret = {}
for k in d1:
if k in d2:
ret[k] = d1[k]
return ret |
def _convert_wmi_type_to_xsd_type(predicate_type_name):
"""
This converts a WMI type name to the equivalent XSD type, as a string.
Later, the conversion to a 'real' XSD type is straightforward.
The point of this conversion is that it does not need rdflib.
WMI types: https://powershell.one/wmi/datat... |
def padVersionString(versString, tupleCount):
"""Normalize the format of a version string"""
if versString is None:
versString = '0'
components = str(versString).split('.')
if len(components) > tupleCount:
components = components[0:tupleCount]
else:
while len(components) < tu... |
def SplitScmUrl(url):
"""Given a repository, return a set containing the URL and the revision."""
url_split = url.split('@')
scm_url = url_split[0]
scm_rev = 'HEAD'
if len(url_split) == 2:
scm_rev = url_split[1]
return (scm_url, scm_rev) |
def _generate_action(action_name, commands):
"""Generate action in imagebuilder components."""
action = {"name": action_name, "action": "ExecuteBash", "inputs": {"commands": [commands]}}
return action |
def three_sum(a, s):
"""
Gets pairs of three whose sum is 0
Parameters:
a : array
s : sum to find equivalent to
Returns:
1 : If triplets found
0 : if triplets not found
"""
a.sort()
answer_set = []
for i in range(len(a) - 3):
l = i+1
r = ... |
def replace_key_with_read_id(x):
"""
now that data is grouped by read properly, let's replace the key with
the read ID instead of file line number to make sure joins are correct.
"""
return x[1][0], x[1] |
def rol(int_type, size, offset):
"""rol(int_type, size, offset) -> int
Returns the value of int_type rotated left by (offset mod size) bits.
"""
mask = (1 << size) - 1
offset %= size
left = (int_type << offset) & mask
circular = (int_type & mask) >> (size - offset)
return left | circula... |
def round_point(p, n):
"""round"""
return (round(p[0], n), round(p[1], n)) |
def _filter_for_numa_threads(possible, wantthreads):
"""Filter to topologies which closest match to NUMA threads
:param possible: list of nova.objects.VirtCPUTopology
:param wantthreads: ideal number of threads
Determine which topologies provide the closest match to
the number of threads desired by... |
def _until_dh(splited):
""" Slice until double hyphen """
i = 0
for i, s in enumerate(splited):
if s == "--":
return splited[:i], i + 1
elif s.startswith("--"):
return splited[:i], i
return splited[:], i + 1 |
def set_authenticated(cookie_string, user_id, prefix='', rconn=None):
"""Sets cookie into redis, with user_id as value
If successfull return True, if not return False."""
if rconn is None:
return False
if (not user_id) or (not cookie_string):
return False
cookiekey = prefix+co... |
def orth(string):
"""Returns a feature label as a string based on the capitalization and other orthographic characteristics of the string."""
if string.isdigit():
return 'DIGIT'
elif string.isalnum():
if string.islower():
return 'LOWER'
elif string.istitle():
... |
def transform_cnvtag(cnvtag):
"""
Rename some cnv tags for downstream processing.
"""
split_call = cnvtag.split("_")
# exon9hyb_star5 and dup_star13 are unlikely to occur together with yet another sv.
if cnvtag != "exon9hyb_star5":
while "exon9hyb" in split_call and "star5" in split_call... |
def sort_project_list(in_list):
"""
Sort and clean up a list of projects.
Removes duplicates and sorts alphabetically, case-insensitively.
"""
# replace spaces with underscores
in_list_2 = [i.replace(" ", "_") for i in in_list]
# remove duplicate values if we ignore case
# http://stacko... |
def try_composite(a, d, n, s):
"""check composite number for rabin-miller primality test"""
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
"""n is definitely composite"""
return True |
def _format_lineno(lineno):
"""Just convert the line number into a better form.
"""
if lineno is None:
return ""
return ":" + str(lineno) |
def down(spiral: list, coordinates: dict) -> bool:
"""
Move spiral down
:param coordinates: starting point
:param spiral: NxN spiral 2D array
:return: boolean 'done'
"""
done = True
while coordinates['row'] < len(spiral):
row = coordinates['row']
col = coordinates['col']
if row =... |
def extract_file_type(file_location:str) -> str:
"""
A function to return the type of file
-> file_location: str = location of a file in string... ex : "C:\\abc\\abc\\file.xyz"
----
=> str: string of the file type, ex : "xyz"
"""
if not isinstance(file_location,str):
raise TypeError... |
def row_column_translation(row,col):
"""Converts a coordinate made by a letter/number couple in the index usable with the array that represents the board"""
row = int(row) - 1
if row % 2 != 0:
cols = range(ord("a"),ord("a")+7,2)
else:
cols = range(ord("b"),ord("b")+7,2)
if ord(col) not in cols:
return -1,-1... |
def teacher_input(random_numbers):
"""
Defines the contents of `teacher-input.txt` to which `run.sh`
concatenates the student submission as the exercise is posted to
MOOC Grader for grading.
Generates 3 random numbers and forms a string containing
the MathCheck configuration for this exercise.
"""
ret... |
def _sort_by_amount(transactions: list) -> list:
"""
Sort transactions by amount of dollars.
"""
sorted_transactions = sorted(transactions,
key=lambda transaction: transaction["amount"],
reverse=True)
return sorted_transactions |
def coding_problem_21(times):
"""
Given an array of time intervals (start, end) for classroom lectures (possibly overlapping),
find the minimum number of rooms required.
Example:
>>> coding_problem_21([(30, 75), (0, 50), (60, 150)])
2
"""
start_times = [(t[0], 1) for t in times] # [(30... |
def parse_unsigned_int(data: bytes, bitlen: int):
"""Parses an unsigned integer from data that is `bitlen` bits long."""
val = '0b' + ''.join([f'{b:08b}' for b in data])
return int(val[0:2 + bitlen], 2) |
def get_schema_short_name(element):
"""The schema short name reveals is a stand-in for the platform that this element is for and can be derived from the namespace URI
@type element: Element
@param element: the XML Element
@rtype: string
@return: the "short name" of the platform schema or None ... |
def parse_xff(header_value):
"""
Parses out the X-Forwarded-For request header.
This handles the bug that blows up when multiple IP addresses are
specified in the header. The docs state that the header contains
"The originating IP address", but in reality it contains a list
of all the intermedi... |
def to_devport(pipe, port):
"""
Convert a (pipe, port) combination into a 9-bit (devport) number
NOTE: For now this is a Tofino-specific method
"""
return pipe << 7 | port |
def get_extension(_str):
"""
Get ".ext" (extension) of string "_str".
Args:
_str (str)
Returns:
ext (str)
extension of _str
Example:
| >> get_extension("random_plot.png")
| ".png"
"""
_str = str(_str).rsplit("/", 1)[-1]
ext = "."+_str.rsplit... |
def global_line_editor(gle=None):
"""Access the global lineeditor instance.
Args:
gle: (optional) new global lineeditor instance
Returns:
Current global lineeditor instance
"""
global _gle_data
if gle is not None:
_gle_data = gle
return _gle_data |
def set_version(ver: str):
""" Set the version of the API. This function should really only
be used in bot.py.
"""
global version
version = ver
return version |
def check_ends(astring):
"""string -> bool
Write a function check_ends (astring), which takes in a string astring and returns True if the first character in astring is the same as the last character in astring. It returns False otherwise. The check_ends function
does not have to work on the empty string (the s... |
def join_keywords(l):
""" join a list of keywords with '+' for BingSearch """
return u'+'.join(l) |
def strip_prefix(string, prefix):
"""Returns a copy of the string from which the multi-character prefix has been stripped.
Use strip_prefix() instead of lstrip() to remove a substring (instead of individual characters)
from the beginning of a string, if the substring is present. lstrip() does not match substrin... |
def to_pilot_alpha(word):
"""Returns a list of pilot alpha codes corresponding to the input word
>>> to_pilot_alpha('Smrz')
['Sierra', 'Mike', 'Romeo', 'Zulu']
"""
pilot_alpha = ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot',
'Golf', 'Hotel', 'India', 'Juliett', 'Kilo', 'Lima', 'M... |
def normalize_attribute(attr):
"""
Normalizes the name of an attribute which is spelled in slightly different
ways in paizo HTMLs
"""
attr = attr.strip()
if attr.endswith(':'):
attr = attr[:-1] # Remove trailing ':' if any
if attr == 'Prerequisites':
attr = 'Prerequisite' # N... |
def meters_to_feet(meters: float) -> float:
"""
This function takes a float representing a measurement in meters
and returns the corresponding value converted to feet.
The result is rounded to 2 decimal places.
:param meters: A float representing a measurement in meters.
:return: A float represe... |
def B3V_eq(x):
"""
:param x: abcsisse du point de la ligne B3V dont on veut obtenir l'ordonnee
:return: ordonnee du point de la ligne B3V correspondant a l'abscisse x (dans un graphique u-g vs g-r)
"""
return 0.9909 * x - 0.8901 |
def get_locale_parts(locale):
"""Split a locale into three parts, for langauge, script, and region."""
parts = locale.split('_')
if len(parts) == 1:
return (parts[0], None, None)
elif len(parts) == 2:
if len(parts[1]) == 4: # parts[1] is a script
return (parts[0], parts[1], ... |
def Re_reflux(w_liq_real_enter_reflux, rho_reflux, d_enter_reflux_real, mu_reflux):
"""
Calculates the Re criterion .
Parameters
----------
w_liq_real_enter_reflux : float
The real speed of liquid at the tube, [m/s]
rho_reflux : float
The density of reflux, [kg/m**3]
d_enter_... |
def list_product(combination):
"""
Calculates the product of all elements from the list.
Remark: deprecated, use geometric mean instead.
"""
score = 1
for tanimoto in combination:
score = score * tanimoto
return(score) |
def get_or_none(l, n):
"""Get value or return 'None'"""
try:
return l[n]
except (TypeError, IndexError):
return 'None' |
def count_matches(array1, array2, admissible_proximity=40):
"""Finds the matches between two count process.
Returns
-------
tuple of lists
(M, U, M) where M is the list of indices of array2 where
matched with array 1 happened and U contains a list of
indices of array2 where no m... |
def make_damage_list(find_list, damage):
"""make damage list
from result, make damage date to list
Args
find_list (list): score data, as raw data
Returns
ret (boolean): damage found or not found
"""
ret = False
temp_list = []
list_num = len(find_list)
# from res... |
def _allowed_char(char: str) -> bool:
"""Return true if the character is part of a valid policy ID."""
return char.isalnum() or char in {' ', '-', '.'} |
def compute_iou(box_1, box_2):
"""
This function takes a pair of bounding boxes and returns intersection-over-
union (IoU) of two bounding boxes.
"""
tl_row_1, tl_col_1, br_row_1, br_col_1 = box_1
tl_row_2, tl_col_2, br_row_2, br_col_2 = box_2
assert tl_row_1 < br_row_1
assert tl_col_1 ... |
def links_as_text(code):
""" ersetzt alle Vorkommen von '<a href="xxxxxxxx" ... >yyyy</a>' durch '(xxxxxxxx : yyyy)' """
def link_as_text(code):
ret = code
i = code.rfind('<a href="')
if i>-1:
j = code.find('"', i+9)
k = code.find('>', j)
l = code.find('<', k)
ret = code[:i] + '... |
def s2t(x):
"""
Convert 'sigmoid' encoding (aka range [0, 1]) to 'tanh' encoding
"""
return x * 2 - 1 |
def get_predictions_without_annotations_query(label: str):
"""
Expects a label. Returns query dict for images with predictions but not annotations for this label.
Additionally filters images out if they are already marked as "in_progress".
!!! Only works for binary classification !!!
"""
return ... |
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string.
Arguments:
typed: an entered string
elapsed: an amount of time in seconds
>>> wpm('hello friend hello buddy hello', 15)
24.0
>>> wpm('0123456789',60)
2.0
"""
assert elapsed > 0, 'Elapsed ... |
def _clean_up_git_link(git_link: str) -> str:
"""Clean up git link, delete .git extension, make https url."""
if "@" in git_link:
git_link.replace(":", "/").replace("git@", "https://")
if git_link.endswith(".git"):
git_link = git_link[:-4]
return git_link |
def exclude_bracket(enabled, filter_type, language_list, language):
"""
Exclude or include brackets based on filter lists.
"""
exclude = True
if enabled:
# Black list languages
if filter_type == 'blacklist':
exclude = False
if language != None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.