content stringlengths 42 6.51k |
|---|
def coups_legaux(grille):
"""Renvoie la liste des colonnes dans lesquelles il est possible de
jouer un jeton
"""
coups = []
for i in range(0, 6):
if grille[i][0] == 0:
coups += [str(i + 1)]
return coups |
def mag(mag_star, mag_ref=0):
"""Calculates the brightness difference based on magnitudes
Parameters
----------
mag_star : float
Magnitude of input star
mag_ref : float
magnitude of reference star"""
return 10**(0.4*((mag_ref)-(mag_star))) |
def compute_markdown_rendering(rendertype, text):
"""Generate special markdown rendering."""
rendered = ""
if text:
if rendertype == 1:
for key, value in text.items():
rendered += "* " + key + " ### " + value + "\n"
elif rendertype == 2:
for i in text:... |
def get_file_name(file):
"""
As explained in clone_online_repo method test_dataset_* file name must be branch's name
"""
return file.split("/")[-1].split(".")[0] |
def compareDicts(dict1, dict2):
""" Compare two dictionaries, returning sets containing keys from
dict1 difference dict2, dict2 difference dict1, and shared keys with
non-equivalent values, respectively.
Parameters
----------
dict1 : dict
dict2 : dict
Returns
-------
set, set, ... |
def trans_shape(trans_index, tensor_shape):
"""trans_shape"""
s = list(tensor_shape)
s[trans_index[0]], s[trans_index[1]] = s[trans_index[1]], s[trans_index[0]]
return tuple(s) |
def day_to_num(day):
"""
Converts day of week to numerical value.
"""
converter = {
'mon' : 0,
'tue' : 1,
'wed' : 2,
'thu' : 3,
'fri' : 4,
'sat' : 5,
'sun' : 6
}
return converter[day] |
def is_valid_ip(ip: str) -> bool:
"""Checks if ip address is valid
Examples:
>>> assert is_valid_ip('12.255.56.1')
>>> assert not is_valid_ip('1.1.1')
"""
octets = ip.split(".")
if not octets or len(octets) != 4:
return False
return all(map(lambda octet: octet in map(str... |
def getKeyPath(parent, keyPath):
"""
Allows the getting of arbitrary nested dictionary keys via a single
dot-separated string. For example, getKeyPath(parent, "foo.bar.baz")
would fetch parent["foo"]["bar"]["baz"]. If any of the keys don't
exist, None is returned instead.
@param parent: the o... |
def is_create(line):
"""
Returns true if the line begins a SQL insert statement.
"""
return line.startswith('CREATE TABLE') or False |
def _in_target(h, key):
"""
This function checks whether the target exist and key present in target config.
:param h: target config.
:param key: attribute name.
:return: True/False.
"""
return True if h and key in h else False |
def factorial(n):
"""
This function returns the factorial of n.
factorial(5) => 120
"""
#base case
if n == 0:
return 1
#recursive case
else:
fact = n * factorial(n-1)
return fact |
def leja_growth_rule(level):
"""
The number of samples in the 1D Leja quadrature rule of a given
level. Most leja rules produce two point quadrature rules which
have zero weight assigned to one point. Avoid this by skipping from
one point rule to 3 point rule and then increment by 1.
Parameter... |
def get_test_config(config, test):
"""Get a single test module's config"""
return config["modules"].get(test) |
def is_prime(n):
"""Determine if input number is prime number
Args:
n(int): input number
Return:
true or false(bool):
"""
for curr_num in range(2, n):
# if input is evenly divisible by the current number
if n % curr_num == 0:
# print("current num:", curr_n... |
def show_bit_mask(bit_mask):
"""
"""
return '{:012b}'.format(bit_mask) |
def html_close(tag):
"""</tag>"""
return "</{}>".format(tag) |
def decode_txpower(t):
""" convert the data in info['txpower'] which is, for example, '15.00 dBm' into 15.0
@return: the value of the tx power
@rtype: float
"""
r = float(t.split()[0].strip())
return r |
def userstatus(data):
"""
Returns a dictionary id : status with info
about latest status of every user in data.
status - dict
"""
return {u['id']: u["status"] for u in data['users']} |
def extract_groups_cores(grouped_jobs, max_cores=None):
"""Processes the list of task names to group, extracting the max number of
cores per task. The grouped task name can have the format:
task_name:num_cores or just task_name. If num_cores is set, the max_cores
is used instead.
Args:
- grouped... |
def leniter(iterator):
"""leniter(iterator): return the length of an iterator, consuming it."""
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements |
def word_fits_in_line(pagewidth, x_pos, wordsize_w):
""" Return True if a word can fit into a line. """
return (pagewidth - x_pos - wordsize_w) > 0 |
def safe2f(x):
"""converts to float if possible, otherwise is a string"""
try:
return float(x)
except:
return x |
def get_resource_and_action(action):
""" Extract resource and action (write, read) from api operation """
data = action.split(':', 1)[0].split('_', 1)
return ("%ss" % data[-1], data[0] != 'get') |
def get_acceleration_of_gravity(_):
"""
Get the acceleration of gravity for a carla vehicle
(for the moment constant at 9.81 m/s^2)
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: acceleration of gravity [m/s^2]
:rtype: float64
"""... |
def make_list(obj):
""" Turn an object into a list if it isn't already """
if isinstance(obj, list):
return obj
else:
return list(obj) |
def ValueErrorOnNull(result, error):
"""Raises ValueError(error) if result is None, otherwise returns result."""
if result is None:
raise ValueError(error)
return result |
def sin_recursive(x, N=100):
"""Calculate sin(x) for N iterations.
Arguments
---------
x : float
argument of sin(x)
N : int
number of iterations
Returns
-------
func_value
"""
# special case 0
if x == 0:
return 0.0
sumN = an = x # n=1
for n... |
def find_prime(x):
"""
Usage: Find largest prime numbers within a list of integer.
Argument:
x : a list of integer.
Return:
an integer
Examples:
find_prime([0,1,2,3,4,5])
>>>5
find_prime([0,1])
>>> "No prime number in list"
... |
def numstr(number, decimalpoints: int) -> str:
""" Print big numbers nicely.
Add commas, and restrict decimal places
Parameters
----------
number : numeric
decimalpoints : int
Number of decimal points to which the output string is restricted
Returns
-------
str
nice... |
def remap(value, from_min_value, from_max_value, to_min_value, to_max_value):
"""Remap value from from_min_value:from_max_value range to to_min_value:to_max_value range"""
# Check reversed input range
reverse_input = False
from_min = min(from_min_value, from_max_value)
from_max = max(from_min_value,... |
def get_remote_host(dns_prefix, location):
"""
Provides a remote host according to the passed dns_prefix and location.
"""
return '{}.{}.cloudapp.azure.com'.format(dns_prefix, location) |
def build_response(session_attributes, speechlet_response):
"""
Build the full response JSON from the speechlet response
"""
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} |
def _value(ch, charset):
"""Decodes an individual digit of a base62 encoded string."""
try:
return charset.index(ch)
except ValueError:
raise ValueError('base62: Invalid character (%s)' % ch) |
def getMatchingLFN(_lfn, lfns):
""" Return the proper LFN knowing only the preliminary LFN """
# Note: the preliminary LFN may contain substrings added to the actual LFN
actual_lfn = ""
for lfn in lfns:
if lfn in _lfn:
actual_lfn = lfn
break
return actual_lfn |
def derivative(func, x, h):
"""
Evaluate the derivative of a function
at point x, with step size h
Uses the symmetric derivative
Parameters
----------
func : function
Function to evaluate
x : float
Point to evaluate derivative
h : float
Step size
Retur... |
def zigzag(seq):
""" returns odd values, even values """
return seq[::2], seq[1::2] |
def lines_cross(begin1, end1, begin2, end2, inclusive=False):
""" Returns true if the line segments intersect """
A1 = end1[1] - begin1[1]
B1 = -end1[0] + begin1[0]
C1 = - (begin1[1] * B1 + begin1[0] * A1)
A2 = end2[1] - begin2[1]
B2 = -end2[0] + begin2[0]
C2 = - (begin2[1] * B2 + begin2[0] ... |
def fibonacci(n):
"""
This is the original function, it will be used to compare execution times.
"""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2) |
def knight(x,y):
"""Knight distance heuristic."""
return max((x//2+x%2),(y//2+y%2)) |
def isIONO(filename):
"""
Checks whether a file is IM806 format.
"""
try:
temp = open(filename, 'rt').readline()
except:
return False
try:
if not temp.startswith('Messdaten IM806'):
if not temp.startswith('Date;Time;NegMin;'):
return False
... |
def port_bound(port):
"""Returns true if the port is bound."""
return port['binding:vif_type'] != 'unbound' |
def Generate_windows_and_count_tags(taglist, chrom, chrom_length, window_size, file):
"""
taglist: sorted list of positions that includes every tag on a chromosome
window_size: the artificial bin size for binning the tags
bed_vals: a dictionary keyed by the start of tag_containing
windows, with ... |
def digital_sum(n):
"""returns the sum of the digits of an integer"""
assert isinstance(n, int), "Digital sum is defined for integers only."
return sum([int(digit) for digit in str(n)]) |
def mixing_dict(xy, normalized=False):
"""Returns a dictionary representation of mixing matrix.
Parameters
----------
xy : list or container of two-tuples
Pairs of (x,y) items.
attribute : string
Node attribute key
normalized : bool (default=False)
Return counts if False ... |
def sizeToTeam(size):
"""Given a size in kilobytes, returns the 512kb.club team (green/orange/blue),
or "N/A" if size is too big for 512kb.club"""
if size<100:
return "green"
elif size<250:
return "orange"
elif size<=512:
return "blue"
else:
return "N/A" |
def count_data(data, code = None):
"""Helper function that counts the number of data points in an arbitrary list of lists"""
if isinstance(data,list):
sum = 0
for d in data:
sum += count_data(d, code=code)
return sum
if data != '' and data != 'NA':
if code == None or data == code:
return 1
return 0 |
def greaterD( ef, gh):
"""
Return True if pair ef has greater margin than pair gh.
A pair is a pair of the form: (pref[e,f],pref[f,e])
Schulze says (page 154):
"(N[e,f],N[f,e]) >_win (N[g,h],N[h,g])
if and only if at least one of the following conditions is satisfied:
1. N[e,f] > N[f,e] ... |
def sort_databases(dbs: list, chids: tuple) -> tuple:
"""Ensures that the databases match the cubes."""
if len(dbs) != len(chids):
raise IndexError(
f"The number of databases {len(dbs)} does not "
"match the number of Product IDs {chids}"
)
chid_db_map = dict()
... |
def find_new(vglist1,vglist2,key):
"""
Return list of elements of vglist2 that are not in vglist1.
Uses specified key to determine new elements of list.
"""
# Get all the values for the specified key
values = []
for row in vglist1:
values.append(row[key])
# Check through the new list for new valu... |
def make_car(
manufacturer, model_name, **car_info):
"""Build a dictionary containing everything we know about a car."""
car = {}
car['manufacturer'] = manufacturer
car['model'] = model_name
for key, value in car_info.items():
car[key] = value
return car |
def page_not_found(e):
"""
Handler for page not found 404
"""
# pylint: disable=no-member
# pylint: disable=unused-argument
# pylint: disable=undefined-variable
return "Flask 404 here, but not the page you requested." |
def user_login(r):
"""
Because dict nesting, this is a special function to return the user_login out of a dict
"""
if "user" in r:
if "login" in r["user"]:
return r["user"]["login"]
return None |
def clean_description(incoming: str) -> str:
"""Format behavior description strings for output."""
description = []
for desc in incoming.split("\n"):
part = ""
for piece in desc.split():
delim = ""
if len(part) > 60:
description.append(part)
... |
def slim_aggregates(aggregates):
""""slim version of the region aggregates, minimizing NoData and verbose naming"""
slimmed_aggregates = []
for aggregate in aggregates:
verbose_keys = list(aggregate.keys())
for verbose_key in verbose_keys:
slim_key = verbose_key.split("_")[0]
... |
def get_nth_digit(N, n):
"""
return the nth digit from an N digit number
>>> get_nth_digit(12345, 3)
4
>>> get_nth_digit(12345, 7)
Traceback (most recent call last):
...
IndexError: string index out of range
"""
return int(str(N)[n]) |
def caminho_asset(nome: str, png_min: bool = False) -> str:
"""Retorna o caminho para o asset da peca com o identificador passado"""
return f'assets/{nome}.png' + ('.min' if png_min else '') |
def uppercase_underscore(a_string):
"""
Internally some strings that are Title Cased With Spaces should be
UPPER_CASED_WITH_UNDERSCORES.
"""
a_string = a_string.replace(' ','_')
return a_string.upper() |
def query_newer_than(timestamp):
"""
Return a query string for later than "timestamp"
:param timestamp: CloudGenix timestamp
:return: Dictionary of the query
"""
return {
"query_params": {
"_updated_on_utc": {
"gt": timestamp
}
},
"... |
def lines_from_file(path):
"""Return a list of strings, one for each line in a file."""
with open(path, "r") as f:
return [line.strip() for line in f.readlines()] |
def XMLescape(txt):
"""Returns provided string with symbols & < > " replaced by their respective XML entities."""
return txt.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """) |
def get_repo_name_from_url(url):
"""
:param url:
:return: user/repo (or None if invalid)
"""
url = url.replace(' ', '')
url = url.lower().strip()
if url[:19] == "https://github.com/":
name = url[19:]
else:
name = url
print("name: "+name)
if name[-1] == "/":
... |
def parse_spec(spec, default_module):
"""Parse a spec of the form module.class:kw1=val,kw2=val.
Returns a triple of module, classname, arguments list and keyword dict.
"""
name, args = (spec.split(':', 1) + [''])[:2]
if '.' not in name:
if default_module:
module, klass = defaul... |
def divide_grid(grid):
"""Divides the length of a grid into 4 and returns a list of slice indices."""
chunksize = int(len(grid)/4)
chunk1 = (0, chunksize)
chunk2 = (chunksize, chunksize*2)
chunk3 = (chunksize*2, chunksize*3)
chunk4 = (chunksize*3, len(grid))
return [chunk1, chunk2,... |
def factorial_recursive(num):
"""returns the factorial of num using a recursive method."""
return 1 if num == 0 else num * factorial_recursive(num - 1) |
def select_top_relsent_cred(relsent):
"""Select the top available credibility source for a relsent
This will be either the domain_credibility or a normalised
claimReview_credibility_rating.
:param relsent: a SimilarSent dict
:returns: either the domain_credibility, or the claimReview_credibili... |
def unify_stringlist(L: list):
""" Adds asterisks to strings that appear multiple times, so the resulting
list has only unique strings but still the same length, order, and meaning.
For example:
unify_stringlist(['a','a','b','a','c']) -> ['a','a*','b','a**','c']
"""
assert(all([isinstance(... |
def removestringparts(matchers, listt):
"""returns cleaned list of input listt (list) and to-be-removed matchers (list)
>>> removestringparts("QQ",["QQasdf","asdfQQasdf"])
['asdf', 'asdfasdf']
>>> removestringparts(["QQ","s"],["QQasdf","asdfQQasdf"])
['adf', 'adfadf']
"""
#print("... |
def repeat(s, exclaim):
"""
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
"""
result = s + s + s # can also use "s * 3" which is faster (Why?)
#faster because * calculates len of object once, + does it each time + is called
#+ and * are called "overload... |
def dxR_calc(u,Ki_GCC):
"""Calculate derivative of current controller integral state - real component"""
dxR = Ki_GCC*u.real
return dxR |
def _property_method(class_dict, name):
""" Returns the method associated with a particular class property
getter/setter.
"""
return class_dict.get(name) |
def file_cadence(granularity):
"""Set the resolution of the file"""
if granularity < 60*60*24:
return '1D'
else:
return '1M' |
def find_local_maxima(etas, es):
"""
input: a real array es energies(eta)
output: all local maxima
"""
n = len(es)
out = []
for i in range(1,n-1):
if es[i] > es[i-1] and es[i] > es[i+1]:
out.append((etas[i],es[i]))
return out |
def exclude_tags(tag_list, *args):
"""
- Filters a tag set by Exclusion
- variable tag keys given as parameters, tag keys corresponding to args
are excluded
RETURNS
TYPE: list
"""
clean = tag_list.copy()
for tag in tag_list:
for arg in args:
if... |
def extrapolDiff(f, x, h):
"""return Ableitung der Funktion f an Stelle x
nach '1/3h *( 8*(f(x + h/4)-f(x - h/4)) - (f(x + h/2) - f(x - h/2)))'
"""
return 1/(3*h) * (8*(f(x+h/4) - f(x-h/4)) - (f(x+h/2) - f(x-h/2))) |
def ordinal(value):
"""
Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',
3 is '3rd', etc. Works for any integer.
"""
try:
value = int(value)
except (TypeError, ValueError):
return value
t = ('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th')
... |
def any(iter):
""" For < Python2.5 compatibility. """
for elem in iter:
if elem:
return True
return False |
def unique_sorted_list(nums):
"""
Returns a unique numbers in the list
in a sorted order.
List items should contain only the integers
"""
unique_list = []
for number in nums:
if number not in unique_list:
unique_list.append(number)
unique_list.sort()
return unique... |
def decimal_from_str(src):
"""Decodes a decimal from a string returning a python float value.
If string is not a valid lexical representation of a decimal value
then ValueError is raised."""
sign = False
point = False
digit = False
for c in src:
v = ord(c)
if v == 0x2B or v ... |
def tags_since_dt(sentence, i):
"""Creates a string describing the set of all part-of-speech tags\
that have been encountered since the most recent determiner.
:param sentence: Array of word and part of speech tag
:param i: Index of the actual word
"""
tags = set()
for word, pos in sentenc... |
def user_dict(user, base64_file=None):
"""Convert the user object to a result dict"""
if user:
return {
'username': user.id,
'accesskey': user.access,
'secretkey': user.secret,
'file': base64_file,
}
else:
return {} |
def calc_image_weighted_average_accuracy(dict):
"""Calculate SOA-I"""
accuracy = 0
total_images = 0
for label in dict.keys():
num_images = dict[label]["images_total"]
accuracy += num_images * dict[label]["accuracy"]
total_images += num_images
overall_accuracy = accuracy / tot... |
def get_worktime(hour_in, hour_out, check_in, check_out):
"""menghitung jam kerja minus telat dan pulang awal"""
if check_in > hour_in:
result = hour_out - check_in
elif check_out > hour_out:
result = check_out - hour_in
else:
result = hour_out - hour_in
return result |
def is_quantity_range(val: str) -> bool:
"""Checks if [] are present in val.
"""
if '[' in val and ']' in val:
return True
return False |
def hide_password(url, start=6):
"""Returns the http url with password part replaced with '*'.
:param url: URL to upload the plugin to.
:type url: str
:param start: Position of start of password.
:type start: int
"""
start_position = url.find(':', start) + 1
end_position = url.find('@'... |
def tags_as_str(tags):
"""Convert list of tags to string."""
return " ".join(tags) if tags else "all tests" |
def _make_parameters(signature):
"""Return actual parameters (that can be passed to a call) corresponding to
signature (the formal parameters). Copes with bare `*` (see PEP 3102) e.g.
shutil.copyfile's signature is now "src, dst, *, follow_symlinks=True":
return "src, dst, *, follow_symlinks=follow_syml... |
def categorical(responses):
"""Analyses categorical responses
Args:
responses(list/tuple): List/tuple of the responses
For example: ["Yes","No","Yes"] or ("Yes","No","Yes")
Returns:
A dictionary containing the sorted percentages of each response.
For example:
{"... |
def extract_hyperparameter(file_path, name, delimiter='/'):
"""Extract hyperparameter value from the file path.
Example 1:
path: '/../learning_rate=420,momentum=101/Seed45'
name: 'learning_rate='
delimiter: ','
return: '420'
Example 2:
path: '/../learning_rate420/momentum101/Seed45'
name... |
def levenshtein_1d_blocks(string, transpositions=False, flag='\x00'):
"""
Function returning the minimal set of longest Levenshtein distance <= 1
blocking keys of target string. Under the hood, this splits the given
string into an average of 3 blocks (2 when string length is even, 4 when
odd). When ... |
def bagdiff(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs):
result.extend(ys[yi:])
return result
if yi >= len(ys):
result.extend(xs[xi:])
return result
... |
def laplace(x):
"""
Product of Laplace distributions, mu=3, b=0.1.
"""
return sum(abs(xi-3.)/0.1 for xi in x) |
def str_to_bool(value):
"""Convert a string into a boolean"""
if value.lower() in ("yes", "true", "t", "1"):
return True
if value.lower() in ("no", "false", "f", "0"):
return False
return None |
def _to_lists(x):
"""
Returns lists of lists when given tuples of tuples
"""
if isinstance(x, tuple):
return [_to_lists(el) for el in x]
return x |
def preprocess_cl_line(line):
"""Process one line in the category label database file."""
name, forms = line.strip().split("\t")
forms = [form.strip() for form in forms.split(';')]
return name, forms |
def remove_empty_entries(dicts):
"""Drop keys from dicts in a list of dicts if key is falsey"""
reduced = []
for d in dicts:
new_d = {}
for key in d:
if d[key]:
new_d[key] = d[key]
reduced.append(new_d)
return reduced |
def meric_hit(h_rank, t_rank, N=50):
"""evaluate the vector result by hit-N method
N: the rate of the true entities in the topN rank
return the mean rate
"""
print('start evaluating by Hit')
num = 0
for r1 in h_rank:
if r1 <= N:
num += 1
rate_h = num / len(h_ran... |
def _StringQuote(s, quote='"', escape='\\'):
"""Returns <quote>s<quote> with <escape> and <quote> in s escaped.
s.encode('string-escape') does not work with type(s) == unicode.
Args:
s: The string to quote.
quote: The outer quote character.
escape: The enclosed escape character.
Returns:
<quo... |
def helper_concatenation(var_pre, var_post):
""" Simple helper method for concatenationg fields (Module and app/func name) """
return_val = None
if var_pre is None:
var_pre = "Not Specified"
if var_post is None:
var_post = "Not Specified"
if var_pre != "Not Specified" or var_post != ... |
def quad2list2(quad):
"""
convert to list of list
"""
return [
[quad[0]["x"], quad[0]["y"]],
[quad[1]["x"], quad[1]["y"]],
[quad[2]["x"], quad[2]["y"]],
[quad[3]["x"], quad[3]["y"]],
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.