content stringlengths 42 6.51k |
|---|
def turn_right(block_matrix, debug=False):
"""block turn right."""
new_block = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for i in range(4):
for j in range(4):
new_block[3-j][i] = block_matrix[i][j]
if debug:
print(new_block)
return new_block |
def scott(n: int, ess: float):
"""
Returns Scott's factor for KDE approximation.
Args:
n: See ``silverman``.
ess: See ``silverman``.
"""
return 1.059 * ess ** (-1 / (n + 4)) |
def format_license(license: str) -> str:
"""
Format license using a short name
"""
MAX = 21
if len(license) > MAX:
license = license[:MAX-3] + '...'
return license |
def dummy_flow(positional_str, positional_bool, positional_int,
positional_float, optional_str='default', optional_bool=False,
optional_int=0, optional_float=1.0, optional_float_2=2.0):
""" Workflow used to test the introspective argument parser.
Parameters
----------
posi... |
def ordered_dict_to_pref(obj, member, val):
""" Function to convert an OrderedDict to something that can
be easily stored and read back, in this case a list of tuples.
Parameters
----------
obj: Atom
The instance calling the function
member: Member
The member that must be store... |
def _get_ratio(user_a, user_b):
"""Get ratio."""
user_b = 1 if int(user_b) == 0 else user_b
user_a = 1 if int(user_b) == 0 else user_a
return user_a/user_b |
def extractSentencePairs(conversations):
"""
Extract the sample lines from the conversations
"""
qa_pairs = []
for conversation in conversations:
# Iterate over all the lines of the conversation
for i in range(len(conversation["lines"]) - 1): # We ignore the last line (no answer f... |
def str2bin(s):
"""
String to binary.
"""
ret = []
for c in s:
ret.append(bin(ord(c))[2:].zfill(8))
return ''.join(ret) |
def slider_command_to_str(arguments):
"""
Convert arguments for slider and arrowbox command into comment string
for config file.
:param arguments: slider arguments
:return: Formatted string for config file.
"""
return '; '.join(arguments) |
def length_vector_sqrd_numba(a):
""" Calculate the squared length of the vector.
Parameters
----------
a : array
XYZ components of the vector.
Returns
-------
float: The squared length of the XYZ components.
"""
return a[0]**2 + a[1]**2 + a[2]**2 |
def colorinterval(x, y, z):
"""
test for y < x < z with tupples
:param x:
:param y:
:param z:
:return:
"""
a = y[0] <= x[0] <= z[0]
b = y[1] <= x[1] <= z[1]
c = y[1] <= x[1] <= z[1]
return a and b and c |
def get_prefix(headword, length):
"""
Return the prefix for the given headword,
of length length.
:param headword: the headword string
:type headword: unicode
:param length: prefix length
:type length: int
:rtype: unicode
"""
if headword is None:
return None
lowerc... |
def bmin(L,M,s=0.20):
"""
Return minimum number of precincts that could be "bad".
L = list of n precincts: n (size,name) pairs
M = margin of victory as number of votes separating winner
from runner-up
s = maximum within-precinct miscount
"""
assert 0 <= M <= sum(... |
def vmul(vect, s):
"""
This function returns the vector result of multiplying each entries of a vector by a scalar. Works also for flat matrices
:param vect: the vector to be multiplied with the scalar value
:param s: the scalar value
:type vect: double or integer iterable
:type s: d... |
def print_clean(item):
"""
Helper function for print_board
Returns "." if the element is a list
"""
if len(item) == 1:
print(item[0]),
else:
print("."),
return 0 |
def salutation(hour: int) -> str:
"""Determine the correct salutation using the hour parameter."""
greetings = ((range(0, 12), "Good Morning",),
(range(12, 17), "Good Afternoon"),
(range(17, 24), "Good Evening"),)
return list(filter(lambda x: hour in x[0], greetings))[0][1] |
def docs_with_low_token_count(corpus_statistics, max_token_count=350):
"""
"""
# Gather list of doc_ids and total token count
docs_2_tokens = {}
for report in corpus_statistics:
docs_2_tokens.update({report['doc_id']: report['num_tokens']})
# Subset dictionary to get only records wth va... |
def _splice_comma_names(namelist):
""" Given a list of names, some of the names can be comma-separated lists.
Return a new list of single names (names in comma-separated lists are
spliced into the list).
"""
newlist = []
for name in namelist:
if ',' in name:
newlist.e... |
def is_mci(code):
"""
ICD9
331.83 Mild cognitive impairment, so stated
294.9 Unspecified persistent mental disorders due to conditions classified elsewhere
ICD10
G31.84 Mild cognitive impairment, so stated
F09 Unspecified mental disorder due to known ... |
def extractrelation(s, level=0):
""" Extract discourse relation on different level
"""
items = s.lower().split('-')
if items[0] == 'same':
rela = '_'.join(items[:2])
else:
rela = items[0]
return rela |
def vector_average(vv):
"""Calculate average from iterable of vectors."""
c = None
for i, v in enumerate(vv):
c = v if c is None else tuple((i*a+b)/(i+1) for (a, b) in zip(c, v))
return c |
def safer_getattr(object, name, default=None, getattr=getattr):
"""Getattr implementation which prevents using format on string objects.
format() is considered harmful:
http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/
"""
if isinstance(object, str) and name == 'format':
raise No... |
def prl_utils(device_type='kinect', camera_name='', quality=()):
"""Returns default rgb and depth topics for the kinect sensors
Keyword Arguments:
device_type {str} -- device type, one of 'kinect', 'kinect2', 'realsense' (default: {'kinect'})
camera_name {str} -- camera unique identifier (defau... |
def undistill_link(Ftarget, Finitial):
"""
Obtains the fidelity of a link when reversing distillation of the target link assuming Werner states
:param Ftarget: type float
Fidelity of the distilled link
:param Finitial: type float
Fidelity of the second link used to produce the distilled ... |
def get_unique_open_finding_hr(unique_open_finding):
"""
Prepare open findings dictionary for human readable data.
This method is used in 'risksense-get-unique-open-findings' command.
:param unique_open_finding: Dictionary representing open host findings.
:return: None.
"""
return {
... |
def format_plaintext_email(message):
"""Replace \n by <br> to display as HTML"""
return message.replace('\n', '<br>') |
def from_two_bytes(bytes):
"""
Return an integer from two 7 bit bytes.
>>> for i in range(32766, 32768):
... val = to_two_bytes(i)
... ret = from_two_bytes(val)
... assert ret == i
...
>>> from_two_bytes(('\\xff', '\\xff'))
32767
>>> from_two_bytes(('\\x7f', '\\xff')... |
def index(tup, ind):
"""Fancy indexing with tuples."""
return tuple(tup[i] for i in ind) |
def average_t(ave, number, new):
"""
Add up all the temperature and count average.
:param ave: Integer, The average of all temperature before last input
:param number: Integer, number>0. The total amount of temperature
:param new: Integer, new!=EXIT, The lasted temperature input
:return: ave: Integer, The curren... |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"user": string,
"... |
def _secs_to_ms(value):
"""Converts a seconds value in float to the number of ms as an integer."""
return int(round(value * 1000.)) |
def check_timestamp_event_type(event_list):
"""For the given event_list, determine whether physical
or spell offensive actions take place"""
for line in event_list:
if 'You perform' in line \
or 'You attack ' in line \
or 'You shot' in line \
or 'You miss' in line \
... |
def power(x: int, y: int) -> int:
"""Returns x to the power of non-negative integer y."""
assert not y < 0, "Non-negative integer y only."
if y == 0:
return 1
return x * power(x, y - 1) |
def _strip_comments_from_pex_json_lockfile(lockfile_bytes: bytes) -> bytes:
"""Pex does not like the header Pants adds to lockfiles, as it violates JSON.
Note that we only strip lines starting with `//`, which is all that Pants will ever add. If
users add their own comments, things will fail.
"""
r... |
def vec_sub (x, y):
"""[Lab 14] Returns x - y"""
return [x_i - y_i for (x_i, y_i) in zip (x, y)] |
def _nb_models_and_deficit(nb_targets, potential_targets):
""" Calculates the number of models to learn based on the number of targets and the potential targets
Args:
nb_targets: number of targets
potential_targets: attributes that can be used as targets
Returns:
nb_models: number ... |
def flatten(S):
""" Flattens a list of lists, but leaves tuples intact"""
flatlist = [val for sublist in S for val in sublist]
return flatlist |
def longest_palindrom_ver1(strs: str) -> str:
"""Dynamic programing"""
if len(strs) < 2 or strs == strs[::-1]:
return strs
palins = []
for num in range(1, len(strs)):
for i in range(len(strs) - num):
if strs[i:i + num + 1][::-1] == strs[i:i + num + 1]:
palins... |
def sample(i):
"""
Helper method to generate a meaningful sample value.
"""
return 'sample{}'.format(i) |
def get_tile_url(xtile, ytile, zoom):
"""
Return a URL for a tile given some OSM tile co-ordinates
"""
return "http://tile.openstreetmap.org/%d/%d/%d.png" % (zoom, xtile, ytile) |
def shock_standoff(R_n, rho_inf, rho_s):
"""
Approximates supersonic shock stand-off distance for the stagnation
point of an obstacle with equivalent radius R_n
Input variables:
R_n : Obstacle radius
rho_inf : Freestream density
rho_s : Density at point immediately behind shock
... |
def cell_volume(a1,a2,a3):
"""
returns the volume of the primitive cell: |a1.(a2xa3)|
"""
a_mid_0 = a2[1]*a3[2] - a2[2]*a3[1]
a_mid_1 = a2[2]*a3[0] - a2[0]*a3[2]
a_mid_2 = a2[0]*a3[1] - a2[1]*a3[0]
return abs(float(a1[0]*a_mid_0 + a1[1]*a_mid_1 + a1[2]*a_mid_2)) |
def dealign(text):
"""
Original text is limited to 72 characters per line, paragraphs separated
by a blank line. This function merges every paragraph to one line.
Args:
text (str): Text with limited line size.
Returns:
str: Text with every paragraph on a single line.
""... |
def area_square(r):
"""Return the area of a square with side length R."""
assert r > 0, 'A length must be positive'
return r * r |
def extract_teams(picks_bans, radiant_win):
"""
Unest teams field from STEAM API
"""
teams = {
'winners': [],
'loosers': []
}
for pick_ban in picks_bans:
if pick_ban['is_pick']:
# radiant team id is 0
is_win = (pick_ban['team'] != radiant_win)
... |
def findLength(lst):
"""Given a list of bytestrings and NamedInts, return the total
length of all items in the list.
"""
return sum(len(item) for item in lst) |
def get_metadata(data):
"""Converts metadata from CVAT format.
Args:
data (OrderedDict): CVAT annotation
Returns:
dict: Annotation metadata
"""
metadata = {}
metadata['source_name'] = data['source']
metadata['frames_size'] = data['task']['size']
metadata['start_frame']... |
def maf_binary(sorted_array, value):
"""
In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed.
"""
err = "Not Found"
min = 0
... |
def _build_time_predicates(
from_date=None,
to_date=None,
):
"""
Build time range predicates
"""
must = []
if from_date:
must.append("start={}".format(from_date))
if to_date:
must.append("end={}".format(to_date))
return "&".join(must) |
def delete_part(sentence, delete_part, mainword, **kwargs): #Done with testing
"""Delete all words in the sentence coming either <delete_part>='before'
or <delete_part>='after'"""
if mainword not in sentence:
return False, sentence
senthalved = sentence.split(mainword)
if delete_part == 'aft... |
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
return sum(hand.values()) |
def Sub(matA, matB):
"""
Sub(matrix1, matix2):
Subtracts both matices and returns -1 if order of both matrices different or else returns resultant matrix
"""
A=len(matA)
B=len(matB)
#checks number of columns equal of not for both matices, same as previous
if A!=B:
return -1
C... |
def tag_only(tag):
"""
simple function to remove the elements token from a tag name
e.g. tag_only('tag_name{10}') -> 'tag_name'
"""
if '{' in tag:
return tag[:tag.find('{')]
else:
return tag |
def bin_to_int(bin_str: str, signed: bool = True) -> str:
"""Converts binary string to int string
Parameters
----------
bin_str : str
binary string to convert
signed : bool, optional
if the binary string should be interpreted as signed or not, default True
Returns
-------
... |
def rb_is_true(value: str) -> bool:
"""String to bool conversion function for use with args.get(...).
"""
return value.lower() == "true" |
def default_opinions(codel_size=1, noncoding='block', sliding='halting', color_dir_h='-', color_dir_l='-'):
"""Constructs an opinions dictionary for a repiet compiler pass
(implicity filling in defaults)"""
return dict(codel_size=codel_size,
noncoding=noncoding,
sliding=slidi... |
def formatColoria(a):
"""int array to #rrggbb"""
return '#%02x%02x%02x' % (a[0],a[1],a[2]) |
def recursive_fibonacci_cache(
n: int
) -> int:
"""
Returns n-th Fibonacci number
n must be more than 0, otherwise it raises a ValueError.
>>> recursive_fibonacci_cache(0)
0
>>> recursive_fibonacci_cache(1)
1
>>> recursive_fibonacci_cache(2)
1
>>> recursive_fibonacci_cach... |
def get_min_sec_stocks(nr_of_stocks, sectors):
"""
Returns the Number of minimum stocks per sector requiered to get to the nr_of_stocks with the selected sectors
Args:
nr_of_stocks (ind): Readout of the 'nr_of_stocks' input in the interface.
sectors (list): List that is returned from the 's... |
def is_valid(name):
"""Return whether name is valid for Pygame Zero.
name can contain lowercase letters, numbers and underscores only.
They also have to start with a letter.
Args:
name: String name to test.
Returns:
True if name is valid for Pygame Zero. False otherwise.
"""
... |
def isSpace(s):
"""
isSpace :: str -> bool
Returns True for any Unicode space character, and the control characters
\t, \n, \r, \f, \v.
"""
return s in " \t\n\r\f\v" |
def index_structure(structure, path, path_separator="/"):
"""Follows :obj:`path` in a nested structure of objects, lists, and dicts."""
keys = path.split(path_separator)
for i, key in enumerate(keys):
current_path = "%s%s" % (path_separator, path_separator.join(keys[:i]))
if isinstance(structure, list):
... |
def get_metrics_names(metrics):
"""Gets the names of the metrics.
Args:
metrics: Dict keyed by client id. Each element is a dict of metrics
for that client in the specified round. The dicts for all clients
are expected to have the same set of keys."""
if len(metrics) == 0:
... |
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '='* (4 - missing_padding)
return data |
def _expand_check_paths(template, lookup_key):
"""Generate paths to examine from a variable-type template.
`template` may be one of three data structures:
- str: search for files matching this exact template
- list of str: search for files matching each template listed.
- dict: use `lo... |
def resultlist_reader(response, all_unicode=False):
""" Returns a list
"""
links = []
def get_self(links):
for link in links:
if link['rel'] == "self":
return link['uri']
for result in response:
links.append(get_self(result['links']))
retu... |
def pageurl_template(category, pagenum, date):
"""
Function to return formatted URL given category, page number, date
"""
assert len(str(date)) == 8, 'Invalid input date format'
return f"https://news.daum.net/breakingnews/{category}?page={pagenum}®Date={date}" |
def _times_2(number: int) -> int:
"""
If number * 2 is greater than 9, return 1
otherwise return the number * 2
:param number:
:return:
"""
return int(list(str(number * 2))[0]) |
def cyan(x):
"""Format a string in cyan.
Returns:
The string `x` made cyan by terminal escape sequence.
"""
return f"\033[36m{x}\033[0m" |
def validate_rng_seed(seed, min_length):
"""
Validates random hexadecimal seed
returns => <boolean>
seed: <string> hex string to be validated
min_length: <int> number of characters required. > 0
"""
if len(seed) < min_length:
print("Error: Computer entropy must be at least {0} cha... |
def _attributes_from_line(line):
"""Parse an attribute line.
Arguments:
line -- a single line from the tlpdb
Returns:
A dictionary of attributes
Example input lines:
arch=x86_64-darwin size=1
details="Package introduction" language="de"
RELOC/doc/platex/pxbase/README ... |
def normalizeAnswer (answer, yes=None, missing=None):
"""Special-case hackery, perhaps eventually more parameterized ..."""
if answer in (None, ""):
answer = missing
# Special-case hackery ...
elif answer.lower() == yes:
answer = "yes"
else:
answer = "no"
return answer |
def tot(sequence, total=0):
"""Helper method: returns total of string sequence."""
total = counter = 0
temp = ''
plus_minus = 1 # variable for managing + and -
while counter < len(sequence):
try:
int(sequence[counter])
temp += sequence[counter]
except Val... |
def get_bert_dataset_name(is_cased):
"""Returns relevant BERT dataset name, depending on whether we are using a cased model.
Parameters
----------
is_cased: bool
Whether we are using a cased model.
Returns
-------
str: Named of the BERT dataset.
"""
if is_cased:
re... |
def save_list(input_list, file_name):
"""A list (input_list) is saved in a file (file_name)"""
with open(file_name, 'w') as fh:
for item in input_list:
fh.write('{0}\n'.format(item))
return None |
def get_target_start_date_col(forecast_id):
"""Returns the name of the target start date col for dataframes
associated with the given forecast identifier
Args:
forecast_id: string identifying forecast (see get_forecast)
"""
if forecast_id.startswith("nmme"):
return "target_start"
... |
def which(program):
"""The Unix which command in Python."""
import os
def is_exe(fpath):
"""Check if file is executable."""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, _ = os.path.split(program)
if fpath:
if is_exe(program):
return program
... |
def isnumber(s):
""" Is number or not
"""
try:
val = int(s)
return True
except ValueError:
return False |
def no_filter(f_0, F, X_target, y_target, metric=None, vote_func=None):
"""Apply no filter to the data, just merge F and F_0 and return
Args:
f_0: baseline learner
F: set of possible learners
X_target: target training instances
y_target: target training labels
metric: unuse params... |
def _get_time_axis(time_list, units='hours'):
"""Convert time to sequential format and convert time units."""
time_axis = []
for i in range(len(time_list)):
time_sum = sum(time_list[:i])
if units == 'seconds':
pass
elif units == 'minutes':
time_sum /= 60.0
... |
def mean(iterable):
"""
Compute the mean value of the entries in {iterable}
"""
# make an iterator over the iterable
i = iter(iterable)
# initialize the counters
count = 1
total = next(i)
# loop
for item in i:
# update the counters
count += 1
total += item... |
def locate(x1, y1, x2, y2, x3):
"""An equation solver to solve: given two points on a line and x, solve the
y coordinate on the same line.
Suppose p1 = (x1, y1), p2 = (x2, y2), p3 = (x3, y3) on the same line.
given x1, y1, x2, y2, x3, find y3::
y3 = y1 - (y1 - y2) * (x1 - x3) / (x1 - x3)
"... |
def guess_number(f_guess, f_turns_left):
"""Obtain player guess
Params:
f_guess: int
f_turns_left: int
Returns:
int, str
"""
try:
if f_guess < 1 or f_guess > 9:
raise ValueError
return f_guess, f_turns_left - 1
except ValueError:
retu... |
def zipmap(keys, vals):
"""Return a map from keys to values"""
return dict(zip(keys, vals)) |
def calculate(puzzle_input):
"""Tracks Santa's steps"""
x = y = rx = ry = 0
visited = set()
robot = False
for step in puzzle_input:
if step == "^":
if robot:
ry += 1
else:
y += 1
elif step == "v":
if robot:
... |
def del_empty_space(list):
"""deletes empty elements with "space" in it"""
for x in range(len(list)):
if " " in list[x - 1]:
del list[x - 1]
return list |
def is_stressful(subj):
"""
recoognise stressful subject
"""
import re
return (subj.isupper() or subj.endswith('!!!') or
any(re.search('+[.!-]*'.join(word), subj.lower())
for word in ['help', 'asap', 'urgent']
# 'h+[.!-]*e+[.!-]*l+[.!-]*p'
... |
def get_drop_indices(num_chunks, keep_indices):
"""obtain the drop_indices given the keep_indices.
Args:
num_chunks (int): The total number of chunks
keep_indices (List): The keep indices.
Returns: List. The dropped indices (frozen chunks).
"""
drop_indices = []
for i in range... |
def calculate_kill_death_assists_ratio(kills, deaths, assists):
"""
kda = kills + (assists / 2) / deaths
Ensure the MLG's have some deaths.
"""
numerator = kills + (assists / 2)
if deaths > 0:
kda = numerator / deaths
else:
kda = numerator
return round(kda, 2) |
def get_log(name=None):
"""Return a console logger.
Output may be sent to the logger using the `debug`, `info`, `warning`,
`error` and `critical` methods.
Parameters
----------
name : str
Name of the log.
References
----------
.. [1] Logging facility for Pytho... |
def unit_conversion(current_values, unit_type, current_unit, new_unit):
"""
Converts given values between the specified units
:param current_values: the current values that you want converted between units. It can be any type, so long as
arithmetic operations with scalars behave appropriately. A numpy a... |
def _get_pattern_list(testdata, global_obj, pattern="start"):
"""
Get the pattern attribute from either the current testdata block
or from the global section
"""
global_var_pattern = global_obj.find("variable_pattern") if global_obj is \
not None else None
if pattern == "start":... |
def region_append_without_whitespace(book, rclass, start, end, *extra):
"""
Shrink the region (start, end) until there is no whitespace either end of
the region. Then if it is non-zero, append the region to (rclass)
Return true iff a region is added.
"""
if start is None:
return
if... |
def distinct(lst1, lst2):
"""
Argument order: source following list, accumulated source's following list
"""
following = lst1
second_layer_following = lst2
unique = set(following)
final = [x for x in second_layer_following if x not in unique]
return final |
def get_columns(filters):
"""return columns based on filters"""
columns = [
{
"fieldname":"item",
"fieldtype":"Link",
"label":"Item",
"options":"Item",
"width":250
},
{
"fieldname":"open_qty",
"fieldtype":"Float",
"labe... |
def solution(a: int, b: int, k: int) -> int:
"""
:return: The number of integers within the range [a..b]
that are divisible by k.
>>> solution(6, 11, 2)
3
>>> solution(3, 14, 7)
2
"""
count = (b - a + 1) // k
if b % k == 0:
count += 1
return count |
def allZero(buffer):
"""
Tries to determine if a buffer is empty.
@type buffer: str
@param buffer: Buffer to test if it is empty.
@rtype: bool
@return: C{True} if the given buffer is empty, i.e. full of zeros,
C{False} if it doesn't.
"""
allZero = True
for byte ... |
def pick_one(l: list):
"""Pick one of the items from the list."""
# special case for picking only one item
if len(l) == 1:
return l[0]
for i, item in enumerate(l):
print(f"{i + 1}) {item}")
while True:
try:
val = input("Pick one (leave blank for 1): ")
... |
def del_comment(string):
"""Delete the comment from the parameter setting string.
Parameters
----------
string : str, default None
The parameter setting string probably with the comment.
Returns
-------
string : str
The parameter setting string without the commen... |
def stringify(num):
"""
Takes a number and returns a string putting a zero in front if it's
single digit.
"""
num_string = str(num)
if len(num_string) == 1:
num_string = '0' + num_string
return num_string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.